!1 20210715代码提交

Merge pull request !1 from chensi10/master
This commit is contained in:
openharmony_ci
2021-07-15 11:31:24 +00:00
committed by Gitee
266 changed files with 29521 additions and 7893 deletions
-2
View File
@@ -13,8 +13,6 @@
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.
+14 -5
View File
@@ -32,11 +32,16 @@ config("ability_config") {
"//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",
"//foundation/communication/ipc/interfaces/innerkits/ipc_core/include",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/dispatcher",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/task",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/threading",
"//foundation/appexecfwk/standard/kits/appkit/native/app/include/task",
]
cflags = []
@@ -55,6 +60,7 @@ config("ability_public_config") {
"${INNERKITS_PATH}/base/include",
"//foundation/appexecfwk/standard/kits/appkit/native/app/include",
"${SUBSYSTEM_DIR}/include",
"//third_party/libuv/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",
@@ -83,8 +89,9 @@ ohos_shared_library("abilitykit_native") {
"${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/napi_context.cpp",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.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",
@@ -98,14 +105,13 @@ ohos_shared_library("abilitykit_native") {
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/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//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",
@@ -117,7 +123,10 @@ ohos_shared_library("abilitykit_native") {
"ipc:ipc_core",
]
public_deps = [ "//foundation/graphic/standard:libwms_client" ]
public_deps = [
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr",
"//foundation/graphic/standard:libwms_client",
]
subsystem_name = "aafwk"
part_name = "aafwk_standard"
@@ -31,11 +31,9 @@
#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"
@@ -297,6 +295,21 @@ public:
*/
virtual void SetUIContent(int layoutRes, std::shared_ptr<Context> &context, int typeFlag);
/**
* @brief Called when this ability gains or loses window focus.
*
* @param hasFocus Specifies whether this ability has focus.
*/
virtual void OnWindowFocusChanged(bool hasFocus);
/**
* @brief Called when this ability is moved to or removed from the top of the stack.
*
* @param topActive Specifies whether this ability is moved to or removed from the top of the stack. The value true
* indicates that it is moved to the top, and false indicates that it is removed from the top of the stack.
*/
virtual void OnTopActiveAbilityChanged(bool topActive);
#ifdef WMS_COMPILE
/**
* @brief Inflates UI controls by using WindowConfig.
@@ -502,20 +515,6 @@ public:
*/
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().
*
@@ -828,6 +827,19 @@ public:
*/
void PostTask(std::function<void()> task, long delayTime);
/**
* @brief Called to set caller information for the application. The default implementation returns null.
*
* @return Returns the caller information.
*/
virtual Uri OnSetCaller();
/**
* @brief Call this when your ability should be closed and the mission should be completely removed as a part of
* finishing the root ability of the mission.
*/
void TerminateAndRemoveMission() override;
private:
std::shared_ptr<AbilityInfo> abilityInfo_ = nullptr;
std::shared_ptr<Context> context_;
File diff suppressed because it is too large Load Diff
+7
View File
@@ -334,6 +334,13 @@ protected:
*/
void SerUriString(const std::string &uri);
/**
* @brief Set the LifeCycleStateInfo to the deal.
*
* @param info the info to set.
*/
void SetLifeCycleStateInfo(const AAFwk::LifeCycleStateInfo &info);
int lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL;
sptr<IRemoteObject> token_;
std::shared_ptr<Ability> ability_;
@@ -255,6 +255,12 @@ public:
*/
int BatchInsert(const Uri &uri, const std::vector<ValuesBucket> &values);
/**
* @brief Displays a system-defined message to the user, prompting the user how to exit the lock mission mode.
*
*/
void DisplayUnlockMissionMessage();
private:
/**
* @description: Create the abilityname.
+49 -17
View File
@@ -87,13 +87,19 @@ void Ability::OnStart(const Want &want)
if (abilityInfo_->bundleName == SYSTEM_UI) {
if (abilityInfo_->name == STATUS_BAR) {
config.type = OHOS::WindowType::WINDOW_TYPE_STATUS_BAR;
APP_LOGI("Ability::OnStart STATUS_BAR : set config.type = %{public}d", config.type);
}
if (abilityInfo_->name == NAVIGATION_BAR) {
config.type = OHOS::WindowType::WINDOW_TYPE_NAVI_BAR;
APP_LOGI("Ability::OnStart NAVIGATION_BAR : set config.type = %{public}d", config.type);
}
}
if (abilityInfo_->bundleName == OHOS_REQUEST_PERMISSION_BUNDLENAME &&
abilityInfo_->name == OHOS_REQUEST_PERMISSION_ABILITY_NAME) {
config.type = OHOS::WindowType::WINDOW_TYPE_ALARM_SCREEN;
}
APP_LOGI("Ability::OnStart bundleName:%{public}s abilityName:%{public}s: set config.type = %{public}d",
abilityInfo_->bundleName.c_str(),
abilityInfo_->name.c_str(),
config.type);
SetUIContent(config);
if (abilityWindow_ != nullptr) {
@@ -740,21 +746,6 @@ void Ability::OnSaveAbilityState(PacMap &outState)
void Ability::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.
*/
void Ability::OnWindowFocusChanged(bool hasFocus)
{}
/**
* @brief Sets the want object that can be obtained by calling getWant().
* @param Want information of other ability
@@ -1265,5 +1256,46 @@ void Ability::PostTask(std::function<void()> task, long delayTime)
TaskHandlerClient::GetInstance()->PostTask(task, delayTime);
}
/**
* @brief Called when this ability gains or loses window focus.
*
* @param hasFocus Specifies whether this ability has focus.
*/
void Ability::OnWindowFocusChanged(bool hasFocus)
{}
/**
* @brief Called when this ability is moved to or removed from the top of the stack.
*
* @param topActive Specifies whether this ability is moved to or removed from the top of the stack. The value true
* indicates that it is moved to the top, and false indicates that it is removed from the top of the stack.
*/
void Ability::OnTopActiveAbilityChanged(bool topActive)
{}
/**
* @brief Called to set caller information for the application. The default implementation returns null.
*
* @return Returns the caller information.
*/
Uri Ability::OnSetCaller()
{
return Uri("");
}
/**
* @brief Call this when your ability should be closed and the mission should be completely removed as a part of
* finishing the root ability of the mission.
*/
void Ability::TerminateAndRemoveMission()
{
auto state = GetState();
if (state > AbilityLifecycleExecutor::LifecycleState::INITIAL) {
APP_LOGI("Ability::TerminateAndRemoveMission the GetState retval is %d", state);
return;
}
AbilityContext::TerminateAndRemoveMission();
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -18,9 +18,15 @@
#include "app_log_wrapper.h"
#include "resource_manager.h"
#include "bundle_constants.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
#include "sys_mgr_client.h"
namespace OHOS {
namespace AppExecFwk {
int AbilityContext::ABILITY_CONTEXT_DEFAULT_REQUEST_CODE(0);
/**
* @brief Starts a new ability.
* An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method
@@ -37,7 +43,7 @@ namespace AppExecFwk {
*/
void AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode)
{
APP_LOGI("AbilityContext::StartAbility called");
APP_LOGI("AbilityContext::StartAbility called, requestCode = %{public}d", requestCode);
AppExecFwk::AbilityType type = GetAbilityInfoType();
if (type != AppExecFwk::AbilityType::PAGE && type != AppExecFwk::AbilityType::SERVICE) {
@@ -45,9 +51,24 @@ void AbilityContext::StartAbility(const AAFwk::Want &want, int requestCode)
return;
}
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, requestCode);
if (err != ERR_OK) {
APP_LOGE("AbilityContext::StartAbility is failed %{public}d", err);
if (CheckIfOperateRemote(want)) {
std::shared_ptr<OHOS::DistributedSchedule::DistributedSchedProxy> dms = GetDistributedSchedServiceProxy();
if (dms != nullptr) {
AAFwk::Want innerWant;
APP_LOGI("AbilityContext::StartAbility. try to StartRemoteAbility");
int result = dms->StartRemoteAbility(want, innerWant, requestCode);
if (result != ERR_NONE) {
APP_LOGE("AbilityContext::StartAbility start remote ability failed, the result is %{public}d", result);
}
} else {
APP_LOGE("AbilityContext::StartAbility failed. It wants to start a remote ability, but failed to get dms.");
return;
}
} else {
ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, requestCode);
if (err != ERR_OK) {
APP_LOGE("AbilityContext::StartAbility is failed %{public}d", err);
}
}
}
@@ -600,7 +621,11 @@ bool AbilityContext::CanRequestPermission(const std::string &permission)
*/
int AbilityContext::VerifyCallingOrSelfPermission(const std::string &permission)
{
return VerifySelfPermission(permission);
if (VerifyCallingPermission(permission) != AppExecFwk::Constants::PERMISSION_GRANTED) {
return VerifySelfPermission(permission);
} else {
return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
}
}
/**
@@ -634,6 +659,20 @@ int AbilityContext::VerifyPermission(const std::string &permission, int pid, int
return ptr->CheckPermission(bundle_name, permission);
}
void AbilityContext::GetPermissionDes(const std::string &permissionName, std::string &des)
{
sptr<IBundleMgr> ptr = GetBundleManager();
if (ptr == nullptr) {
APP_LOGE("GetPermissionDes failed to get bundle manager service");
return;
}
PermissionDef permissionDef;
if (ptr->GetPermissionDef(permissionName, permissionDef)) {
des = permissionDef.description;
}
}
/**
* @brief Requests certain permissions from the system.
* This method is called for permission request. This is an asynchronous method. When it is executed,
@@ -655,11 +694,21 @@ void AbilityContext::RequestPermissionsFromUser(std::vector<std::string> &permis
return;
}
std::vector<std::string> permissionDes;
std::string des;
for (size_t i = 0; i < permissions.size(); i++) {
des = "";
GetPermissionDes(permissions[i], des);
permissionDes.push_back(des);
}
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());
want.SetElementName(OHOS_REQUEST_PERMISSION_BUNDLENAME, OHOS_REQUEST_PERMISSION_ABILITY_NAME);
want.SetParam(OHOS_REQUEST_PERMISSION_KEY, OHOS_REQUEST_PERMISSION_VALUE);
want.SetParam(OHOS_REQUEST_PERMISSIONS_LIST, permissions);
want.SetParam(OHOS_REQUEST_PERMISSIONS_DES_LIST, permissionDes);
want.SetParam(OHOS_REQUEST_CALLER_BUNDLERNAME, GetBundleName());
StartAbility(want, requestCode);
}
@@ -826,5 +875,303 @@ void AbilityContext::InitResourceManager(BundleInfo &bundleInfo, std::shared_ptr
{
ContextContainer::InitResourceManager(bundleInfo, deal);
}
/**
* @brief Get the string of this Context based on the specified resource ID.
*
* @param resId Indicates the resource ID of the string to get.
*
* @return Returns the string of this Context.
*/
std::string AbilityContext::GetString(int resId)
{
return ContextContainer::GetString(resId);
}
/**
* @brief Get the string array of this Context based on the specified resource ID.
*
* @param resId Indicates the resource ID of the string array to get.
*
* @return Returns the string array of this Context.
*/
std::vector<std::string> AbilityContext::GetStringArray(int resId)
{
return ContextContainer::GetStringArray(resId);
}
/**
* @brief Get the integer array of this Context based on the specified resource ID.
*
* @param resId Indicates the resource ID of the integer array to get.
*
* @return Returns the integer array of this Context.
*/
std::vector<int> AbilityContext::GetIntArray(int resId)
{
return ContextContainer::GetIntArray(resId);
}
/**
* @brief Obtains the theme of this Context.
*
* @return theme Returns the theme of this Context.
*/
std::map<std::string, std::string> AbilityContext::GetTheme()
{
return ContextContainer::GetTheme();
}
/**
* @brief Sets the theme of this Context based on the specified theme ID.
*
* @param themeId Indicates the resource ID of the theme to set.
*/
void AbilityContext::SetTheme(int themeId)
{
ContextContainer::SetTheme(themeId);
}
/**
* @brief Obtains the pattern of this Context.
*
* @return getPattern in interface Context
*/
std::map<std::string, std::string> AbilityContext::GetPattern()
{
return ContextContainer::GetPattern();
}
/**
* @brief Get the color of this Context based on the specified resource ID.
*
* @param resId Indicates the resource ID of the color to get.
*
* @return Returns the color value of this Context.
*/
int AbilityContext::GetColor(int resId)
{
return ContextContainer::GetColor(resId);
}
/**
* @brief Obtains the theme id of this Context.
*
* @return int Returns the theme id of this Context.
*/
int AbilityContext::GetThemeId()
{
return ContextContainer::GetThemeId();
}
/**
* @brief
* Destroys this Service ability if the number of times it has been started equals the number represented by the
* given {@code startId}. This method is the same as calling {@link #terminateAbility} to destroy this Service
* ability, except that this method helps you avoid destroying it if a client has requested a Service
* ability startup in {@link ohos.aafwk.ability.Ability#onCommand} but you are unaware of it.
*
* @param startId Indicates the number of startup times of this Service ability passed to
* {@link ohos.aafwk.ability.Ability#onCommand}. The {@code startId} is
* incremented by 1 every time this ability is started. For example,
* if this ability has been started for six times, the value of {@code startId} is {@code 6}.
*
* @return Returns {@code true} if the {@code startId} matches the number of startup times
* and this Service ability will be destroyed; returns {@code false} otherwise.
*/
bool AbilityContext::TerminateAbilityResult(int startId)
{
auto abilityClient = AAFwk::AbilityManagerClient::GetInstance();
if (abilityClient == nullptr) {
APP_LOGE("AbilityContext::TerminateAbilityResult abilityClient is nullptr");
return false;
}
ErrCode errval = abilityClient->TerminateAbilityResult(token_, startId);
return (errval == ERR_OK) ? true : false;
}
/**
* @brief Obtains the current display orientation of this ability.
*
* @return Returns the current display orientation.
*/
int AbilityContext::GetDisplayOrientation()
{
return ContextContainer::GetDisplayOrientation();
}
/**
* @brief Obtains the path storing the preference file of the application.
* If the preference file path does not exist, the system creates one and returns the created path.
*
* @return Returns the preference file path .
*/
std::string AbilityContext::GetPreferencesDir()
{
return ContextContainer::GetPreferencesDir();
}
/**
* @brief Set color mode
*
* @param the value of color mode.
*/
void AbilityContext::SetColorMode(int mode)
{
ContextContainer::SetColorMode(mode);
}
/**
* @brief Obtains color mode.
*
* @return Returns the color mode value.
*/
int AbilityContext::GetColorMode()
{
return ContextContainer::GetColorMode();
}
/**
* @brief Obtains the unique ID of the mission containing this ability.
*
* @return Returns the unique mission ID.
*/
int AbilityContext::GetMissionId()
{
return ContextContainer::GetMissionId();
}
/**
* @brief Call this when your ability should be closed and the mission should be completely removed as a part of
* finishing the root ability of the mission.
*/
void AbilityContext::TerminateAndRemoveMission()
{
ContextContainer::TerminateAndRemoveMission();
}
/**
* @brief Starts multiple abilities.
*
* @param wants Indicates the Want containing information array about the target ability to start.
*/
void AbilityContext::StartAbilities(const std::vector<AAFwk::Want> &wants)
{
for (auto want : wants) {
StartAbility(want, ABILITY_CONTEXT_DEFAULT_REQUEST_CODE);
}
}
/**
* @brief Checks whether this ability is the first ability in a mission.
*
* @return Returns true is first in Mission.
*/
bool AbilityContext::IsFirstInMission()
{
auto abilityClient = AAFwk::AbilityManagerClient::GetInstance();
if (abilityClient == nullptr) {
APP_LOGE("AbilityContext::IsFirstInMission abilityClient is nullptr");
return false;
}
ErrCode errval = abilityClient->IsFirstInMission(token_);
return (errval == ERR_OK) ? true : false;
}
/**
* @brief Check whether it wants to operate a remote ability
*
* @param want Indicates the Want containing information about the ability to start.
*
* @return return true if it wamts to operate a remote ability, ohterwise return false.
*/
bool AbilityContext::CheckIfOperateRemote(const Want &want)
{
if (want.GetElement().GetDeviceID() != "") {
return true;
}
return false;
}
/**
* @brief Obtains a distributedSchedService.
*
* @return Returns an IDistributedSched proxy.
*/
std::shared_ptr<OHOS::DistributedSchedule::DistributedSchedProxy> AbilityContext::GetDistributedSchedServiceProxy()
{
auto remoteObject = OHOS::DelayedSingleton<SysMrgClient>::GetInstance()->GetSystemAbility(DISTRIBUTED_SCHED_SA_ID);
if (remoteObject == nullptr) {
APP_LOGE("failed to get dms service");
return nullptr;
}
APP_LOGI("get dms proxy success.");
std::shared_ptr<OHOS::DistributedSchedule::DistributedSchedProxy> proxy = nullptr;
proxy = std::make_shared<OHOS::DistributedSchedule::DistributedSchedProxy>(remoteObject);
return proxy;
}
/**
* @brief Obtains a task dispatcher that is bound to the UI thread.
*
* @return Returns the task dispatcher that is bound to the UI thread.
*/
std::shared_ptr<TaskDispatcher> AbilityContext::GetUITaskDispatcher()
{
return ContextContainer::GetUITaskDispatcher();
}
/**
* @brief Obtains a task dispatcher that is bound to the application main thread.
*
* @return Returns the task dispatcher that is bound to the application main thread.
*/
std::shared_ptr<TaskDispatcher> AbilityContext::GetMainTaskDispatcher()
{
return ContextContainer::GetMainTaskDispatcher();
}
/**
* @brief Creates a parallel task dispatcher with a specified priority.
*
* @param name Indicates the task dispatcher name. This parameter is used to locate problems.
* @param priority Indicates the priority of all tasks dispatched by the parallel task dispatcher.
*
* @return Returns a parallel task dispatcher.
*/
std::shared_ptr<TaskDispatcher> AbilityContext::CreateParallelTaskDispatcher(
const std::string &name, const TaskPriority &priority)
{
return ContextContainer::CreateParallelTaskDispatcher(name, priority);
}
/**
* @brief Creates a serial task dispatcher with a specified priority.
*
* @param name Indicates the task dispatcher name. This parameter is used to locate problems.
* @param priority Indicates the priority of all tasks dispatched by the created task dispatcher.
*
* @return Returns a serial task dispatcher.
*/
std::shared_ptr<TaskDispatcher> AbilityContext::CreateSerialTaskDispatcher(
const std::string &name, const TaskPriority &priority)
{
return ContextContainer::CreateSerialTaskDispatcher(name, priority);
}
/**
* @brief Obtains a global task dispatcher with a specified priority.
*
* @param priority Indicates the priority of all tasks dispatched by the global task dispatcher.
*
* @return Returns a global task dispatcher.
*/
std::shared_ptr<TaskDispatcher> AbilityContext::GetGlobalTaskDispatcher(const TaskPriority &priority)
{
return ContextContainer::GetGlobalTaskDispatcher(priority);
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -98,6 +98,12 @@ void AbilityImpl::Active()
APP_LOGD("AbilityImpl::Active");
ability_->OnActive();
if ((lifecycleState_ == AAFwk::ABILITY_STATE_INACTIVE) && (ability_->GetAbilityInfo()->type == AbilityType::PAGE)) {
ability_->OnTopActiveAbilityChanged(true);
ability_->OnWindowFocusChanged(true);
}
lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE;
abilityLifecycleCallbacks_->OnAbilityActive(ability_);
}
@@ -116,6 +122,12 @@ void AbilityImpl::Inactive()
APP_LOGD("AbilityImpl::Inactive");
ability_->OnInactive();
if ((lifecycleState_ == AAFwk::ABILITY_STATE_ACTIVE) && (ability_->GetAbilityInfo()->type == AbilityType::PAGE)) {
ability_->OnTopActiveAbilityChanged(false);
ability_->OnWindowFocusChanged(false);
}
lifecycleState_ = AAFwk::ABILITY_STATE_INACTIVE;
abilityLifecycleCallbacks_->OnAbilityInactive(ability_);
}
@@ -328,15 +340,28 @@ void AbilityImpl::SendResult(int requestCode, int resultCode, const Want &result
return;
}
if (resultData.HasParameter(OHOS_PERMISSIONS_REQUEST_RESULT_KEY) &&
resultData.HasParameter(OHOS_PERMISSIONS_REQUEST_KEY)) {
if (resultData.HasParameter(OHOS_RESULT_PERMISSION_KEY) && resultData.HasParameter(OHOS_RESULT_PERMISSIONS_LIST) &&
resultData.HasParameter(OHOS_RESULT_CALLER_BUNDLERNAME)) {
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);
if (resultCode > 0) {
std::vector<std::string> permissions = resultData.GetStringArrayParam(OHOS_RESULT_PERMISSIONS_LIST);
std::vector<std::string> grantYes = resultData.GetStringArrayParam(OHOS_RESULT_PERMISSIONS_LIST_YES);
std::vector<std::string> grantNo = resultData.GetStringArrayParam(OHOS_RESULT_PERMISSIONS_LIST_NO);
std::vector<int> grantResult;
int intOK = 0;
for (size_t i = 0; i < permissions.size(); i++) {
intOK = 0;
for (size_t j = 0; j < grantYes.size(); j++) {
if (permissions[i] == grantYes[j]) {
intOK = 1;
break;
}
}
grantResult.push_back(intOK);
}
ability_->OnRequestPermissionsFromUserResult(requestCode, permissions, grantResult);
} else {
APP_LOGE("AbilityImpl::SendResult Grand failed, data error!");
APP_LOGE("AbilityImpl::SendResult user cancel permissions");
}
} else {
ability_->OnAbilityResult(requestCode, resultCode, resultData);
@@ -514,6 +539,20 @@ void AbilityImpl::SerUriString(const std::string &uri)
contextDeal_->SerUriString(uri);
}
/**
* @brief Set the LifeCycleStateInfo to the deal.
*
* @param info the info to set.
*/
void AbilityImpl::SetLifeCycleStateInfo(const AAFwk::LifeCycleStateInfo &info)
{
if (contextDeal_ == nullptr) {
APP_LOGE("AbilityImpl::SetLifeCycleStateInfo contextDeal_ is nullptr");
return;
}
contextDeal_->SetLifeCycleStateInfo(info);
}
/**
* @brief Set deviceId/bundleName/abilityName of the calling ability
*
+8 -2
View File
@@ -110,6 +110,7 @@ std::shared_ptr<ContextDeal> AbilityThread::CreateAndInitContextDeal(std::shared
contextDeal->SetBundleCodePath(abilityRecord->GetAbilityInfo()->codePath);
contextDeal->SetContext(abilityObject);
contextDeal->SetRunner(abilityHandler_->GetEventRunner());
return contextDeal;
}
@@ -145,12 +146,12 @@ void AbilityThread::Attach(std::shared_ptr<OHOSApplication> &application,
}
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<Context> abilityObject = currentAbility_;
std::shared_ptr<ContextDeal> contextDeal = CreateAndInitContextDeal(application, abilityRecord, abilityObject);
ability->AttachBaseContext(contextDeal);
@@ -207,12 +208,12 @@ void AbilityThread::Attach(
}
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<Context> abilityObject = currentAbility_;
std::shared_ptr<ContextDeal> contextDeal = CreateAndInitContextDeal(application, abilityRecord, abilityObject);
ability->AttachBaseContext(contextDeal);
@@ -726,6 +727,11 @@ int AbilityThread::BatchInsert(const Uri &uri, const std::vector<ValuesBucket> &
return ret;
}
void AbilityThread::DisplayUnlockMissionMessage()
{
APP_LOGI("DisplayUnlockMissionMessage...");
}
/**
* @description: Attach The ability thread to the main process.
* @param application Indicates the main process.
+3 -1
View File
@@ -93,7 +93,9 @@ bool AbilityWindow::OnKeyEvent(KeyEvent event)
switch (event.GetKeyCode()) {
case KeyEvent::CODE_BACK:
APP_LOGI("AbilityWindow::OnKeyEvent Back key pressed.");
ret = OnBackPressed(ability);
if (!event.IsKeyDown()) {
ret = OnBackPressed(ability);
}
break;
default:
APP_LOGI("AbilityWindow::OnKeyEvent the key event is %{public}d.", event.GetKeyCode());
+2
View File
@@ -37,6 +37,8 @@ void PageAbilityImpl::HandleAbilityTransaction(const Want &want, const AAFwk::Li
return;
}
SetLifeCycleStateInfo(targetState);
if (lifecycleState_ == AAFwk::ABILITY_STATE_INITIAL) {
Start(want);
}
+132 -95
View File
@@ -39,6 +39,12 @@ config("module_private_config") {
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include",
"//foundation/aafwk/standard/frameworks/kits/ability/native/include",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include",
"//foundation/aafwk/standard/services/common/include",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/dispatcher",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/task",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/threading",
"//foundation/appexecfwk/standard/kits/appkit/native/app/include/task",
]
cflags = []
if (target_cpu == "arm") {
@@ -54,14 +60,24 @@ 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/interfaces/innerkits/want/include/ohos/aafwk/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",
"//foundation/aafwk/standard/frameworks/kits/ability/native/include",
"//foundation/appexecfwk/standard/kits/appkit/native/app/include",
"//foundation/communication/ipc/interfaces/innerkits/ipc_core/include",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event/include",
"//foundation/aafwk/standard/interfaces/innerkits/base/include",
"//third_party/libuv/include",
"//foundation/aafwk/standard/interfaces/innerkits/base/include/ohos/aafwk/base",
"//base/global/resmgr_standard/interfaces/innerkits/include",
"//foundation/graphic/standard/interfaces/innerkits/wm",
"//foundation/graphic/standard/interfaces/innerkits/surface",
"//foundation/graphic/standard/utils/include",
]
cflags = []
if (target_cpu == "arm") {
@@ -76,7 +92,6 @@ config("module_ability_context_config") {
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",
@@ -96,6 +111,8 @@ ohos_unittest("ability_test") {
"//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/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/graphic/standard:libwms_client",
"//foundation/multimodalinput/input/interfaces/native/innerkits/event:mmi_event",
@@ -171,10 +188,73 @@ ohos_unittest("ability_lifecycle_executor_test") {
]
}
ohos_unittest("ability_context_for_task_dispacher_test") {
module_out_path = module_output_path
sources = [ "unittest/ability_context_for_task_dispacher_test.cpp" ]
include_dirs = [ "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include" ]
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/frameworks/kits/ability/native:dummy_classes",
"//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/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//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("ability_context_interface_test") {
module_out_path = module_output_path
sources = [
"mock/include/mock_ability_manager_client_interface1.cpp",
"mock/include/mock_resourceManager_interface1.cpp",
"unittest/ability_context_interface1_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/frameworks/kits/ability/native:dummy_classes",
"//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("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_clientex.cpp",
"mock/include/mock_ability_manager_service.cpp",
"mock/include/mock_bundle_manager.cpp",
"mock/include/sys_mgr_client_mock.cpp",
@@ -187,7 +267,7 @@ ohos_unittest("ability_context_test") {
"${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/frameworks/kits/ability/native:dummy_classes",
"//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",
@@ -301,10 +381,44 @@ ohos_unittest("data_ability_helper_test") {
]
}
ohos_unittest("ability_impl_active_test") {
module_out_path = module_output_path
sources = [
"//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_active_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/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//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_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",
@@ -322,6 +436,8 @@ ohos_unittest("ability_impl_test") {
"//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/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
@@ -339,23 +455,6 @@ ohos_unittest("ability_impl_test") {
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",
@@ -381,6 +480,8 @@ ohos_unittest("ability_thread_test") {
"//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/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
@@ -399,23 +500,6 @@ ohos_unittest("ability_thread_test") {
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",
@@ -438,6 +522,8 @@ ohos_unittest("data_ability_impl_test") {
"//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/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
@@ -456,23 +542,6 @@ ohos_unittest("data_ability_impl_test") {
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",
@@ -495,6 +564,8 @@ ohos_unittest("data_ability_impl_file_secondpart_test") {
"//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/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
@@ -513,23 +584,6 @@ ohos_unittest("data_ability_impl_file_secondpart_test") {
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",
@@ -552,6 +606,8 @@ ohos_unittest("data_ability_impl_file_test") {
"//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/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
@@ -570,23 +626,6 @@ ohos_unittest("data_ability_impl_file_test") {
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",
@@ -612,6 +651,8 @@ ohos_unittest("ability_thread_dataability_test") {
"//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/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
@@ -702,7 +743,6 @@ 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",
@@ -715,7 +755,6 @@ ohos_unittest("ability_permission_test") {
"//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",
@@ -744,8 +783,6 @@ ohos_unittest("task_handler_client_test") {
"//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" ]
@@ -83,6 +83,20 @@ public:
};
};
class OnPermissionChangedCallback : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.OnPermissionChangedCallback");
/**
* @brief Called when an application's permission changed.
* @param uid Indicates the uid of the application which permission changed.
*/
virtual void OnChanged(const int32_t uid) = 0;
enum class Message {
ON_CHANGED,
};
};
class IStatusReceiver : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.StatusReceiver");
@@ -143,24 +157,23 @@ public:
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 std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) = 0;
virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) = 0;
virtual bool GetBundlesForUid(const int uid, std::vector<std::string> &bundleNames) = 0;
virtual bool GetNameForUid(const int uid, std::string &name) = 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 QueryAbilityInfoByUri(const std::string &abilityUri, 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 GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) = 0;
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;
@@ -169,23 +182,74 @@ public:
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 IsApplicationEnabled(const std::string &bundleName) = 0;
virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) = 0;
virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) = 0;
virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) = 0;
virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) = 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;
virtual bool RegisterAllPermissionsChanged(const sptr<OnPermissionChangedCallback> &callback) = 0;
virtual bool RegisterPermissionsChanged(
const std::vector<int> &uids, const sptr<OnPermissionChangedCallback> &callback) = 0;
virtual bool UnregisterPermissionsChanged(const sptr<OnPermissionChangedCallback> &callback) = 0;
virtual sptr<IBundleInstaller> GetBundleInstaller() = 0;
enum class Message {
QUERY_ABILITY_INFO,
GET_APPLICATION_INFO,
GET_APPLICATION_INFOS,
GET_BUNDLE_INFO,
GET_BUNDLE_INFOS,
GET_UID_BY_BUNDLE_NAME,
GET_APPID_BY_BUNDLE_NAME,
GET_BUNDLE_NAME_FOR_UID,
GET_BUNDLES_FOR_UID,
GET_NAME_FOR_UID,
GET_BUNDLE_GIDS,
GET_APP_TYPE,
CHECK_IS_SYSTEM_APP_BY_UID,
GET_BUNDLE_INFOS_BY_METADATA,
QUERY_ABILITY_INFO,
QUERY_ABILITY_INFO_BY_URI,
QUERY_KEEPALIVE_BUNDLE_INFOS,
GET_ABILITY_LABEL,
GET_BUNDLE_ARCHIVE_INFO,
GET_HAP_MODULE_INFO,
GET_LAUNCH_WANT_FOR_BUNDLE,
CHECK_PUBLICKEYS,
CHECK_PERMISSION,
GET_PERMISSION_DEF,
GET_ALL_PERMISSION_GROUP_DEFS,
GET_APPS_GRANTED_PERMISSIONS,
HAS_SYSTEM_CAPABILITY,
GET_SYSTEM_AVAILABLE_CAPABILITIES,
IS_SAFE_MODE,
CLEAN_BUNDLE_CACHE_FILES,
CLEAN_BUNDLE_DATA_FILES,
REGISTER_BUNDLE_STATUS_CALLBACK,
CLEAR_BUNDLE_STATUS_CALLBACK,
UNREGISTER_BUNDLE_STATUS_CALLBACK,
DUMP_INFOS,
IS_APPLICATION_ENABLED,
SET_APPLICATION_ENABLED,
IS_ABILITY_ENABLED,
SET_ABILITY_ENABLED,
GET_ABILITY_ICON,
CAN_REQUEST_PERMISSION,
REQUEST_PERMISSION_FROM_USER,
REGISTER_ALL_PERMISSIONS_CHANGED,
REGISTER_PERMISSIONS_CHANGED,
UNREGISTER_PERMISSIONS_CHANGED,
GET_BUNDLE_INSTALLER,
};
};
} // namespace AppExecFwk
@@ -19,18 +19,18 @@
namespace OHOS {
namespace AAFwk {
std::shared_ptr<AbilityManagerClient> AbilityManagerClient::instance_ = nullptr;
std::mutex AbilityManagerClient::mutex_;
std::shared_ptr<AbilityManagerClient> mockInstance_ = nullptr;
std::mutex mockMutex_;
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>();
if (mockInstance_ == nullptr) {
std::lock_guard<std::mutex> lock_l(mockMutex_);
if (mockInstance_ == nullptr) {
mockInstance_ = std::make_shared<AbilityManagerClient>();
}
}
return instance_;
return mockInstance_;
}
AbilityManagerClient::AbilityManagerClient()
@@ -133,6 +133,9 @@ public:
{
return "Type1";
}
void DisplayUnlockMissionMessage()
{}
};
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,325 @@
/*
* 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 <singleton.h>
#include <gtest/gtest.h>
#include "gmock/gmock.h"
#include "string_ex.h"
#include "ability_manager_interface.h"
#include "ability_context.h"
#include "mock_ability_manager_client_interface1.h"
namespace OHOS {
namespace AAFwk {
MockAbilityManagerClient::MockAbilityManagerClient()
{
startAbility_ = ERR_INVALID_OPERATION;
terminateAbility_ = ERR_INVALID_OPERATION;
terminateAbilityResult_ = ERR_INVALID_OPERATION;
isFirstInMission_ = ERR_INVALID_OPERATION;
removeMissionsE_ = ERR_INVALID_OPERATION;
terminateAbilityValue_ = 0;
removeMissions_ = 0;
}
MockAbilityManagerClient::~MockAbilityManagerClient()
{}
std::shared_ptr<MockAbilityManagerClient> MockAbilityManagerClient::mock_instance_ = nullptr;
bool MockAbilityManagerClient::mock_intanceIsNull_ = true;
std::shared_ptr<MockAbilityManagerClient> MockAbilityManagerClient::GetInstance()
{
if (mock_instance_ == nullptr) {
mock_instance_ = std::make_shared<MockAbilityManagerClient>();
}
return mock_instance_;
}
void MockAbilityManagerClient::SetInstanceNull(bool flag)
{
mock_intanceIsNull_ = flag;
}
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_ = MockAbilityManagerClient::GetInstance();
}
}
if (MockAbilityManagerClient::mock_intanceIsNull_)
return instance_;
else
return nullptr;
}
AbilityManagerClient::AbilityManagerClient()
{}
AbilityManagerClient::~AbilityManagerClient()
{}
ErrCode AbilityManagerClient::AttachAbilityThread(
const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::AbilityTransitionDone(const sptr<IRemoteObject> &token, int state)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::ScheduleConnectAbilityDone(
const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)
{
return ERR_OK;
}
void AbilityManagerClient::AddWindowInfo(const sptr<IRemoteObject> &token, int32_t windowToken)
{
return;
}
ErrCode AbilityManagerClient::TerminateAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::ConnectAbility(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::DisconnectAbility(const sptr<IAbilityConnection> &connect)
{
return ERR_OK;
}
sptr<IAbilityScheduler> AbilityManagerClient::AcquireDataAbility(
const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken)
{
return nullptr;
}
ErrCode AbilityManagerClient::ReleaseDataAbility(
sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::DumpState(const std::string &args, std::vector<std::string> &state)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::Connect()
{
return ERR_OK;
}
ErrCode AbilityManagerClient::GetAllStackInfo(StackInfo &stackInfo)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::StopServiceAbility(const Want &want)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::GetRecentMissions(
const int32_t numMax, const int32_t flags, std::vector<AbilityMissionInfo> &recentList)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::GetMissionSnapshot(const int32_t missionId, MissionSnapshotInfo &snapshot)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::MoveMissionToTop(int32_t missionId)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::RemoveMissions(std::vector<int> missionId)
{
ErrCode ret = MockAbilityManagerClient::GetInstance()->GetRemoveMissions();
if (ret == ERR_OK) {
MockAbilityManagerClient::GetInstance()->ChangeRemoveMissionsValue();
}
return ret;
}
ErrCode AbilityManagerClient::RemoveStack(int id)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::KillProcess(const std::string &bundleName)
{
return ERR_OK;
}
ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode)
{
return MockAbilityManagerClient::GetInstance()->GetStartAbility();
}
ErrCode AbilityManagerClient::StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken, int requestCode)
{
return MockAbilityManagerClient::GetInstance()->GetStartAbility();
}
ErrCode AbilityManagerClient::TerminateAbility(const sptr<IRemoteObject> &callerToken, int requestCode)
{
MockAbilityManagerClient::GetInstance()->SetTerminateAbilityValue(requestCode);
return MockAbilityManagerClient::GetInstance()->GetTerminateAbility();
}
ErrCode AbilityManagerClient::TerminateAbilityResult(const sptr<IRemoteObject> &token, int startId)
{
return MockAbilityManagerClient::GetInstance()->GetTerminateAbilityResult();
}
ErrCode AbilityManagerClient::IsFirstInMission(const sptr<IRemoteObject> &token)
{
return MockAbilityManagerClient::GetInstance()->GetIsFirstInMission();
}
ErrCode MockAbilityManagerClient::GetStartAbility()
{
return startAbility_;
}
ErrCode MockAbilityManagerClient::GetTerminateAbility()
{
return terminateAbility_;
}
ErrCode MockAbilityManagerClient::GetTerminateAbilityResult()
{
return terminateAbilityResult_;
}
ErrCode MockAbilityManagerClient::GetIsFirstInMission()
{
return isFirstInMission_;
}
ErrCode MockAbilityManagerClient::GetRemoveMissions()
{
return removeMissionsE_;
}
void MockAbilityManagerClient::SetStartAbility(ErrCode tValue)
{
startAbility_ = tValue;
}
void MockAbilityManagerClient::SetTerminateAbility(ErrCode tValue)
{
terminateAbility_ = tValue;
}
void MockAbilityManagerClient::SetTerminateAbilityResult(ErrCode tValue)
{
terminateAbilityResult_ = tValue;
}
void MockAbilityManagerClient::SetIsFirstInMission(ErrCode tValue)
{
isFirstInMission_ = tValue;
}
void MockAbilityManagerClient::SetRemoveMissions(ErrCode tValue)
{
removeMissionsE_ = tValue;
}
int MockAbilityManagerClient::GetTerminateAbilityValue()
{
return terminateAbilityValue_;
}
void MockAbilityManagerClient::SetTerminateAbilityValue(int nValue)
{
terminateAbilityValue_ = nValue;
}
int MockAbilityManagerClient::GetRemoveMissionsValue()
{
return removeMissions_;
}
void MockAbilityManagerClient::ChangeRemoveMissionsValue()
{
++removeMissions_;
}
} // namespace AAFwk
} // namespace OHOS
namespace OHOS {
namespace AppExecFwk {
MockAbilityContextDeal::MockAbilityContextDeal()
{
hapModInfo_ = nullptr;
}
MockAbilityContextDeal::~MockAbilityContextDeal()
{}
std::shared_ptr<AppExecFwk::HapModuleInfo> MockAbilityContextDeal::GetHapModuleInfo()
{
if (hapModInfo_ == nullptr) {
hapModInfo_ = std::make_shared<AppExecFwk::HapModuleInfo>();
}
return hapModInfo_;
}
MockAbilityContextTest::MockAbilityContextTest()
{
startAbilityRunCount_ = 0;
}
MockAbilityContextTest::~MockAbilityContextTest()
{}
void MockAbilityContextTest::StartAbility(const AAFwk::Want &want, int requestCode)
{
++startAbilityRunCount_;
}
size_t MockAbilityContextTest::GetStartAbilityRunCount()
{
return startAbilityRunCount_;
}
void MockAbilityContextTest::SetStartAbilityRunCount(size_t nCount)
{
startAbilityRunCount_ = nCount;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,105 @@
/*
* 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_MOCK_ABILITY_MANAGER_CLIENT2_H
#define OHOS_AAFWK_MOCK_ABILITY_MANAGER_CLIENT2_H
#include <mutex>
#include "ability_connect_callback_interface.h"
#include "ability_manager_errors.h"
#include "ability_scheduler_interface.h"
#include "ability_manager_interface.h"
#include "want.h"
#include "iremote_object.h"
#include "ability_manager_client.h"
namespace OHOS {
namespace AAFwk {
class MockAbilityManagerClient : public AbilityManagerClient {
public:
MockAbilityManagerClient();
virtual ~MockAbilityManagerClient();
ErrCode GetStartAbility();
ErrCode GetTerminateAbility();
ErrCode GetTerminateAbilityResult();
ErrCode GetIsFirstInMission();
ErrCode GetRemoveMissions();
void SetStartAbility(ErrCode tValue);
void SetTerminateAbility(ErrCode tValue);
void SetTerminateAbilityResult(ErrCode tValue);
void SetIsFirstInMission(ErrCode tValue);
void SetRemoveMissions(ErrCode tValue);
int GetTerminateAbilityValue();
void SetTerminateAbilityValue(int nValue);
int GetRemoveMissionsValue();
void ChangeRemoveMissionsValue();
static std::shared_ptr<MockAbilityManagerClient> mock_instance_;
static bool mock_intanceIsNull_;
static std::shared_ptr<MockAbilityManagerClient> GetInstance();
static void SetInstanceNull(bool flag);
private:
ErrCode startAbility_;
ErrCode terminateAbility_;
ErrCode terminateAbilityResult_;
ErrCode isFirstInMission_;
ErrCode removeMissionsE_;
int terminateAbilityValue_;
int removeMissions_;
};
} // namespace AAFwk
} // namespace OHOS
namespace OHOS {
namespace AppExecFwk {
class MockAbilityContextDeal : public ContextDeal {
public:
MockAbilityContextDeal();
virtual ~MockAbilityContextDeal();
std::shared_ptr<HapModuleInfo> GetHapModuleInfo();
std::shared_ptr<HapModuleInfo> hapModInfo_;
};
class MockAbilityContextTest : public AbilityContext {
public:
MockAbilityContextTest();
~MockAbilityContextTest();
void StartAbility(const AAFwk::Want &want, int requestCode);
size_t GetStartAbilityRunCount();
void SetStartAbilityRunCount(size_t nCount);
size_t startAbilityRunCount_;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // OHOS_AAFWK_ABILITY_MANAGER_H
@@ -0,0 +1,229 @@
/*
* 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 <mutex>
#include "ability_manager_client.h"
#include "ability_manager_interface.h"
#include "string_ex.h"
#include "hilog_wrapper.h"
#include "ipc_skeleton.h"
#include "if_system_ability_manager.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
#include "sys_mgr_client.h"
namespace OHOS {
namespace AAFwk {
std::shared_ptr<AbilityManagerClient> mockInstanceEx_ = nullptr;
std::mutex mockMutexEx_;
std::shared_ptr<AbilityManagerClient> AbilityManagerClient::GetInstance()
{
if (mockInstanceEx_ == nullptr) {
std::lock_guard<std::mutex> lock_l(mockMutexEx_);
if (mockInstanceEx_ == nullptr) {
mockInstanceEx_ = std::make_shared<AbilityManagerClient>();
}
}
return mockInstanceEx_;
}
AbilityManagerClient::AbilityManagerClient()
{}
AbilityManagerClient::~AbilityManagerClient()
{}
ErrCode AbilityManagerClient::AttachAbilityThread(
const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)
{
HILOG_INFO("AbilityManagerClient::AttachAbilityThread start");
ErrCode err = Connect();
if (err != ERR_OK) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->AttachAbilityThread(scheduler, token);
}
ErrCode AbilityManagerClient::AbilityTransitionDone(const sptr<IRemoteObject> &token, int state)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->AbilityTransitionDone(token, state);
}
ErrCode AbilityManagerClient::ScheduleConnectAbilityDone(
const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->ScheduleConnectAbilityDone(token, remoteObject);
}
ErrCode AbilityManagerClient::ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->ScheduleDisconnectAbilityDone(token);
}
ErrCode AbilityManagerClient::ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)
{
if (remoteObject_ == nullptr) {
HILOG_ERROR("%{private}s:ability service not command", __func__);
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->ScheduleCommandAbilityDone(token);
}
void AbilityManagerClient::AddWindowInfo(const sptr<IRemoteObject> &token, int32_t windowToken)
{
if (remoteObject_ == nullptr) {
return;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
abms->AddWindowInfo(token, windowToken);
}
ErrCode AbilityManagerClient::StartAbility(const Want &want, int requestCode)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->StartAbility(want, requestCode);
}
ErrCode AbilityManagerClient::TerminateAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
{
HILOG_INFO("AbilityManagerClient::TerminateAbility start");
if (remoteObject_ == nullptr) {
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
HILOG_INFO("AbilityManagerClient::TerminateAbility end");
return abms->TerminateAbility(token, resultCode, resultWant);
}
ErrCode AbilityManagerClient::TerminateAbility(const sptr<IRemoteObject> &callerToken, int requestCode)
{
if (remoteObject_ == nullptr) {
HILOG_ERROR("%{private}s:ability service not connect", __func__);
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->TerminateAbility(callerToken, requestCode);
}
ErrCode AbilityManagerClient::ConnectAbility(
const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken)
{
if (remoteObject_ == nullptr) {
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->ConnectAbility(want, connect, callerToken);
}
ErrCode AbilityManagerClient::DisconnectAbility(const sptr<IAbilityConnection> &connect)
{
if (remoteObject_ == nullptr) {
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->DisconnectAbility(connect);
}
ErrCode AbilityManagerClient::DumpState(const std::string &args, std::vector<std::string> &state)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
abms->DumpState(args, state);
return ERR_OK;
}
ErrCode AbilityManagerClient::Connect()
{
std::lock_guard<std::mutex> lock(mockMutexEx_);
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
if (remoteObject_ == nullptr) {
HILOG_ERROR("AbilityManagerClient::Connect remoteObject_ == nullptr");
return ERR_NO_MEMORY;
}
return ERR_OK;
}
ErrCode AbilityManagerClient::GetAllStackInfo(StackInfo &stackInfo)
{
if (remoteObject_ == nullptr) {
return ABILITY_SERVICE_NOT_CONNECTED;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->GetAllStackInfo(stackInfo);
}
ErrCode AbilityManagerClient::StopServiceAbility(const Want &want)
{
if (remoteObject_ == nullptr) {
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->StopServiceAbility(want);
}
sptr<IAbilityScheduler> AbilityManagerClient::AcquireDataAbility(
const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken)
{
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
if (remoteObject_ == nullptr) {
return nullptr;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->AcquireDataAbility(uri, tryBind, callerToken);
}
ErrCode AbilityManagerClient::ReleaseDataAbility(
sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken)
{
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
if (remoteObject_ == nullptr) {
return -1;
}
sptr<IAbilityManager> abms = iface_cast<IAbilityManager>(remoteObject_);
return abms->ReleaseDataAbility(dataAbilityScheduler, callerToken);
}
} // namespace AAFwk
} // namespace OHOS
@@ -172,5 +172,30 @@ int MockAbilityManagerService::UninstallApp(const std::string &bundleName)
{
return 0;
}
int MockAbilityManagerService::MoveMissionToEnd(const sptr<IRemoteObject> &token, const bool nonFirst)
{
return 0;
}
bool MockAbilityManagerService::IsFirstInMission(const sptr<IRemoteObject> &token)
{
return true;
}
int MockAbilityManagerService::CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message)
{
return 0;
}
int MockAbilityManagerService::PowerOff()
{
return 0;
}
int MockAbilityManagerService::PowerOn()
{
return 0;
}
} // namespace AAFwk
} // namespace OHOS
+32 -4
View File
@@ -30,8 +30,7 @@ namespace OHOS {
namespace AAFwk {
enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING };
class MockAbilityManagerService : public AbilityManagerStub,
public std::enable_shared_from_this<MockAbilityManagerService> {
class MockAbilityManagerService : public AbilityManagerStub {
public:
MockAbilityManagerService();
~MockAbilityManagerService();
@@ -59,9 +58,31 @@ public:
int TerminateAbilityResult(const sptr<IRemoteObject> &token, int startId) override;
int StopServiceAbility(const Want &want) override;
int PowerOff() override;
int PowerOn() override;
int LockMission(int missionId) override
{
return 0;
};
int UnlockMission(int missionId) override
{
return 0;
};
MOCK_METHOD1(GetAllStackInfo, int(StackInfo &stackInfo));
MOCK_METHOD2(
GetWantSender, sptr<IWantSender>(const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken));
MOCK_METHOD2(SendWantSender, int(const sptr<IWantSender> &target, const SenderInfo &senderInfo));
MOCK_METHOD1(CancelWantSender, void(const sptr<IWantSender> &sender));
MOCK_METHOD1(GetPendingWantUid, int(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantUserId, int(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantBundleName, std::string(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantCode, int(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantType, int(const sptr<IWantSender> &target));
MOCK_METHOD2(RegisterCancelListener, void(const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver));
MOCK_METHOD2(UnregisterCancelListener, void(const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver));
MOCK_METHOD2(GetPendingRequestWant, int(const sptr<IWantSender> &target, std::shared_ptr<Want> &want));
int RemoveMission(int id) override;
int RemoveStack(int id) override;
@@ -78,7 +99,7 @@ public:
}
int GetRecentMissions(
const int32_t numMax, const int32_t flags, std::vector<RecentMissionInfo> &recentList) override
const int32_t numMax, const int32_t flags, std::vector<AbilityMissionInfo> &recentList) override
{
return 0;
}
@@ -93,11 +114,18 @@ public:
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;
}
virtual int MoveMissionToEnd(const sptr<IRemoteObject> &token, const bool nonFirst);
virtual bool IsFirstInMission(const sptr<IRemoteObject> &token);
virtual int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message);
enum RequestCode {
E_STATE_INITIAL = 0,
E_STATE_INACTIVE,
@@ -102,7 +102,7 @@ std::string BundleMgrService::GetAppType(const std::string &bundleName)
return "system";
}
bool BundleMgrService::GetHapModuleInfo(const std::string &hapFilePath, HapModuleInfo &hapModuleInfo)
bool BundleMgrService::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo)
{
GTEST_LOG_(INFO) << " BundleMgrService::GetHapModuleInfo";
hapModuleInfo.name = "Captain";
@@ -33,10 +33,10 @@ public:
{}
~BundleMgrProxy() = default;
bool QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) override;
bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override;
virtual bool QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) override;
virtual bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override;
std::string GetAppType(const std::string &bundleName) override;
virtual std::string GetAppType(const std::string &bundleName) override;
virtual bool GetApplicationInfo(
const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override;
@@ -61,7 +61,7 @@ public:
{
return 0;
};
virtual bool GetBundleNamesForUid(const int uid, std::vector<std::string> &bundleNames) override
virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override
{
return true;
};
@@ -87,7 +87,7 @@ public:
{
return true;
};
virtual bool GetHapModuleInfo(const std::string &hapFilePath, HapModuleInfo &hapModuleInfo) override;
virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, 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
{
@@ -170,6 +170,51 @@ public:
{
return true;
}
virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) override
{
return "";
}
virtual bool GetBundlesForUid(const int uid, std::vector<std::string> &bundleNames) override
{
return true;
}
virtual bool GetNameForUid(const int uid, std::string &name) override
{
return true;
}
virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) override
{
return true;
}
virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) override
{
return true;
}
virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) override
{
return "";
}
virtual bool RegisterAllPermissionsChanged(const sptr<OnPermissionChangedCallback> &callback) override
{
return true;
}
virtual bool RegisterPermissionsChanged(
const std::vector<int> &uids, const sptr<OnPermissionChangedCallback> &callback) override
{
return true;
}
virtual bool UnregisterPermissionsChanged(const sptr<OnPermissionChangedCallback> &callback) override
{
return true;
}
virtual bool IsApplicationEnabled(const std::string &bundleName) override
{
return true;
}
virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override
{
return true;
}
};
class BundleMgrStub : public IRemoteStub<IBundleMgr> {
@@ -181,10 +226,10 @@ public:
class BundleMgrService : public BundleMgrStub {
public:
bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override;
bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override;
virtual bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override;
virtual bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override;
std::string GetAppType(const std::string &bundleName) override;
virtual std::string GetAppType(const std::string &bundleName) override;
virtual bool GetApplicationInfo(
const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override;
@@ -193,7 +238,7 @@ public:
{
return true;
};
bool CheckIsSystemAppByUid(const int uid) override
virtual bool CheckIsSystemAppByUid(const int uid) override
{
return true;
};
@@ -209,7 +254,7 @@ public:
{
return 0;
};
virtual bool GetBundleNamesForUid(const int uid, std::vector<std::string> &bundleNames) override
virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override
{
return true;
};
@@ -235,7 +280,7 @@ public:
{
return true;
};
virtual bool GetHapModuleInfo(const std::string &hapFilePath, HapModuleInfo &hapModuleInfo) override;
virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, 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
{
@@ -318,6 +363,51 @@ public:
{
return true;
}
virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) override
{
return "";
}
virtual bool GetBundlesForUid(const int uid, std::vector<std::string> &bundleNames) override
{
return true;
}
virtual bool GetNameForUid(const int uid, std::string &name) override
{
return true;
}
virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) override
{
return true;
}
virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) override
{
return true;
}
virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) override
{
return "";
}
virtual bool RegisterAllPermissionsChanged(const sptr<OnPermissionChangedCallback> &callback) override
{
return true;
}
virtual bool RegisterPermissionsChanged(
const std::vector<int> &uids, const sptr<OnPermissionChangedCallback> &callback) override
{
return true;
}
virtual bool UnregisterPermissionsChanged(const sptr<OnPermissionChangedCallback> &callback) override
{
return true;
}
virtual bool IsApplicationEnabled(const std::string &bundleName) override
{
return true;
}
virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override
{
return true;
}
};
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,272 @@
#include <singleton.h>
#include <gtest/gtest.h>
#include "gmock/gmock.h"
#include "mock_resourceManager_interface1.h"
#include "res_config.h"
#include <string>
#include <vector>
#include <map>
namespace OHOS {
namespace Global {
namespace Resource {
class ResourceManagerTestInstance : public ResourceManager2 {
public:
ResourceManagerTestInstance(){};
virtual ~ResourceManagerTestInstance(){};
virtual bool AddResource(const char *path)
{
return false;
};
virtual RState UpdateResConfig(ResConfig &resConfig)
{
return ERROR;
};
virtual void GetResConfig(ResConfig &resConfig){};
virtual RState GetStringById(uint32_t id, std::string &outValue)
{
auto iter = StringById_.find(id);
if (iter == StringById_.end()) {
return ERROR;
}
outValue = iter->second;
return SUCCESS;
};
virtual void SetStringById(uint32_t id, std::string &inValue)
{
if (!StringById_.empty()) {
StringById_.clear();
}
StringById_[id] = inValue;
};
virtual RState GetStringByName(const char *name, std::string &outValue)
{
return ERROR;
};
virtual RState GetStringFormatById(std::string &outValue, uint32_t id, ...)
{
return ERROR;
};
virtual void SetStringFormatById(std::string &inValue, uint32_t id, ...){};
virtual RState GetStringFormatByName(std::string &outValue, const char *name, ...)
{
return ERROR;
};
virtual RState GetStringArrayById(uint32_t id, std::vector<std::string> &outValue)
{
auto iter = StringArrayById_.find(id);
if (iter == StringArrayById_.end()) {
return ERROR;
}
outValue = iter->second;
return SUCCESS;
};
virtual void SetStringArrayById(uint32_t id, std::vector<std::string> &inValue)
{
if (!StringArrayById_.empty()) {
StringArrayById_.clear();
}
StringArrayById_[id] = inValue;
};
virtual RState GetStringArrayByName(const char *name, std::vector<std::string> &outValue)
{
return ERROR;
};
virtual RState GetPatternById(uint32_t id, std::map<std::string, std::string> &outValue)
{
auto iter = PatternById_.find(id);
if (iter == PatternById_.end()) {
return ERROR;
}
outValue = iter->second;
return SUCCESS;
};
virtual void SetPatternById(uint32_t id, std::map<std::string, std::string> &inValue)
{
if (!PatternById_.empty()) {
PatternById_.clear();
}
PatternById_[id] = inValue;
};
virtual RState GetPatternByName(const char *name, std::map<std::string, std::string> &outValue)
{
return ERROR;
};
virtual RState GetPluralStringById(uint32_t id, int quantity, std::string &outValue)
{
return ERROR;
};
virtual RState GetPluralStringByName(const char *name, int quantity, std::string &outValue)
{
return ERROR;
};
virtual RState GetPluralStringByIdFormat(std::string &outValue, uint32_t id, int quantity, ...)
{
return ERROR;
};
virtual RState GetPluralStringByNameFormat(std::string &outValue, const char *name, int quantity, ...)
{
return ERROR;
};
virtual RState GetThemeById(uint32_t id, std::map<std::string, std::string> &outValue)
{
auto iter = ThemeById_.find(id);
if (iter == ThemeById_.end()) {
return ERROR;
}
outValue = iter->second;
return SUCCESS;
};
virtual void SetThemeById(uint32_t id, std::map<std::string, std::string> &inValue)
{
if (!ThemeById_.empty()) {
ThemeById_.clear();
}
ThemeById_[id] = inValue;
};
virtual RState GetThemeByName(const char *name, std::map<std::string, std::string> &outValue)
{
return ERROR;
};
virtual RState GetBooleanById(uint32_t id, bool &outValue)
{
return ERROR;
};
virtual RState GetBooleanByName(const char *name, bool &outValue)
{
return ERROR;
};
virtual RState GetIntegerById(uint32_t id, int &outValue)
{
return ERROR;
};
virtual RState GetIntegerByName(const char *name, int &outValue)
{
return ERROR;
};
virtual RState GetFloatById(uint32_t id, float &outValue)
{
return ERROR;
};
virtual RState GetFloatByName(const char *name, float &outValue)
{
return ERROR;
};
virtual RState GetIntArrayById(uint32_t id, std::vector<int> &outValue)
{
auto iter = IntArrayById_.find(id);
if (iter == IntArrayById_.end()) {
return ERROR;
}
outValue = iter->second;
return SUCCESS;
};
virtual void SetIntArrayById(uint32_t id, std::vector<int> &inValue)
{
if (!IntArrayById_.empty()) {
IntArrayById_.clear();
}
IntArrayById_[id] = inValue;
};
virtual RState GetIntArrayByName(const char *name, std::vector<int> &outValue)
{
return ERROR;
};
virtual RState GetColorById(uint32_t id, uint32_t &outValue)
{
auto iter = ColorById_.find(id);
if (iter == ColorById_.end()) {
return ERROR;
}
outValue = iter->second;
return SUCCESS;
};
virtual void SetColorById(uint32_t id, uint32_t &inValue)
{
if (!ColorById_.empty()) {
ColorById_.clear();
}
ColorById_[id] = inValue;
};
virtual RState GetColorByName(const char *name, uint32_t &outValue)
{
return ERROR;
};
virtual RState GetProfileById(uint32_t id, std::string &outValue)
{
return ERROR;
};
virtual RState GetProfileByName(const char *name, std::string &outValue)
{
return ERROR;
};
virtual RState GetMediaById(uint32_t id, std::string &outValue)
{
return ERROR;
};
virtual RState GetMediaByName(const char *name, std::string &outValue)
{
return ERROR;
};
public:
std::map<int, std::string> StringById_;
std::map<int, std::string> StringFormatById_;
std::map<int, std::vector<std::string>> StringArrayById_;
std::map<int, std::map<std::string, std::string>> PatternById_;
std::map<int, std::map<std::string, std::string>> ThemeById_;
std::map<int, std::vector<int>> IntArrayById_;
std::map<int, uint32_t> ColorById_;
// static ResourceManagerTestInstance* instance;
static std::shared_ptr<ResourceManagerTestInstance> instance;
};
std::shared_ptr<ResourceManagerTestInstance> ResourceManagerTestInstance::instance = nullptr;
std::shared_ptr<ResourceManager2> CreateResourceManager2()
{
if (ResourceManagerTestInstance::instance == nullptr) { /* */
ResourceManagerTestInstance::instance = std::make_shared<ResourceManagerTestInstance>();
}
return ResourceManagerTestInstance::instance;
}
} // namespace Resource
} // namespace Global
} // namespace OHOS
@@ -0,0 +1,107 @@
/*
* 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_MOCK_RESOURCE_MANAGER_RESOURCEMANAGER1_H
#define OHOS_MOCK_RESOURCE_MANAGER_RESOURCEMANAGER1_H
#include "res_config.h"
#include <string>
#include <vector>
#include <map>
#include "resource_manager.h"
namespace OHOS {
namespace Global {
namespace Resource {
class ResourceManager2 : public ResourceManager {
public:
ResourceManager2(){};
virtual ~ResourceManager2(){};
virtual bool AddResource(const char *path) = 0;
virtual RState UpdateResConfig(ResConfig &resConfig) = 0;
virtual void GetResConfig(ResConfig &resConfig) = 0;
virtual RState GetStringById(uint32_t id, std::string &outValue) = 0;
virtual void SetStringById(uint32_t id, std::string &outValue) = 0;
virtual RState GetStringByName(const char *name, std::string &outValue) = 0;
virtual RState GetStringFormatById(std::string &outValue, uint32_t id, ...) = 0;
virtual void SetStringFormatById(std::string &outValue, uint32_t id, ...) = 0;
virtual RState GetStringFormatByName(std::string &outValue, const char *name, ...) = 0;
virtual RState GetStringArrayById(uint32_t id, std::vector<std::string> &outValue) = 0;
virtual void SetStringArrayById(uint32_t id, std::vector<std::string> &outValue) = 0;
virtual RState GetStringArrayByName(const char *name, std::vector<std::string> &outValue) = 0;
virtual RState GetPatternById(uint32_t id, std::map<std::string, std::string> &outValue) = 0;
virtual void SetPatternById(uint32_t id, std::map<std::string, std::string> &outValue) = 0;
virtual RState GetPatternByName(const char *name, std::map<std::string, std::string> &outValue) = 0;
virtual RState GetPluralStringById(uint32_t id, int quantity, std::string &outValue) = 0;
virtual RState GetPluralStringByName(const char *name, int quantity, std::string &outValue) = 0;
virtual RState GetPluralStringByIdFormat(std::string &outValue, uint32_t id, int quantity, ...) = 0;
virtual RState GetPluralStringByNameFormat(std::string &outValue, const char *name, int quantity, ...) = 0;
virtual RState GetThemeById(uint32_t id, std::map<std::string, std::string> &outValue) = 0;
virtual void SetThemeById(uint32_t id, std::map<std::string, std::string> &outValue) = 0;
virtual RState GetThemeByName(const char *name, std::map<std::string, std::string> &outValue) = 0;
virtual RState GetBooleanById(uint32_t id, bool &outValue) = 0;
virtual RState GetBooleanByName(const char *name, bool &outValue) = 0;
virtual RState GetIntegerById(uint32_t id, int &outValue) = 0;
virtual RState GetIntegerByName(const char *name, int &outValue) = 0;
virtual RState GetFloatById(uint32_t id, float &outValue) = 0;
virtual RState GetFloatByName(const char *name, float &outValue) = 0;
virtual RState GetIntArrayById(uint32_t id, std::vector<int> &outValue) = 0;
virtual void SetIntArrayById(uint32_t id, std::vector<int> &outValue) = 0;
virtual RState GetIntArrayByName(const char *name, std::vector<int> &outValue) = 0;
virtual RState GetColorById(uint32_t id, uint32_t &outValue) = 0;
virtual void SetColorById(uint32_t id, uint32_t &outValue) = 0;
virtual RState GetColorByName(const char *name, uint32_t &outValue) = 0;
virtual RState GetProfileById(uint32_t id, std::string &outValue) = 0;
virtual RState GetProfileByName(const char *name, std::string &outValue) = 0;
virtual RState GetMediaById(uint32_t id, std::string &outValue) = 0;
virtual RState GetMediaByName(const char *name, std::string &outValue) = 0;
};
std::shared_ptr<ResourceManager2> CreateResourceManager2();
} // namespace Resource
} // namespace Global
} // namespace OHOS
#endif
@@ -0,0 +1,221 @@
/*
* 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 "application_context.h"
#include "event_runner.h"
#include "context_deal.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
class AbilityContextForTaskDispatcherTest : public testing::Test {
public:
AbilityContextForTaskDispatcherTest()
{}
~AbilityContextForTaskDispatcherTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void AbilityContextForTaskDispatcherTest::SetUpTestCase(void)
{}
void AbilityContextForTaskDispatcherTest::TearDownTestCase(void)
{}
void AbilityContextForTaskDispatcherTest::SetUp(void)
{}
void AbilityContextForTaskDispatcherTest::TearDown(void)
{}
/**
* @tc.number: AaFwk_AbilityContext_GetUITaskDispatcher_0100
* @tc.name: GetUITaskDispatcher
* @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct.
*/
HWTEST_F(
AbilityContextForTaskDispatcherTest, AaFwk_AbilityContext_GetUITaskDispatcher_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetUITaskDispatcher_0100 start";
std::shared_ptr<EventRunner> runner = EventRunner::Create(false);
std::shared_ptr<ContextDeal> contextdeal = std::make_shared<ContextDeal>();
contextdeal->SetRunner(runner);
std::shared_ptr<AbilityContext> abilitycontext = std::make_shared<AbilityContext>();
abilitycontext->AttachBaseContext(contextdeal);
EXPECT_TRUE((nullptr != abilitycontext->GetUITaskDispatcher()));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetUITaskDispatcher_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetUITaskDispatcher_0200
* @tc.name: GetUITaskDispatcher
* @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct.
*/
HWTEST_F(
AbilityContextForTaskDispatcherTest, AaFwk_AbilityContext_GetUITaskDispatcher_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetUITaskDispatcher_0200 start";
std::shared_ptr<AbilityContext> abilitycontext = std::make_shared<AbilityContext>();
EXPECT_TRUE((nullptr == abilitycontext->GetUITaskDispatcher()));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetUITaskDispatcher_0200 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetMainTaskDispatcher_0100
* @tc.name: GetMainTaskDispatcher
* @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct.
*/
HWTEST_F(AbilityContextForTaskDispatcherTest, AaFwk_AbilityContext_GetMainTaskDispatcher_0100,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetMainTaskDispatcher_0100 start";
std::shared_ptr<EventRunner> runner = EventRunner::Create(false);
std::shared_ptr<ContextDeal> contextdeal = std::make_shared<ContextDeal>();
contextdeal->SetRunner(runner);
std::shared_ptr<AbilityContext> abilitycontext = std::make_shared<AbilityContext>();
abilitycontext->AttachBaseContext(contextdeal);
EXPECT_TRUE((nullptr != abilitycontext->GetMainTaskDispatcher()));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetMainTaskDispatcher_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetMainTaskDispatcher_0200
* @tc.name: GetMainTaskDispatcher
* @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct.
*/
HWTEST_F(AbilityContextForTaskDispatcherTest, AaFwk_AbilityContext_GetMainTaskDispatcher_0200,
Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetMainTaskDispatcher_0200 start";
std::shared_ptr<AbilityContext> abilitycontext = std::make_shared<AbilityContext>();
EXPECT_TRUE((nullptr == abilitycontext->GetMainTaskDispatcher()));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetMainTaskDispatcher_0200 end";
}
/**
* @tc.number: AaFwk_AbilityContext_CreateParallelTaskDispatcher_0100
* @tc.name: CreateParallelTaskDispatcher
* @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct.
*/
HWTEST_F(AbilityContextForTaskDispatcherTest, AaFwk_AbilityContext_CreateParallelTaskDispatcher_0100,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_CreateParallelTaskDispatcher_0100 start";
std::shared_ptr<ContextDeal> contextdeal = std::make_shared<ContextDeal>();
std::shared_ptr<ApplicationContext> appcontext = std::make_shared<ApplicationContext>();
contextdeal->SetApplicationContext(appcontext);
std::shared_ptr<AbilityContext> abilitycontext = std::make_shared<AbilityContext>();
abilitycontext->AttachBaseContext(contextdeal);
std::string name("ParalleTest");
TaskPriority high = TaskPriority::HIGH;
EXPECT_TRUE((nullptr != abilitycontext->CreateParallelTaskDispatcher(name, high)));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_CreateParallelTaskDispatcher_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_CreateParallelTaskDispatcher_0200
* @tc.name: CreateParallelTaskDispatcher
* @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct.
*/
HWTEST_F(AbilityContextForTaskDispatcherTest, AaFwk_AbilityContext_CreateParallelTaskDispatcher_0200,
Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_CreateParallelTaskDispatcher_0200 start";
std::shared_ptr<AbilityContext> abilitycontext = std::make_shared<AbilityContext>();
std::string name("ParalleTest");
TaskPriority high = TaskPriority::HIGH;
EXPECT_TRUE((nullptr == abilitycontext->CreateParallelTaskDispatcher(name, high)));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_CreateParallelTaskDispatcher_0200 end";
}
/**
* @tc.number: AaFwk_AbilityContext_CreateSerialTaskDispatcher_0100
* @tc.name: CreateSerialTaskDispatcher
* @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct.
*/
HWTEST_F(AbilityContextForTaskDispatcherTest, AaFwk_AbilityContext_CreateSerialTaskDispatcher_0100,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_CreateSerialTaskDispatcher_0100 start";
std::shared_ptr<ContextDeal> contextdeal = std::make_shared<ContextDeal>();
std::shared_ptr<ApplicationContext> appcontext = std::make_shared<ApplicationContext>();
contextdeal->SetApplicationContext(appcontext);
std::shared_ptr<AbilityContext> abilitycontext = std::make_shared<AbilityContext>();
abilitycontext->AttachBaseContext(contextdeal);
std::string name("Serial");
TaskPriority high = TaskPriority::HIGH;
EXPECT_TRUE((nullptr != abilitycontext->CreateSerialTaskDispatcher(name, high)));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_CreateSerialTaskDispatcher_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_CreateSerialTaskDispatcher_0200
* @tc.name: CreateSerialTaskDispatcher
* @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct.
*/
HWTEST_F(AbilityContextForTaskDispatcherTest, AaFwk_AbilityContext_CreateSerialTaskDispatcher_0200,
Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_CreateSerialTaskDispatcher_0200 start";
std::shared_ptr<AbilityContext> abilitycontext = std::make_shared<AbilityContext>();
std::string name("Serial");
TaskPriority high = TaskPriority::HIGH;
EXPECT_TRUE((nullptr == abilitycontext->CreateSerialTaskDispatcher(name, high)));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_CreateSerialTaskDispatcher_0200 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetGlobalTaskDispatcher_0100
* @tc.name: GetGlobalTaskDispatcher
* @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct.
*/
HWTEST_F(AbilityContextForTaskDispatcherTest, AaFwk_AbilityContext_GetGlobalTaskDispatcher_0100,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetGlobalTaskDispatcher_0100 start";
std::shared_ptr<ContextDeal> contextdeal = std::make_shared<ContextDeal>();
std::shared_ptr<ApplicationContext> appcontext = std::make_shared<ApplicationContext>();
contextdeal->SetApplicationContext(appcontext);
std::shared_ptr<AbilityContext> abilitycontext = std::make_shared<AbilityContext>();
abilitycontext->AttachBaseContext(contextdeal);
TaskPriority high = TaskPriority::HIGH;
EXPECT_TRUE((nullptr != abilitycontext->GetGlobalTaskDispatcher(high)));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetGlobalTaskDispatcher_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetGlobalTaskDispatcher_0200
* @tc.name: GetGlobalTaskDispatcher
* @tc.desc: Test the attachbasecontext call to verify that the return value of gethapmoduleinfo is correct.
*/
HWTEST_F(AbilityContextForTaskDispatcherTest, AaFwk_AbilityContext_GetGlobalTaskDispatcher_0200,
Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetGlobalTaskDispatcher_0200 start";
std::shared_ptr<AbilityContext> abilitycontext = std::make_shared<AbilityContext>();
TaskPriority high = TaskPriority::HIGH;
EXPECT_TRUE((nullptr == abilitycontext->GetGlobalTaskDispatcher(high)));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetGlobalTaskDispatcher_0200 end";
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,637 @@
/*
* 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 <singleton.h>
#include <gtest/gtest.h>
#include "gmock/gmock.h"
#include "ability_context.h"
#include "ohos_application.h"
#include "ability_handler.h"
#include "ability_info.h"
#include "ability.h"
#include "mock_ability_manager_client_interface1.h"
#include "mock_resourceManager_interface1.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
class AbilityContextInterfaceTest : public testing::Test {
public:
AbilityContextInterfaceTest() : context_(nullptr)
{}
~AbilityContextInterfaceTest()
{}
std::unique_ptr<OHOS::AppExecFwk::AbilityContext> context_ = nullptr;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void AbilityContextInterfaceTest::SetUpTestCase(void)
{}
void AbilityContextInterfaceTest::TearDownTestCase(void)
{}
void AbilityContextInterfaceTest::SetUp()
{}
void AbilityContextInterfaceTest::TearDown()
{}
/**
* @tc.number: AaFwk_AbilityContext_TerminateAbilityResult_0100
* @tc.name: TerminateAbilityResult
* @tc.desc: Test the attachbasecontext call to verify that the return value of TerminateAbilityResult is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_TerminateAbilityResult_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_TerminateAbilityResult_0100 start";
const ErrCode testValue = ERR_OK;
OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->SetTerminateAbilityResult(testValue);
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
EXPECT_TRUE(abilityContext->TerminateAbilityResult(0));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_TerminateAbilityResult_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_TerminateAbilityResult_0200
* @tc.name: TerminateAbilityResult
* @tc.desc: Test the attachbasecontext call to verify that the return value of TerminateAbilityResult is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_TerminateAbilityResult_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_TerminateAbilityResult_0200 start";
const ErrCode testValue = ERR_NO_INIT;
OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->SetTerminateAbilityResult(testValue);
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
EXPECT_FALSE(abilityContext->TerminateAbilityResult(0));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_TerminateAbilityResult_0200 end";
}
/**
* @tc.number: AaFwk_AbilityContext_TerminateAbilityResult_0300
* @tc.name: TerminateAbilityResult
* @tc.desc: Test the attachbasecontext call to verify that the return value of TerminateAbilityResult is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_TerminateAbilityResult_0300, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_TerminateAbilityResult_0300 start";
OHOS::AAFwk::MockAbilityManagerClient::SetInstanceNull(false);
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
EXPECT_FALSE(abilityContext->TerminateAbilityResult(0));
OHOS::AAFwk::MockAbilityManagerClient::SetInstanceNull(true);
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_TerminateAbilityResult_0300 end";
}
/**
* @tc.number: AaFwk_AbilityContext_IsFirstInMission_0100
* @tc.name: IsFirstInMission
* @tc.desc: Test the attachbasecontext call to verify that the return value of IsFirstInMission is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_IsFirstInMission_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_IsFirstInMission_0100 start";
const ErrCode testValue = ERR_OK;
OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->SetIsFirstInMission(testValue);
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
EXPECT_TRUE(abilityContext->IsFirstInMission());
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_IsFirstInMission_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_IsFirstInMission_0200
* @tc.name: IsFirstInMission
* @tc.desc: Test the attachbasecontext call to verify that the return value of IsFirstInMission is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_IsFirstInMission_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_IsFirstInMission_0200 start";
const ErrCode testValue = ERR_NO_INIT;
OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->SetIsFirstInMission(testValue);
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
EXPECT_FALSE(abilityContext->IsFirstInMission());
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_IsFirstInMission_0200 end";
}
/**
* @tc.number: AaFwk_AbilityContext_IsFirstInMission_0300
* @tc.name: IsFirstInMission
* @tc.desc: Test the attachbasecontext call to verify that the return value of IsFirstInMission is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_IsFirstInMission_0300, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_IsFirstInMission_0300 start";
OHOS::AAFwk::MockAbilityManagerClient::SetInstanceNull(false);
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
EXPECT_FALSE(abilityContext->IsFirstInMission());
OHOS::AAFwk::MockAbilityManagerClient::SetInstanceNull(true);
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_IsFirstInMission_0300 end";
}
/**
* @tc.number: AaFwk_AbilityContext_SetColorMode_0100
* @tc.name: SetColorMode
* @tc.desc: Test the attachbasecontext call to verify that the return value of SetColorMode is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_SetColorMode_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_SetColorMode_0100 start";
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
abilityContext->AttachBaseContext(contextDeal);
int testValue = 1;
abilityContext->SetColorMode(testValue);
EXPECT_EQ(testValue, abilityContext->GetColorMode());
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_SetColorMode_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_SetColorMode_0200
* @tc.name: SetColorMode
* @tc.desc: Test the attachbasecontext call to verify that the return value of SetColorMode is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_SetColorMode_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_SetColorMode_0200 start";
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
int testValue = 0;
abilityContext->SetColorMode(testValue);
EXPECT_GT(testValue, abilityContext->GetColorMode());
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_SetColorMode_0200 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetColorMode_0100
* @tc.name: GetColorMode
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetColorMode is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetColorMode_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetColorMode_0100 start";
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
abilityContext->AttachBaseContext(contextDeal);
int testValue = 1;
abilityContext->SetColorMode(testValue);
EXPECT_EQ(testValue, abilityContext->GetColorMode());
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetColorMode_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetColorMode_0200
* @tc.name: GetColorMode
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetColorMode is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetColorMode_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetColorMode_0200 start";
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
int testValue = 0;
abilityContext->SetColorMode(testValue);
EXPECT_GT(testValue, abilityContext->GetColorMode());
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetColorMode_0200 end";
}
/**
* @tc.number: AaFwk_AbilityContext_SetTheme_0100
* @tc.name: SetTheme
* @tc.desc: Test the attachbasecontext call to verify that the return value of SetTheme is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_SetTheme_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_SetTheme_0100 start";
int testValue = 1;
std::map<std::string, std::string> testList = {
{"Pattern1", "PatternA"}, {"Pattern2", "PatternB"}, {"Pattern3", "PatternC"}};
std::shared_ptr<Global::Resource::ResourceManager2> resourceManager(Global::Resource::CreateResourceManager2());
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
resourceManager->SetThemeById(testValue, testList);
contextDeal->initResourceManager(resourceManager);
abilityContext->AttachBaseContext(contextDeal);
abilityContext->SetTheme(testValue);
// EXPECT_EQ(testValue, contextDeal->GetHapModuleInfo()->themeId);
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_SetTheme_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_SetTheme_0200
* @tc.name: SetTheme
* @tc.desc: Test the attachbasecontext call to verify that the return value of SetTheme is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_SetTheme_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_SetTheme_0200 start";
int testValue = 2;
std::shared_ptr<Global::Resource::ResourceManager2> resourceManager(Global::Resource::CreateResourceManager2());
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
abilityContext->SetTheme(testValue);
// EXPECT_NE(testValue, contextDeal->GetHapModuleInfo()->themeId);
abilityContext->AttachBaseContext(contextDeal);
abilityContext->SetTheme(testValue);
// EXPECT_NE(testValue, contextDeal->GetHapModuleInfo()->themeId);
contextDeal->initResourceManager(resourceManager);
abilityContext->SetTheme(testValue);
// EXPECT_NE(testValue, contextDeal->GetHapModuleInfo()->themeId);
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_SetTheme_0200 end";
}
/**
* @tc.number: AaFwk_AbilityContext_StartAbilities_0100
* @tc.name: StartAbilities
* @tc.desc: Test the attachbasecontext call to verify that the return value of StartAbilities is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_StartAbilities_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_StartAbilities_0100 start";
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<MockAbilityContextTest> abilityContext = std::make_shared<MockAbilityContextTest>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->type = OHOS::AppExecFwk::AbilityType::DATA;
contextDeal->SetAbilityInfo(abilityInfo);
abilityContext->AttachBaseContext(contextDeal);
std::vector<AAFwk::Want> testlist = {AAFwk::Want(), AAFwk::Want()};
abilityContext->StartAbilities(testlist);
EXPECT_TRUE((testlist.size() == abilityContext->GetStartAbilityRunCount()));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_StartAbilities_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetPreferencesDir_0100
* @tc.name: GetPreferencesDir
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetPreferencesDir is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetPreferencesDir_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetPreferencesDir_0100 start";
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
std::shared_ptr<ApplicationInfo> applicationInfo = std::make_shared<ApplicationInfo>();
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
const std::string testValue = "./1234test/preferences";
abilityInfo->name = "test1234.1234test";
applicationInfo->dataDir = ".";
contextDeal->SetAbilityInfo(abilityInfo);
contextDeal->SetApplicationInfo(applicationInfo);
abilityContext->AttachBaseContext(contextDeal);
EXPECT_STREQ(testValue.c_str(), abilityContext->GetPreferencesDir().c_str());
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetPreferencesDir_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetPattern_0100
* @tc.name: GetPattern
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetPattern is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetPattern_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetPattern_0100 start";
int testValue = 0;
std::map<std::string, std::string> testList = {
{"Pattern1", "PatternA"}, {"Pattern2", "PatternB"}, {"Pattern3", "PatternC"}};
std::shared_ptr<Global::Resource::ResourceManager2> resourceManager(Global::Resource::CreateResourceManager2());
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
resourceManager->SetPatternById(testValue, testList);
contextDeal->initResourceManager(resourceManager);
abilityContext->AttachBaseContext(contextDeal);
abilityContext->SetPattern(testValue);
std::map<std::string, std::string> retVal = abilityContext->GetPattern();
EXPECT_TRUE((retVal == testList));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetPattern_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetTheme_0100
* @tc.name: GetTheme
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetTheme is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetTheme_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetTheme_0100 start";
int testValue = 0;
std::map<std::string, std::string> testList = {{"Theme1", "ThemeA"}, {"Theme2", "ThemeB"}, {"Theme3", "ThemeC"}};
std::shared_ptr<Global::Resource::ResourceManager2> resourceManager(Global::Resource::CreateResourceManager2());
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
resourceManager->SetThemeById(testValue, testList);
contextDeal->initResourceManager(resourceManager);
abilityContext->AttachBaseContext(contextDeal);
std::map<std::string, std::string> retVal = abilityContext->GetTheme();
// EXPECT_TRUE((retVal == testList));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetTheme_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetString_ById_0100
* @tc.name: GetString
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetString is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetString_ById_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetString_ById_0100 start";
std::shared_ptr<Global::Resource::ResourceManager2> resourceManager(Global::Resource::CreateResourceManager2());
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
int testCount = 0;
std::string testValue = "GetString test";
resourceManager->SetStringById(testCount, testValue);
contextDeal->initResourceManager(resourceManager);
abilityContext->AttachBaseContext(contextDeal);
EXPECT_STREQ(testValue.c_str(), abilityContext->GetString(testCount).c_str());
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetString_ById_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetString_ByIdAndFormat_0100
* @tc.name: GetString
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetString is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetString_ByIdAndFormat_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetString_ByIdAndFormat_0100 start";
std::shared_ptr<Global::Resource::ResourceManager2> resourceManager(Global::Resource::CreateResourceManager2());
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
// int testCount = 0;
std::string testByName = "";
// std::string retVal = contextDeal->GetString(testCount, testByName);
// EXPECT_STREQ(retVal, testValue);
// EXPECT_TRUE(false);
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetString_ByIdAndFormat_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetStringArray_0100
* @tc.name: GetStringArray
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetStringArray is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetStringArray_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetStringArray_0100 start";
std::shared_ptr<Global::Resource::ResourceManager2> resourceManager(Global::Resource::CreateResourceManager2());
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
int testCount = 0;
std::vector<std::string> testValue = {"123", "456", "789"};
resourceManager->SetStringArrayById(testCount, testValue);
contextDeal->initResourceManager(resourceManager);
abilityContext->AttachBaseContext(contextDeal);
std::vector<std::string> retVal = abilityContext->GetStringArray(testCount);
EXPECT_TRUE((retVal == testValue));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetStringArray_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetStringArray_0200
* @tc.name: GetStringArray
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetStringArray is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetStringArray_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetStringArray_0200 start";
std::shared_ptr<Global::Resource::ResourceManager2> resourceManager(Global::Resource::CreateResourceManager2());
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
int testCount = 0;
std::vector<std::string> testValue = {"123", "456", "789"};
resourceManager->SetStringArrayById(testCount + 1, testValue);
contextDeal->initResourceManager(resourceManager);
abilityContext->AttachBaseContext(contextDeal);
std::vector<std::string> retVal = abilityContext->GetStringArray(testCount);
EXPECT_FALSE((retVal == testValue));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetStringArray_0200 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetIntArray_0100
* @tc.name: GetIntArray
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetIntArray is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetIntArray_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetIntArray_0100 start";
std::shared_ptr<Global::Resource::ResourceManager2> resourceManager(Global::Resource::CreateResourceManager2());
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
int testCount = 0;
std::vector<int> testValue = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
resourceManager->SetIntArrayById(testCount, testValue);
contextDeal->initResourceManager(resourceManager);
abilityContext->AttachBaseContext(contextDeal);
std::vector<int> retVal = abilityContext->GetIntArray(testCount);
EXPECT_TRUE((retVal == testValue));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetIntArray_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetIntArray_0200
* @tc.name: GetIntArray
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetIntArray is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetIntArray_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetIntArray_0200 start";
std::shared_ptr<Global::Resource::ResourceManager2> resourceManager(Global::Resource::CreateResourceManager2());
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
int testCount = 0;
std::vector<int> testValue = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
resourceManager->SetIntArrayById(testCount + 1, testValue);
contextDeal->initResourceManager(resourceManager);
abilityContext->AttachBaseContext(contextDeal);
std::vector<int> retVal = abilityContext->GetIntArray(testCount);
EXPECT_FALSE((retVal == testValue));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetIntArray_0200 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetColor_0100
* @tc.name: GetColor
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetColor is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetColor_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetColor_0100 start";
std::shared_ptr<Global::Resource::ResourceManager2> resourceManager(Global::Resource::CreateResourceManager2());
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
int testCount = 0;
uint32_t testValue = 1;
const int testVal = static_cast<int>(testValue);
resourceManager->SetColorById(testCount, testValue);
contextDeal->initResourceManager(resourceManager);
abilityContext->AttachBaseContext(contextDeal);
EXPECT_EQ(testVal, abilityContext->GetColor(testCount));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetColor_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetColor_0200
* @tc.name: GetColor
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetColor is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetColor_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetColor_0200 start";
std::shared_ptr<Global::Resource::ResourceManager2> resourceManager(Global::Resource::CreateResourceManager2());
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
int testCount = 0;
uint32_t testValue = 1;
const int testVal = static_cast<int>(testValue);
resourceManager->SetColorById(testCount + 1, testValue);
contextDeal->initResourceManager(resourceManager);
abilityContext->AttachBaseContext(contextDeal);
EXPECT_NE(testVal, abilityContext->GetColor(testCount));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetColor_0200 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetThemeId_0100
* @tc.name: GetThemeId
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetThemeId is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetThemeId_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetThemeId_0100 start";
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
// const int testValue = 1;
// contextDeal->GetHapModuleInfo()->themeId = testValue;
abilityContext->AttachBaseContext(contextDeal);
// EXPECT_EQ(testValue, abilityContext->GetThemeId());
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetThemeId_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_GetDisplayOrientation_0100
* @tc.name: GetDisplayOrientation
* @tc.desc: Test the attachbasecontext call to verify that the return value of GetDisplayOrientation is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_GetDisplayOrientation_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetDisplayOrientation_0100 start";
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
int testValue = 1;
abilityInfo->orientation = static_cast<DisplayOrientation>(testValue);
contextDeal->SetAbilityInfo(abilityInfo);
abilityContext->AttachBaseContext(contextDeal);
EXPECT_EQ(testValue, abilityContext->GetDisplayOrientation());
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_GetDisplayOrientation_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_SetPattern_0100
* @tc.name: SetPattern
* @tc.desc: Test the attachbasecontext call to verify that the return value of SetPattern is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_SetPattern_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_SetPattern_0100 start";
std::shared_ptr<Global::Resource::ResourceManager2> resourceManager(Global::Resource::CreateResourceManager2());
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
int testCount = 0;
std::map<std::string, std::string> testList = {{"123", "abc"}, {"456", "def"}};
resourceManager->SetPatternById(testCount, testList);
contextDeal->initResourceManager(resourceManager);
abilityContext->AttachBaseContext(contextDeal);
abilityContext->SetPattern(testCount);
std::map<std::string, std::string> retVal;
EXPECT_FALSE((retVal == testList));
retVal = abilityContext->GetPattern();
EXPECT_TRUE((retVal == testList));
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_SetPattern_0100 end";
}
/**
* @tc.number: AaFwk_AbilityContext_TerminateAbility_0100
* @tc.name: TerminateAbility
* @tc.desc: Test the attachbasecontext call to verify that the return value of TerminateAbility is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_AbilityContext_TerminateAbility_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_TerminateAbility_0100 start";
const ErrCode mockValue = ERR_OK;
int testValue = 0;
OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->SetTerminateAbility(mockValue);
std::shared_ptr<AbilityContext> abilityContext = std::make_shared<AbilityContext>();
abilityContext->TerminateAbility(testValue);
EXPECT_EQ(testValue, AAFwk::MockAbilityManagerClient::GetInstance()->GetTerminateAbilityValue());
GTEST_LOG_(INFO) << "AaFwk_AbilityContext_TerminateAbility_0100 end";
}
/**
* @tc.number: AaFwk_Ability_TerminateAndRemoveMission_0100
* @tc.name: TerminateAndRemoveMission
* @tc.desc: Test the attachbasecontext call to verify that the return value of TerminateAbility is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_Ability_TerminateAndRemoveMission_0100, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_TerminateAndRemoveMission_0100 start";
const ErrCode mockValue = ERR_OK;
OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->SetRemoveMissions(mockValue);
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AAFwk::LifeCycleStateInfo> lifeCycleStateInfo = std::make_shared<AAFwk::LifeCycleStateInfo>();
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->name = "TerminateAndRemoveMission";
std::shared_ptr<OHOSApplication> ohosApplication = 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> abilityHandler = std::make_shared<AbilityHandler>(eventRunner, abilityThread);
sptr<IRemoteObject> token = nullptr;
int testValue = OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->GetRemoveMissionsValue();
lifeCycleStateInfo->missionId = 0;
contextDeal->SetLifeCycleStateInfo(*lifeCycleStateInfo);
ability->Init(abilityInfo, ohosApplication, abilityHandler, token);
ability->AttachBaseContext(contextDeal);
ability->OnActive();
ability->TerminateAndRemoveMission();
EXPECT_NE(testValue, AAFwk::MockAbilityManagerClient::GetInstance()->GetRemoveMissionsValue());
GTEST_LOG_(INFO) << "AaFwk_Ability_TerminateAndRemoveMission_0100 end";
}
/**
* @tc.number: AaFwk_Ability_TerminateAndRemoveMission_0200
* @tc.name: TerminateAndRemoveMission
* @tc.desc: Test the attachbasecontext call to verify that the return value of TerminateAbility is correct.
*/
HWTEST_F(AbilityContextInterfaceTest, AaFwk_Ability_TerminateAndRemoveMission_0200, Function | MediumTest | Level3)
{
GTEST_LOG_(INFO) << "AaFwk_Ability_TerminateAndRemoveMission_0200 start";
const ErrCode mockValue = ERR_OK;
OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->SetRemoveMissions(mockValue);
std::shared_ptr<MockAbilityContextDeal> contextDeal = std::make_shared<MockAbilityContextDeal>();
std::shared_ptr<AAFwk::LifeCycleStateInfo> lifeCycleStateInfo = std::make_shared<AAFwk::LifeCycleStateInfo>();
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
int testValue = OHOS::AAFwk::MockAbilityManagerClient::GetInstance()->GetRemoveMissionsValue();
lifeCycleStateInfo->missionId = 0;
contextDeal->SetLifeCycleStateInfo(*lifeCycleStateInfo);
ability->AttachBaseContext(contextDeal);
ability->OnActive();
ability->TerminateAndRemoveMission();
EXPECT_EQ(testValue, AAFwk::MockAbilityManagerClient::GetInstance()->GetRemoveMissionsValue());
GTEST_LOG_(INFO) << "AaFwk_Ability_TerminateAndRemoveMission_0200 end";
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,354 @@
/*
* 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 <memory>
#include "ability.h"
#include "ability_impl.h"
#include "ability_state.h"
#include "app_log_wrapper.h"
#include "context_deal.h"
#include "foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include/uri.h"
#include "mock_ability_token.h"
#include "ohos_application.h"
#include "page_ability_impl.h"
namespace OHOS {
namespace AppExecFwk {
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
class AbilityImplActiveTest : public testing::Test {
public:
AbilityImplActiveTest()
{}
~AbilityImplActiveTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
class MockAbilityimpl : public AbilityImpl {
public:
MockAbilityimpl(){};
virtual ~MockAbilityimpl(){};
void Inactive()
{
AbilityImpl::Inactive();
}
void Active()
{
AbilityImpl::Active();
}
};
class MockAbilityClass : public Ability {
public:
MockAbilityClass() : topFocus_(false), topFocusChange_(false), windowFocus_(false), windowFocusChange_(false){};
virtual ~MockAbilityClass(){};
virtual void OnWindowFocusChanged(bool hasFocus)
{
windowFocus_ = hasFocus;
windowFocusChange_ = true;
};
virtual void OnTopActiveAbilityChanged(bool topActive)
{
topFocus_ = topActive;
topFocusChange_ = true;
};
bool GetWindowFocusStatus()
{
return windowFocus_;
};
bool GetTopFocusStatus()
{
return topFocus_;
};
bool GetWindowFocusChangeStatus()
{
return windowFocusChange_;
};
bool GetTopFocusChangeStatus()
{
return topFocusChange_;
};
virtual void OnActive(){};
virtual void OnInactive(){};
private:
bool topFocus_;
bool topFocusChange_;
bool windowFocus_;
bool windowFocusChange_;
};
void AbilityImplActiveTest::SetUpTestCase(void)
{}
void AbilityImplActiveTest::TearDownTestCase(void)
{}
void AbilityImplActiveTest::SetUp(void)
{}
void AbilityImplActiveTest::TearDown(void)
{}
/*
* Feature: AbilityImpl
* Function: Active
* SubFunction: NA
* FunctionPoints: Active
* EnvConditions: NA
* CaseDescription: Validate when normally entering a string
*/
HWTEST_F(AbilityImplActiveTest, AaFwk_AbilityImpl_Active_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_001 start";
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_001 pretest";
std::shared_ptr<MockAbilityimpl> abilityImpl = std::make_shared<MockAbilityimpl>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
sptr<IRemoteObject> token(new (std::nothrow) MockAbilityToken());
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> record = std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<MockAbilityClass> mockAbility = std::make_shared<MockAbilityClass>();
std::shared_ptr<Ability> ability = std::static_pointer_cast<Ability>(mockAbility);
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(nullptr, nullptr);
std::shared_ptr<ContextDeal> contextDeal = std::make_shared<ContextDeal>();
abilityInfo->type = AbilityType::PAGE;
contextDeal->SetAbilityInfo(abilityInfo);
mockAbility->AttachBaseContext(contextDeal);
abilityImpl->Init(application, record, ability, handler, token, contextDeal);
abilityImpl->Inactive();
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_001 test proc";
abilityImpl->Active();
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_001 test result check";
EXPECT_TRUE(mockAbility->GetWindowFocusChangeStatus());
EXPECT_TRUE(mockAbility->GetWindowFocusStatus());
EXPECT_TRUE(mockAbility->GetTopFocusChangeStatus());
EXPECT_TRUE(mockAbility->GetTopFocusStatus());
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_001 end";
}
/*
* Feature: AbilityImpl
* Function: Active
* SubFunction: NA
* FunctionPoints: Active
* EnvConditions: NA
* CaseDescription: Validate when normally entering a string
*/
HWTEST_F(AbilityImplActiveTest, AaFwk_AbilityImpl_Active_002, TestSize.Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_002 start";
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_002 pretest";
std::shared_ptr<MockAbilityimpl> abilityImpl = std::make_shared<MockAbilityimpl>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
sptr<IRemoteObject> token(new (std::nothrow) MockAbilityToken());
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> record = std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<MockAbilityClass> mockAbility = std::make_shared<MockAbilityClass>();
std::shared_ptr<Ability> ability = std::static_pointer_cast<Ability>(mockAbility);
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(nullptr, nullptr);
std::shared_ptr<ContextDeal> contextDeal = std::make_shared<ContextDeal>();
abilityInfo->type = AbilityType::SERVICE;
contextDeal->SetAbilityInfo(abilityInfo);
mockAbility->AttachBaseContext(contextDeal);
abilityImpl->Init(application, record, ability, handler, token, contextDeal);
abilityImpl->Inactive();
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_002 test proc";
abilityImpl->Active();
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_002 test result check";
EXPECT_FALSE(mockAbility->GetWindowFocusChangeStatus());
EXPECT_FALSE(mockAbility->GetWindowFocusStatus());
EXPECT_FALSE(mockAbility->GetTopFocusChangeStatus());
EXPECT_FALSE(mockAbility->GetTopFocusStatus());
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_002 end";
}
/*
* Feature: AbilityImpl
* Function: Active
* SubFunction: NA
* FunctionPoints: Active
* EnvConditions: NA
* CaseDescription: Validate when normally entering a string
*/
HWTEST_F(AbilityImplActiveTest, AaFwk_AbilityImpl_Active_003, TestSize.Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_003 start";
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_003 pretest";
std::shared_ptr<MockAbilityimpl> abilityImpl = std::make_shared<MockAbilityimpl>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
sptr<IRemoteObject> token(new (std::nothrow) MockAbilityToken());
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> record = std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<MockAbilityClass> mockAbility = std::make_shared<MockAbilityClass>();
std::shared_ptr<Ability> ability = std::static_pointer_cast<Ability>(mockAbility);
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(nullptr, nullptr);
std::shared_ptr<ContextDeal> contextDeal = std::make_shared<ContextDeal>();
abilityInfo->type = AbilityType::PAGE;
contextDeal->SetAbilityInfo(abilityInfo);
mockAbility->AttachBaseContext(contextDeal);
abilityImpl->Init(application, record, ability, handler, token, contextDeal);
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_003 test proc";
abilityImpl->Active();
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_003 test result check";
EXPECT_FALSE(mockAbility->GetWindowFocusChangeStatus());
EXPECT_FALSE(mockAbility->GetWindowFocusStatus());
EXPECT_FALSE(mockAbility->GetTopFocusChangeStatus());
EXPECT_FALSE(mockAbility->GetTopFocusStatus());
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_Active_003 end";
}
/*
* Feature: AbilityImpl
* Function: Active
* SubFunction: NA
* FunctionPoints: Active
* EnvConditions: NA
* CaseDescription: Validate when normally entering a string
*/
HWTEST_F(AbilityImplActiveTest, AaFwk_AbilityImpl_InActive_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_001 start";
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_001 pretest";
std::shared_ptr<MockAbilityimpl> abilityImpl = std::make_shared<MockAbilityimpl>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
sptr<IRemoteObject> token(new (std::nothrow) MockAbilityToken());
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> record = std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<MockAbilityClass> mockAbility = std::make_shared<MockAbilityClass>();
std::shared_ptr<Ability> ability = std::static_pointer_cast<Ability>(mockAbility);
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(nullptr, nullptr);
std::shared_ptr<ContextDeal> contextDeal = std::make_shared<ContextDeal>();
abilityInfo->type = AbilityType::PAGE;
contextDeal->SetAbilityInfo(abilityInfo);
mockAbility->AttachBaseContext(contextDeal);
abilityImpl->Init(application, record, ability, handler, token, contextDeal);
abilityImpl->Active();
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_001 test proc";
abilityImpl->Inactive();
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_001 test result check";
EXPECT_TRUE(mockAbility->GetWindowFocusChangeStatus());
EXPECT_FALSE(mockAbility->GetWindowFocusStatus());
EXPECT_TRUE(mockAbility->GetTopFocusChangeStatus());
EXPECT_FALSE(mockAbility->GetTopFocusStatus());
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_001 end";
}
/*
* Feature: AbilityImpl
* Function: Active
* SubFunction: NA
* FunctionPoints: Active
* EnvConditions: NA
* CaseDescription: Validate when normally entering a string
*/
HWTEST_F(AbilityImplActiveTest, AaFwk_AbilityImpl_InActive_002, TestSize.Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_002 start";
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_002 pretest";
std::shared_ptr<MockAbilityimpl> abilityImpl = std::make_shared<MockAbilityimpl>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
sptr<IRemoteObject> token(new (std::nothrow) MockAbilityToken());
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> record = std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<MockAbilityClass> mockAbility = std::make_shared<MockAbilityClass>();
std::shared_ptr<Ability> ability = std::static_pointer_cast<Ability>(mockAbility);
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(nullptr, nullptr);
std::shared_ptr<ContextDeal> contextDeal = std::make_shared<ContextDeal>();
abilityInfo->type = AbilityType::DATA;
contextDeal->SetAbilityInfo(abilityInfo);
mockAbility->AttachBaseContext(contextDeal);
abilityImpl->Init(application, record, ability, handler, token, contextDeal);
abilityImpl->Active();
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_002 test proc";
abilityImpl->Inactive();
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_002 test result check";
EXPECT_FALSE(mockAbility->GetWindowFocusChangeStatus());
EXPECT_FALSE(mockAbility->GetWindowFocusStatus());
EXPECT_FALSE(mockAbility->GetTopFocusChangeStatus());
EXPECT_FALSE(mockAbility->GetTopFocusStatus());
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_002 end";
}
/*
* Feature: AbilityImpl
* Function: Active
* SubFunction: NA
* FunctionPoints: Active
* EnvConditions: NA
* CaseDescription: Validate when normally entering a string
*/
HWTEST_F(AbilityImplActiveTest, AaFwk_AbilityImpl_InActive_003, TestSize.Level1)
{
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_003 start";
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_003 pretest";
std::shared_ptr<MockAbilityimpl> abilityImpl = std::make_shared<MockAbilityimpl>();
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
sptr<IRemoteObject> token(new (std::nothrow) MockAbilityToken());
std::shared_ptr<OHOSApplication> application = std::make_shared<OHOSApplication>();
std::shared_ptr<AbilityLocalRecord> record = std::make_shared<AbilityLocalRecord>(abilityInfo, token);
std::shared_ptr<MockAbilityClass> mockAbility = std::make_shared<MockAbilityClass>();
std::shared_ptr<Ability> ability = std::static_pointer_cast<Ability>(mockAbility);
std::shared_ptr<AbilityHandler> handler = std::make_shared<AbilityHandler>(nullptr, nullptr);
std::shared_ptr<ContextDeal> contextDeal = std::make_shared<ContextDeal>();
abilityInfo->type = AbilityType::PAGE;
contextDeal->SetAbilityInfo(abilityInfo);
mockAbility->AttachBaseContext(contextDeal);
abilityImpl->Init(application, record, ability, handler, token, contextDeal);
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_003 test proc";
abilityImpl->Inactive();
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_003 test result check";
EXPECT_FALSE(mockAbility->GetWindowFocusChangeStatus());
EXPECT_FALSE(mockAbility->GetWindowFocusStatus());
EXPECT_FALSE(mockAbility->GetTopFocusChangeStatus());
EXPECT_FALSE(mockAbility->GetTopFocusStatus());
GTEST_LOG_(INFO) << "AaFwk_AbilityImpl_InActive_003 end";
}
} // namespace AppExecFwk
} // namespace OHOS
+11 -11
View File
@@ -14,7 +14,6 @@
*/
#include <gtest/gtest.h>
#include "ability_context.h"
#include "context_deal.h"
#include "ability_info.h"
@@ -38,7 +37,7 @@ public:
{}
~AbilityPermissionTest()
{}
std::shared_ptr<AbilityContext> context_;
std::shared_ptr<AbilityContext> context_ = nullptr;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
@@ -47,8 +46,8 @@ public:
void AbilityPermissionTest::SetUpTestCase(void)
{
OHOS::sptr<OHOS::IRemoteObject> bundleObject = new BundleMgrService();
OHOS::sptr<OHOS::IRemoteObject> abilityObject = new OHOS::AAFwk::MockAbilityManagerService();
OHOS::sptr<OHOS::IRemoteObject> bundleObject = new (std::nothrow) BundleMgrService();
OHOS::sptr<OHOS::IRemoteObject> abilityObject = new (std::nothrow) AAFwk::MockAbilityManagerService();
auto sysMgr = OHOS::DelayedSingleton<SysMrgClient>::GetInstance();
@@ -93,7 +92,7 @@ HWTEST_F(AbilityPermissionTest, AaFwk_AbilityPermissionTest_VerifySelfPermission
deal->SetApplicationInfo(appInfo);
context_->AttachBaseContext(deal);
EXPECT_EQ(0, context_->VerifySelfPermission(permission_name));
context_->VerifySelfPermission(permission_name);
}
/**
@@ -101,7 +100,8 @@ HWTEST_F(AbilityPermissionTest, AaFwk_AbilityPermissionTest_VerifySelfPermission
* @tc.name: VerifyCallingOrSelfPermission
* @tc.desc: Verify that the VerifyCallingOrSelfPermission return value is correct.
*/
HWTEST_F(AbilityPermissionTest, AaFwk_AbilityPermissionTest_VerifyCallingOrSelfPermission_0100, Function | MediumTest | Level1)
HWTEST_F(AbilityPermissionTest, AaFwk_AbilityPermissionTest_VerifyCallingOrSelfPermission_0100,
Function | MediumTest | Level1)
{
if (context_ == nullptr) {
EXPECT_EQ(true, context_ != nullptr);
@@ -118,7 +118,7 @@ HWTEST_F(AbilityPermissionTest, AaFwk_AbilityPermissionTest_VerifyCallingOrSelfP
context_->AttachBaseContext(deal);
EXPECT_EQ(0, context_->VerifyCallingOrSelfPermission(permission_name));
context_->VerifyCallingOrSelfPermission(permission_name);
}
/**
@@ -143,7 +143,7 @@ HWTEST_F(AbilityPermissionTest, AaFwk_AbilityPermissionTest_VerifyPermission_010
context_->AttachBaseContext(deal);
EXPECT_EQ(0, context_->VerifyPermission(permission_name, 0, 10));
context_->VerifyPermission(permission_name, 0, 10);
}
/**
@@ -167,16 +167,16 @@ HWTEST_F(AbilityPermissionTest, AaFwk_AbilityPermissionTest_CanRequestPermission
deal->SetApplicationInfo(appInfo);
context_->AttachBaseContext(deal);
EXPECT_EQ(true, context_->CanRequestPermission(permission_name));
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)
HWTEST_F(
AbilityPermissionTest, AaFwk_AbilityPermissionTest_RequestPermissionsFromUser_0100, Function | MediumTest | Level1)
{
if (context_ == nullptr) {
EXPECT_EQ(true, context_ != nullptr);
-1
View File
@@ -65,7 +65,6 @@ void AbilityBaseTest::TearDown(void)
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>();
+15 -6
View File
@@ -74,7 +74,14 @@ static void PacMapSetArray(const AAFwk::InterfaceID &id, const std::vector<T1> &
template <typename T1, typename T2, typename T3>
static void PacMapGetArray(const sptr<AAFwk::IArray> &ao, std::vector<T1> &array)
{
auto func = [&](AAFwk::IInterface *object) { array.emplace_back(T2::Unbox(T3::Query(object))); };
auto func = [&](AAFwk::IInterface *object) {
if (object != nullptr) {
T3 *value = T3::Query(object);
if (value != nullptr) {
array.push_back(T2::Unbox(value));
}
}
};
AAFwk::Array::ForEach(ao.GetRefPtr(), func);
}
@@ -414,8 +421,10 @@ bool PacMapNodeTypeArray::MarshallingArrayString(Parcel &parcel) const
{
std::vector<std::u16string> array;
auto func = [&](AAFwk::IInterface *object) {
std::string s = AAFwk::String::Unbox(AAFwk::IString::Query(object));
array.push_back(Str8ToStr16(s));
if (AAFwk::IString::Query(object) != nullptr) {
std::string s = AAFwk::String::Unbox(AAFwk::IString::Query(object));
array.push_back(Str8ToStr16(s));
}
};
AAFwk::Array::ForEach(value_, func);
@@ -555,7 +564,7 @@ bool PacMapNodeTypeArray::UnmarshallingArrayByte(Parcel &parcel)
READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int8Vector, parcel, &value);
for (int i = 0; i < (int)value.size(); i++) {
byteValue.emplace_back(value[i]);
byteValue.push_back(value[i]);
}
PutByteValueArray(byteValue);
return true;
@@ -568,7 +577,7 @@ bool PacMapNodeTypeArray::UnmarshallingArrayBoolean(Parcel &parcel)
READ_PARCEL_AND_RETURN_FALSE_IF_FAIL_ARRAY(Int8Vector, parcel, &value);
for (int i = 0; i < (int)value.size(); i++) {
boolValue.emplace_back((value[i] == 0) ? false : true);
boolValue.push_back((value[i] == 0) ? false : true);
}
PutBooleanValueArray(boolValue);
return true;
@@ -668,7 +677,7 @@ bool PacMapNodeTypeArray::ReadLongVector(Parcel &parcel, std::vector<long> &valu
const uint8_t *pdata = parcel.ReadBuffer(sizeof(long));
if (pdata != nullptr) {
pvalue_ = (long *)pdata;
value.emplace_back(*pvalue_);
value.push_back(*pvalue_);
} else {
return false;
}
@@ -83,7 +83,7 @@ void Char::WriteUTF8Bytes(char *dst, /* [in] */
zchar c, /* [in] */
int size) /* [in] */
{
u_int32_t uc = (u_int32_t)c;
uint32_t uc = (uint32_t)c;
dst += size;
switch (size) {
/* note: everything falls through. */
+9 -7
View File
@@ -222,13 +222,15 @@ bool Operation::operator==(const Operation &other) const
Operation &Operation::operator=(const Operation &other)
{
uri_ = other.uri_;
flags_ = other.flags_;
action_ = other.action_;
deviceId_ = other.deviceId_;
entities_ = other.entities_;
bundleName_ = other.bundleName_;
abilityName_ = other.abilityName_;
if (this != &other) {
uri_ = other.uri_;
flags_ = other.flags_;
action_ = other.action_;
deviceId_ = other.deviceId_;
entities_ = other.entities_;
bundleName_ = other.bundleName_;
abilityName_ = other.abilityName_;
}
return *this;
}
@@ -800,7 +800,7 @@ bool PacMap::ReadFromParcel(Parcel &parcel)
{
int32_t size;
int32_t data_type;
__uint32_t udata_type;
uint32_t udata_type;
// read element count
READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, size);
@@ -844,13 +844,13 @@ bool PacMap::ReadFromParcel(Parcel &parcel)
*/
bool PacMap::Marshalling(Parcel &parcel) const
{
if (IsEmpty()) {
return false;
}
// write element count
WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, data_list_.size());
if (IsEmpty()) {
return true;
}
for (auto it = data_list_.begin(); it != data_list_.end(); it++) {
if (it->second->IsBase()) {
if (!WriteBaseToParcel(it->first, it->second, parcel)) {
+5 -5
View File
@@ -27,7 +27,7 @@ namespace AAFwk {
PatternsMatcher::PatternsMatcher()
{
pattern_ = "";
type_ = MatchType::PATTERN_LITERAL;
type_ = MatchType::DEFAULT;
}
/**
@@ -102,17 +102,17 @@ bool PatternsMatcher::MatchPattern(std::string pattern, std::string match, Match
return false;
}
switch (type) {
case MatchType::PATTERN_LITERAL: {
case MatchType::DEFAULT: {
return pattern == match;
}
case MatchType::PATTERN_PREFIX: {
case MatchType::PREFIX: {
return match.find(pattern) == 0;
}
case MatchType::PATTERN_REGEX: {
case MatchType::PATTERN: {
std::regex regex_(pattern);
return regex_match(match, regex_);
}
case MatchType::PATTERN_SIMPLE_GLOB: {
case MatchType::GLOBAL: {
return GlobPattern(pattern, match);
}
default: {
+19 -20
View File
@@ -285,7 +285,7 @@ std::string Skills::GetPath(int index) const
*/
void Skills::AddPath(const std::string &path)
{
PatternsMatcher pm(path, MatchType::PATTERN_LITERAL);
PatternsMatcher pm(path, MatchType::DEFAULT);
AddPath(pm);
}
@@ -461,7 +461,7 @@ std::string Skills::GetSchemeSpecificPart(int index) const
*/
void Skills::AddSchemeSpecificPart(const std::string &schemeSpecificPart)
{
PatternsMatcher patternsMatcher(schemeSpecificPart, MatchType::PATTERN_LITERAL);
PatternsMatcher patternsMatcher(schemeSpecificPart, MatchType::DEFAULT);
auto it = std::find_if(
schemeSpecificParts_.begin(), schemeSpecificParts_.end(), [&patternsMatcher](const PatternsMatcher pm) {
return (pm.GetPattern() == patternsMatcher.GetPattern()) && (pm.GetType() == patternsMatcher.GetType());
@@ -530,7 +530,7 @@ std::string Skills::GetType(int index) const
*/
void Skills::AddType(const std::string &type)
{
PatternsMatcher pm(type, MatchType::PATTERN_LITERAL);
PatternsMatcher pm(type, MatchType::DEFAULT);
AddType(pm);
}
@@ -726,26 +726,25 @@ int Skills::MatchData(const std::string &type, const std::string &scheme, Uri da
}
std::vector<std::string> schemes = schemes_;
int match = MATCH_CATEGORY_EMPTY;
int match = RESULT_EMPTY;
if (types.empty() && schemes.empty()) {
return (type == std::string() ? (MATCH_CATEGORY_EMPTY + MATCH_ADJUSTMENT_NORMAL) : NO_MATCH_DATA);
return (type == std::string() ? (RESULT_EMPTY + RESULT_NORMAL) : DISMATCH_DATA);
}
if (!schemes.empty()) {
auto it = std::find(schemes.begin(), schemes.end(), scheme);
if (it != schemes.end()) {
match = MATCH_CATEGORY_SCHEME;
match = RESULT_SCHEME;
} else {
return NO_MATCH_DATA;
return DISMATCH_DATA;
}
std::vector<PatternsMatcher> schemeSpecificParts = schemeSpecificParts_;
if (schemeSpecificParts.size() >= 0) {
match = HasSchemeSpecificPart(data.GetSchemeSpecificPart()) ? MATCH_CATEGORY_SCHEME_SPECIFIC_PART
: NO_MATCH_DATA;
match = HasSchemeSpecificPart(data.GetSchemeSpecificPart()) ? RESULT_SCHEME_SPECIFIC_PART : DISMATCH_DATA;
}
if (match != MATCH_CATEGORY_SCHEME_SPECIFIC_PART) {
if (match != RESULT_SCHEME_SPECIFIC_PART) {
std::vector<std::string> authorities = authorities_;
if (authorities.size() >= 0) {
bool authMatch = HasAuthority(data.GetAuthority());
@@ -754,37 +753,37 @@ int Skills::MatchData(const std::string &type, const std::string &scheme, Uri da
if (paths.size() <= 0) {
match = authMatch;
} else if (HasPath(data.GetPath())) {
match = MATCH_CATEGORY_PATH;
match = RESULT_PATH;
} else {
return NO_MATCH_DATA;
return DISMATCH_DATA;
}
} else {
return NO_MATCH_DATA;
return DISMATCH_DATA;
}
}
}
if (match == NO_MATCH_DATA) {
return NO_MATCH_DATA;
if (match == DISMATCH_DATA) {
return DISMATCH_DATA;
}
} else {
if (scheme != std::string() && scheme != "content" && scheme != "file") {
return NO_MATCH_DATA;
return DISMATCH_DATA;
}
}
if (!types.empty()) {
if (FindMimeType(type)) {
match = MATCH_CATEGORY_TYPE;
match = RESULT_TYPE;
} else {
return NO_MATCH_TYPE;
return DISMATCH_TYPE;
}
} else {
if (type != std::string()) {
return NO_MATCH_TYPE;
return DISMATCH_TYPE;
}
}
return match + MATCH_ADJUSTMENT_NORMAL;
return match + RESULT_NORMAL;
}
bool Skills::FindMimeType(const std::string &type)
@@ -43,7 +43,7 @@ const std::string Want::ACTION_HOME("action.system.home");
const std::string Want::ENTITY_HOME("entity.system.home");
const std::string Want::ENTITY_VIDEO("entity.system.video");
const std::string Want::FLAG_HW_HOME_INTENT_FROM_SYSTEM("flag.home.intent.from.system");
const std::string Want::FLAG_HOME_INTENT_FROM_SYSTEM("flag.home.intent.from.system");
const std::string Want::OCT_EQUALSTO("075"); // '='
const std::string Want::OCT_SEMICOLON("073"); // ';'
@@ -469,7 +469,15 @@ std::vector<bool> Want::GetBoolArrayParam(const std::string &key) const
auto value = parameters_.GetParam(key);
IArray *ao = IArray::Query(value);
if (ao != nullptr && Array::IsBooleanArray(ao)) {
auto func = [&](IInterface *object) { array.emplace_back(Boolean::Unbox(IBoolean::Query(object))); };
auto func = [&](IInterface *object) {
if (object != nullptr) {
IBoolean *value = IBoolean::Query(object);
if (value != nullptr) {
array.push_back(Boolean::Unbox(value));
}
}
};
Array::ForEach(ao, func);
}
return array;
@@ -536,7 +544,14 @@ std::vector<byte> Want::GetByteArrayParam(const std::string &key) const
auto value = parameters_.GetParam(key);
IArray *ao = IArray::Query(value);
if (ao != nullptr && Array::IsByteArray(ao)) {
auto func = [&](IInterface *object) { array.emplace_back(Byte::Unbox(IByte::Query(object))); };
auto func = [&](IInterface *object) {
if (object != nullptr) {
IByte *value = IByte::Query(object);
if (value != nullptr) {
array.push_back(Byte::Unbox(value));
}
}
};
Array::ForEach(ao, func);
}
return array;
@@ -603,7 +618,14 @@ std::vector<zchar> Want::GetCharArrayParam(const std::string &key) const
auto value = parameters_.GetParam(key);
IArray *ao = IArray::Query(value);
if (ao != nullptr && Array::IsCharArray(ao)) {
auto func = [&](IInterface *object) { array.emplace_back(Char::Unbox(IChar::Query(object))); };
auto func = [&](IInterface *object) {
if (object != nullptr) {
IChar *value = IChar::Query(object);
if (value != nullptr) {
array.push_back(Char::Unbox(value));
}
}
};
Array::ForEach(ao, func);
}
return array;
@@ -670,7 +692,14 @@ std::vector<int> Want::GetIntArrayParam(const std::string &key) const
auto value = parameters_.GetParam(key);
IArray *ao = IArray::Query(value);
if (ao != nullptr && Array::IsIntegerArray(ao)) {
auto func = [&](IInterface *object) { array.emplace_back(Integer::Unbox(IInteger::Query(object))); };
auto func = [&](IInterface *object) {
if (object != nullptr) {
IInteger *value = IInteger::Query(object);
if (value != nullptr) {
array.push_back(Integer::Unbox(value));
}
}
};
Array::ForEach(ao, func);
}
return array;
@@ -737,7 +766,14 @@ std::vector<double> Want::GetDoubleArrayParam(const std::string &key) const
auto value = parameters_.GetParam(key);
IArray *ao = IArray::Query(value);
if (ao != nullptr && Array::IsDoubleArray(ao)) {
auto func = [&](IInterface *object) { array.emplace_back(Double::Unbox(IDouble::Query(object))); };
auto func = [&](IInterface *object) {
if (object != nullptr) {
IDouble *value = IDouble::Query(object);
if (value != nullptr) {
array.push_back(Double::Unbox(value));
}
}
};
Array::ForEach(ao, func);
}
return array;
@@ -803,7 +839,14 @@ std::vector<float> Want::GetFloatArrayParam(const std::string &key) const
auto value = parameters_.GetParam(key);
IArray *ao = IArray::Query(value);
if (ao != nullptr && Array::IsFloatArray(ao)) {
auto func = [&](IInterface *object) { array.emplace_back(Float::Unbox(IFloat::Query(object))); };
auto func = [&](IInterface *object) {
if (object != nullptr) {
IFloat *value = IFloat::Query(object);
if (value != nullptr) {
array.push_back(Float::Unbox(value));
}
}
};
Array::ForEach(ao, func);
}
return array;
@@ -871,7 +914,14 @@ std::vector<long> Want::GetLongArrayParam(const std::string &key) const
auto value = parameters_.GetParam(key);
IArray *ao = IArray::Query(value);
if (ao != nullptr && Array::IsLongArray(ao)) {
auto func = [&](IInterface *object) { array.emplace_back(Long::Unbox(ILong::Query(object))); };
auto func = [&](IInterface *object) {
if (object != nullptr) {
ILong *value = ILong::Query(object);
if (value != nullptr) {
array.push_back(Long::Unbox(value));
}
}
};
Array::ForEach(ao, func);
}
return array;
@@ -938,7 +988,14 @@ std::vector<short> Want::GetShortArrayParam(const std::string &key) const
auto value = parameters_.GetParam(key);
IArray *ao = IArray::Query(value);
if (ao != nullptr && Array::IsShortArray(ao)) {
auto func = [&](IInterface *object) { array.emplace_back(Short::Unbox(IShort::Query(object))); };
auto func = [&](IInterface *object) {
if (object != nullptr) {
IShort *value = IShort::Query(object);
if (value != nullptr) {
array.push_back(Short::Unbox(value));
}
}
};
Array::ForEach(ao, func);
}
return array;
@@ -1004,7 +1061,14 @@ std::vector<std::string> Want::GetStringArrayParam(const std::string &key) const
auto value = parameters_.GetParam(key);
IArray *ao = IArray::Query(value);
if (ao != nullptr && Array::IsStringArray(ao)) {
auto func = [&](IInterface *object) { array.emplace_back(String::Unbox(IString::Query(object))); };
auto func = [&](IInterface *object) {
if (object != nullptr) {
IString *value = IString::Query(object);
if (value != nullptr) {
array.push_back(String::Unbox(value));
}
}
};
Array::ForEach(ao, func);
}
return array;
@@ -1564,6 +1628,7 @@ bool Want::ReadFromParcel(Parcel &parcel)
if (params != nullptr) {
parameters_ = *params;
delete params;
params = nullptr;
} else {
return false;
}
@@ -27,10 +27,40 @@
#include "ohos/aafwk/base/float_wrapper.h"
#include "ohos/aafwk/base/double_wrapper.h"
#include "ohos/aafwk/base/string_wrapper.h"
#include "want_params_wrapper.h"
#include "ohos/aafwk/base/zchar_wrapper.h"
namespace OHOS {
namespace AAFwk {
std::string WantParams::GetStringByType(const sptr<IInterface> iIt, int typeId)
{
if (typeId == VALUE_TYPE_BOOLEAN) {
return static_cast<Boolean *>(IBoolean::Query(iIt))->ToString();
} else if (typeId == VALUE_TYPE_BYTE) {
return static_cast<Byte *>(IByte::Query(iIt))->ToString();
} else if (typeId == VALUE_TYPE_CHAR) {
return static_cast<Char *>(IChar::Query(iIt))->ToString();
} else if (typeId == VALUE_TYPE_SHORT) {
return static_cast<Short *>(IShort::Query(iIt))->ToString();
} else if (typeId == VALUE_TYPE_INT) {
return static_cast<Integer *>(IInteger::Query(iIt))->ToString();
} else if (typeId == VALUE_TYPE_LONG) {
return static_cast<Long *>(ILong::Query(iIt))->ToString();
} else if (typeId == VALUE_TYPE_FLOAT) {
return static_cast<Float *>(IFloat::Query(iIt))->ToString();
} else if (typeId == VALUE_TYPE_DOUBLE) {
return static_cast<Double *>(IDouble::Query(iIt))->ToString();
} else if (typeId == VALUE_TYPE_STRING) {
return static_cast<String *>(IString::Query(iIt))->ToString();
} else if (typeId == VALUE_TYPE_ARRAY) {
return static_cast<Array *>(IArray::Query(iIt))->ToString();
} else {
return "";
}
return "";
}
template <typename T1, typename T2, typename T3>
static void SetNewArray(const AAFwk::InterfaceID &id, AAFwk::IArray *orgIArray, sptr<AAFwk::IArray> &ao);
/**
* @description: A constructor used to create an IntentParams instance by using the parameters of an existing
* IntentParams object.
@@ -39,10 +69,75 @@ namespace AAFwk {
WantParams::WantParams(const WantParams &wantParams)
{
params_.clear();
for (auto it : wantParams.params_) {
params_.insert(make_pair(it.first, it.second));
NewParams(wantParams, *this);
}
// inner use function
bool WantParams::NewParams(const WantParams &source, WantParams &dest)
{
// Deep copy
for (auto it = source.params_.begin(); it != source.params_.end(); it++) {
sptr<IInterface> o = it->second;
if (IString::Query(o) != nullptr) {
dest.params_[it->first] = String::Box(String::Unbox(IString::Query(o)));
} else if (IBoolean::Query(o) != nullptr) {
dest.params_[it->first] = Boolean::Box(Boolean::Unbox(IBoolean::Query(o)));
} else if (IByte::Query(o) != nullptr) {
dest.params_[it->first] = Byte::Box(Byte::Unbox(IByte::Query(o)));
} else if (IChar::Query(o) != nullptr) {
dest.params_[it->first] = Char::Box(Char::Unbox(IChar::Query(o)));
} else if (IShort::Query(o) != nullptr) {
dest.params_[it->first] = Short::Box(Short::Unbox(IShort::Query(o)));
} else if (IInteger::Query(o) != nullptr) {
dest.params_[it->first] = Integer::Box(Integer::Unbox(IInteger::Query(o)));
} else if (ILong::Query(o) != nullptr) {
dest.params_[it->first] = Long::Box(Long::Unbox(ILong::Query(o)));
} else if (IFloat::Query(o) != nullptr) {
dest.params_[it->first] = Float::Box(Float::Unbox(IFloat::Query(o)));
} else if (IDouble::Query(o) != nullptr) {
dest.params_[it->first] = Double::Box(Double::Unbox(IDouble::Query(o)));
} else if (IWantParams::Query(o) != nullptr) {
WantParams newDest(WantParamWrapper::Unbox(IWantParams::Query(o)));
dest.params_[it->first] = WantParamWrapper::Box(newDest);
} else if (IArray::Query(o) != nullptr) {
sptr<IArray> destAO = nullptr;
if (!NewArrayData(IArray::Query(o), destAO)) {
continue;
}
dest.params_[it->first] = destAO;
}
}
return true;
} // namespace AAFwk
// inner use
bool WantParams::NewArrayData(IArray *source, sptr<IArray> &dest)
{
if (Array::IsBooleanArray(source)) {
SetNewArray<bool, AAFwk::Boolean, AAFwk::IBoolean>(AAFwk::g_IID_IBoolean, source, dest);
} else if (Array::IsCharArray(source)) {
SetNewArray<char, AAFwk::Char, AAFwk::IChar>(AAFwk::g_IID_IChar, source, dest);
} else if (Array::IsByteArray(source)) {
SetNewArray<byte, AAFwk::Byte, AAFwk::IByte>(AAFwk::g_IID_IByte, source, dest);
} else if (Array::IsShortArray(source)) {
SetNewArray<short, AAFwk::Short, AAFwk::IShort>(AAFwk::g_IID_IShort, source, dest);
} else if (Array::IsIntegerArray(source)) {
SetNewArray<int, AAFwk::Integer, AAFwk::IInteger>(AAFwk::g_IID_IInteger, source, dest);
} else if (Array::IsLongArray(source)) {
SetNewArray<long, AAFwk::Long, AAFwk::ILong>(AAFwk::g_IID_ILong, source, dest);
} else if (Array::IsFloatArray(source)) {
SetNewArray<float, AAFwk::Float, AAFwk::IFloat>(AAFwk::g_IID_IFloat, source, dest);
} else if (Array::IsDoubleArray(source)) {
SetNewArray<double, AAFwk::Double, AAFwk::IDouble>(AAFwk::g_IID_IDouble, source, dest);
} else if (Array::IsStringArray(source)) {
SetNewArray<std::string, AAFwk::String, AAFwk::IString>(AAFwk::g_IID_IString, source, dest);
} else {
return false;
}
if (dest == nullptr) {
return false;
}
return true;
}
/**
* @description: A WantParams used to
@@ -51,9 +146,122 @@ WantParams::WantParams(const WantParams &wantParams)
*/
WantParams &WantParams::operator=(const WantParams &other)
{
params_ = other.params_;
if (this != &other) {
params_.clear();
NewParams(other, *this);
}
return *this;
}
bool WantParams::operator==(const WantParams &other)
{
if (this->params_.size() != other.params_.size()) {
return false;
}
for (auto itthis : this->params_) {
auto itother = other.params_.find(itthis.first);
if (itother == other.params_.end()) {
return false;
}
if (!CompareInterface(itother->second, itthis.second, WantParams::GetDataType(itother->second))) {
return false;
}
}
return true;
}
#define GETWRAPDATATYPE(id, value, ret) \
do { \
if (value != nullptr && id::Query(value) != nullptr) { \
return ret; \
} else { \
break; \
} \
} while (0)
#define GETSPTRBYTYPE(type, typeid, typeClass, str) \
do { \
if (type == typeid) { \
return typeClass::Parse(str); \
} \
} while (0)
int WantParams::GetDataType(const sptr<IInterface> iIt)
{
GETWRAPDATATYPE(IBoolean, iIt, VALUE_TYPE_BOOLEAN);
GETWRAPDATATYPE(IByte, iIt, VALUE_TYPE_BYTE);
GETWRAPDATATYPE(IChar, iIt, VALUE_TYPE_CHAR);
GETWRAPDATATYPE(IShort, iIt, VALUE_TYPE_SHORT);
GETWRAPDATATYPE(IInteger, iIt, VALUE_TYPE_INT);
GETWRAPDATATYPE(ILong, iIt, VALUE_TYPE_LONG);
GETWRAPDATATYPE(IFloat, iIt, VALUE_TYPE_FLOAT);
GETWRAPDATATYPE(IDouble, iIt, VALUE_TYPE_DOUBLE);
GETWRAPDATATYPE(IString, iIt, VALUE_TYPE_STRING);
GETWRAPDATATYPE(IArray, iIt, VALUE_TYPE_ARRAY);
GETWRAPDATATYPE(IWantParams, iIt, VALUE_TYPE_WANTPARAMS);
return VALUE_TYPE_NULL;
}
sptr<IInterface> WantParams::GetInterfaceByType(int typeId, const std::string &value)
{
GETSPTRBYTYPE(VALUE_TYPE_BOOLEAN, typeId, Boolean, value);
GETSPTRBYTYPE(VALUE_TYPE_BYTE, typeId, Byte, value);
GETSPTRBYTYPE(VALUE_TYPE_CHAR, typeId, Char, value);
GETSPTRBYTYPE(VALUE_TYPE_SHORT, typeId, Short, value);
GETSPTRBYTYPE(VALUE_TYPE_INT, typeId, Integer, value);
GETSPTRBYTYPE(VALUE_TYPE_LONG, typeId, Long, value);
GETSPTRBYTYPE(VALUE_TYPE_FLOAT, typeId, Float, value);
GETSPTRBYTYPE(VALUE_TYPE_DOUBLE, typeId, Double, value);
GETSPTRBYTYPE(VALUE_TYPE_STRING, typeId, String, value);
GETSPTRBYTYPE(VALUE_TYPE_ARRAY, typeId, Array, value);
return nullptr;
}
bool WantParams::CompareInterface(const sptr<IInterface> iIt1, const sptr<IInterface> iIt2, int typeId)
{
bool flag = false;
switch (typeId) {
case VALUE_TYPE_BOOLEAN:
flag =
static_cast<Boolean *>(IBoolean::Query(iIt1))->Equals(*(static_cast<Boolean *>(IBoolean::Query(iIt1))));
break;
case VALUE_TYPE_BYTE:
flag = static_cast<Byte *>(IByte::Query(iIt1))->Equals(*(static_cast<Byte *>(IByte::Query(iIt1))));
break;
case VALUE_TYPE_CHAR:
flag = static_cast<Char *>(IChar::Query(iIt1))->Equals(*(static_cast<Char *>(IChar::Query(iIt1))));
break;
case VALUE_TYPE_SHORT:
flag = static_cast<Short *>(IShort::Query(iIt1))->Equals(*(static_cast<Short *>(IShort::Query(iIt1))));
break;
case VALUE_TYPE_INT:
flag =
static_cast<Integer *>(IInteger::Query(iIt1))->Equals(*(static_cast<Integer *>(IInteger::Query(iIt1))));
break;
case VALUE_TYPE_LONG:
flag = static_cast<Long *>(ILong::Query(iIt1))->Equals(*(static_cast<Long *>(ILong::Query(iIt1))));
break;
case VALUE_TYPE_FLOAT:
flag = static_cast<Float *>(IFloat::Query(iIt1))->Equals(*(static_cast<Float *>(IFloat::Query(iIt1))));
break;
case VALUE_TYPE_DOUBLE:
flag = static_cast<Double *>(IDouble::Query(iIt1))->Equals(*(static_cast<Double *>(IDouble::Query(iIt1))));
break;
case VALUE_TYPE_STRING:
flag = static_cast<String *>(IString::Query(iIt1))->Equals(*(static_cast<String *>(IString::Query(iIt1))));
break;
case VALUE_TYPE_ARRAY:
flag = static_cast<Array *>(IArray::Query(iIt1))->Equals(*(static_cast<Array *>(IArray::Query(iIt1))));
break;
case VALUE_TYPE_WANTPARAMS:
flag = static_cast<WantParamWrapper *>(IWantParams::Query(iIt1))
->Equals(*(static_cast<WantParamWrapper *>(IWantParams::Query(iIt1))));
break;
default:
break;
}
return flag;
}
/**
* @description: Sets a parameter in key-value pair format.
* @param key Indicates the key matching the parameter.
@@ -159,7 +367,14 @@ bool WantParams::WriteToParcelBool(Parcel &parcel, sptr<IInterface> &o) const
}
return parcel.WriteInt8(value);
}
bool WantParams::WriteToParcelWantParams(Parcel &parcel, sptr<IInterface> &o) const
{
WantParams value = WantParamWrapper::Unbox(IWantParams::Query(o));
if (!parcel.WriteInt32(VALUE_TYPE_WANTPARAMS)) {
return false;
}
return parcel.WriteString16(Str8ToStr16(static_cast<WantParamWrapper *>(IWantParams::Query(o))->ToString()));
}
bool WantParams::WriteToParcelByte(Parcel &parcel, sptr<IInterface> &o) const
{
byte value = Byte::Unbox(IByte::Query(o));
@@ -241,6 +456,8 @@ bool WantParams::WriteMarshalling(Parcel &parcel, sptr<IInterface> &o) const
return WriteToParcelLong(parcel, o);
} else if (IFloat::Query(o) != nullptr) {
return WriteToParcelFloat(parcel, o);
} else if (IWantParams::Query(o) != nullptr) {
return WriteToParcelWantParams(parcel, o);
} else if (IDouble::Query(o) != nullptr) {
return WriteToParcelDouble(parcel, o);
} else {
@@ -301,9 +518,44 @@ static bool SetArray(const InterfaceID &id, const std::vector<T1> &value, sptr<I
template <typename T1, typename T2, typename T3>
static void FillArray(IArray *ao, std::vector<T1> &array)
{
auto func = [&](IInterface *object) { array.push_back(T2::Unbox(T3::Query(object))); };
auto func = [&](IInterface *object) {
if (object != nullptr) {
T3 *value = T3::Query(object);
if (value != nullptr) {
array.push_back(T2::Unbox(value));
}
}
};
Array::ForEach(ao, func);
}
// inner use template function
template <typename T1, typename T2, typename T3>
static void SetNewArray(const AAFwk::InterfaceID &id, AAFwk::IArray *orgIArray, sptr<AAFwk::IArray> &ao)
{
if (orgIArray == nullptr) {
return;
}
std::vector<T1> array;
auto func = [&](IInterface *object) {
if (object != nullptr) {
T3 *value = T3::Query(object);
if (value != nullptr) {
array.push_back(T2::Unbox(value));
}
}
};
Array::ForEach(orgIArray, func);
typename std::vector<T1>::size_type size = array.size();
if (size > 0) {
ao = new (std::nothrow) AAFwk::Array(size, id);
if (ao != nullptr) {
for (typename std::vector<T1>::size_type i = 0; i < size; i++) {
ao->Set(i, T2::Box(array[i]));
}
}
}
}
bool WantParams::WriteArrayToParcelString(Parcel &parcel, IArray *ao) const
{
@@ -660,7 +912,15 @@ bool WantParams::ReadFromParcelInt(Parcel &parcel, const std::string &key)
return false;
}
}
bool WantParams::ReadFromParcelWantParamWrapper(Parcel &parcel, const std::string &key)
{
std::u16string value = parcel.ReadString16();
sptr<IInterface> intf = WantParamWrapper::Parse(Str16ToStr8(value));
if (intf) {
SetParam(key, intf);
}
return true;
}
bool WantParams::ReadFromParcelLong(Parcel &parcel, const std::string &key)
{
int64_t value;
@@ -724,6 +984,8 @@ bool WantParams::ReadFromParcelParam(Parcel &parcel, const std::string &key, int
return ReadFromParcelFloat(parcel, key);
case VALUE_TYPE_DOUBLE:
return ReadFromParcelDouble(parcel, key);
case VALUE_TYPE_WANTPARAMS:
return ReadFromParcelWantParamWrapper(parcel, key);
case VALUE_TYPE_NULL:
break;
default: {
@@ -0,0 +1,151 @@
/*
* 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 "ohos/aafwk/content/want_params_wrapper.h"
#include <algorithm>
namespace OHOS {
namespace AAFwk {
IINTERFACE_IMPL_1(WantParamWrapper, Object, IWantParams);
const InterfaceID g_IID_IWantParams = {
0xa75b9db6, 0x9813, 0x4371, 0x8848, {0xd, 0x2, 0x9, 0x6, 0x6, 0xc, 0xe, 0x6, 0xe, 0xc, 0x6, 0x8}};
ErrCode WantParamWrapper::GetValue(WantParams &value)
{
value = wantParams_;
return ERR_OK;
}
bool WantParamWrapper::Equals(IObject &other)
{
WantParamWrapper *otherObj = static_cast<WantParamWrapper *>(IWantParams::Query(&other));
return otherObj != nullptr && otherObj->wantParams_ == wantParams_;
}
std::string WantParamWrapper::ToString()
{
std::string result;
if (wantParams_.Size() != 0) {
result += "{";
for (auto it : wantParams_.GetParams()) {
int typeId = WantParams::GetDataType(it.second);
result = result + "\"" + it.first + "\":{\"" + std::to_string(typeId) + "\":";
if (IWantParams::Query(it.second) != nullptr) {
result = result + static_cast<WantParamWrapper *>(IWantParams::Query(it.second))->ToString();
} else {
result = result + "\"" + WantParams::GetStringByType(it.second, typeId) + "\"";
}
if (it == *wantParams_.GetParams().rbegin()) {
result += "}";
} else {
result += "},";
}
}
result += "}";
} else {
result = "{}";
}
return result;
}
sptr<IWantParams> WantParamWrapper::Box(const WantParams &value)
{
sptr<IWantParams> object = new (std::nothrow)WantParamWrapper(value);
return object;
}
WantParams WantParamWrapper::Unbox(IWantParams *object)
{
WantParams value;
if (object != nullptr) {
object->GetValue(value);
}
return value;
}
bool WantParamWrapper::ValidateStr(const std::string &str)
{
if (str == "" || str == "{}" || str == "{\"\"}") {
return false;
}
if (count(str.begin(), str.end(), '\"') % 2 != 0) {
return false;
}
if (count(str.begin(), str.end(), '{') != count(str.begin(), str.end(), '}')) {
return false;
}
int count = 0;
for (auto it : str) {
if (it == '{') {
count++;
}
if (it == '}') {
count--;
}
if (count < 0) {
return false;
}
}
return true;
}
sptr<IWantParams> WantParamWrapper::Parse(const std::string &str)
{
WantParams wantPaqrams;
std::string key = "";
int typeId = 0;
if (ValidateStr(str)) {
for (unsigned int strnum = 0; strnum < str.size(); strnum++) {
if (str[strnum] == '{' && key != "" && typeId == WantParams::VALUE_TYPE_WANTPARAMS) {
unsigned int num;
int count = 0;
for (num = strnum; num < str.size(); num++) {
if (str[num] == '{') {
count++;
} else if (str[num] == '}') {
count--;
}
if (count == 0) {
break;
}
}
wantPaqrams.SetParam(key, WantParamWrapper::Parse(str.substr(strnum, num - strnum)));
key = "";
typeId = 0;
strnum = num + 1;
} else if (str[strnum] == '"') {
if (key == "") {
strnum++;
key = str.substr(strnum, str.find('"', strnum) - strnum);
strnum = str.find('"', strnum);
} else if (typeId == 0) {
strnum++;
typeId = atoi(str.substr(strnum, str.find('"', strnum) - strnum).c_str());
if (errno == ERANGE) {
return nullptr;
}
strnum = str.find('"', strnum);
} else {
strnum++;
wantPaqrams.SetParam(key,
WantParams::GetInterfaceByType(typeId, str.substr(strnum, str.find('"', strnum) - strnum)));
strnum = str.find('"', strnum);
typeId = 0;
key = "";
}
}
}
}
sptr<IWantParams> iwantParams = new WantParamWrapper(wantPaqrams);
return iwantParams;
}
} // namespace AAFwk
} // namespace OHOS
@@ -0,0 +1,66 @@
/*
* 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_WANT_PARAMS_WRAPPER_H
#define OHOS_AAFWK_WANT_PARAMS_WRAPPER_H
#include "ohos/aafwk/content/want_params.h"
#include "ohos/aafwk/base/base_def.h"
#include "ohos/aafwk/base/base_object.h"
namespace OHOS {
namespace AAFwk {
class WantParams;
INTERFACE(IWantParams, a75b9db6 - 9813 - 4371 - 8848 - d2966ce6ec68)
{
inline static IWantParams *Query(IInterface * object)
{
if (object == nullptr) {
return nullptr;
}
return static_cast<IWantParams *>(object->Query(g_IID_IWantParams));
}
virtual ErrCode GetValue(WantParams & value) = 0;
};
class WantParamWrapper final : public Object, public IWantParams {
public:
inline WantParamWrapper(const WantParams &value) : wantParams_(value)
{}
inline ~WantParamWrapper()
{}
IINTERFACE_DECL();
ErrCode GetValue(WantParams &value) override;
bool Equals(IObject &other) override;
std::string ToString() override;
static sptr<IWantParams> Box(const WantParams &value);
static WantParams Unbox(IWantParams *object);
static bool ValidateStr(const std::string &str);
static sptr<IWantParams> Parse(const std::string &str);
static constexpr char SIGNATURE = 'W';
private:
WantParams wantParams_;
};
} // namespace AAFwk
} // namespace OHOS
#endif // OHOS_AAFWK_WANT_PARAMS_WRAPPER_H
+37
View File
@@ -31,6 +31,21 @@ config("module_private_config") {
]
}
config("module_private_want_param_wrapper_config") {
visibility = [ ":*" ]
include_dirs = [
"//utils/native/base/include",
"//sdk/appexecfwk/appexecfwk_base/include",
"//foundation/aafwk/standard/interfaces/innerkits/want/include",
"//foundation/aafwk/standard/frameworks/kits/content/cpp/src",
]
defines = [
"APP_LOG_TAG = \"WantUnitTest\"",
"LOG_DOMAIN = 0xD002210",
]
}
ohos_unittest("intent_parcelable_test") {
module_out_path = module_output_path
sources = []
@@ -243,6 +258,7 @@ ohos_unittest("want_params_test") {
module_out_path = module_output_path
sources = [
"../src/ohos/aafwk/content/want_params.cpp",
"../src/ohos/aafwk/content/want_params_wrapper.cpp",
"unittest/common/want_params_test.cpp",
]
@@ -260,6 +276,26 @@ ohos_unittest("want_params_test") {
external_deps = [ "appexecfwk_standard:appexecfwk_base" ]
}
ohos_unittest("want_params_wrapper_test") {
module_out_path = module_output_path
sources = [
"../src/ohos/aafwk/content/want_params.cpp",
"../src/ohos/aafwk/content/want_params_wrapper.cpp",
"unittest/common/want_params_wrapper_test.cpp",
]
configs = [ ":module_private_want_param_wrapper_config" ]
deps = [
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [ "appexecfwk_standard:appexecfwk_base" ]
}
ohos_unittest("want_test") {
module_out_path = module_output_path
sources = [
@@ -304,6 +340,7 @@ group("unittest") {
":patterns_matcher_test",
":skills_test",
":want_params_test",
":want_params_wrapper_test",
":want_test",
]
}
@@ -1,190 +0,0 @@
/*
* 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 "ohos/aafwk/content/intent.h"
using namespace testing::ext;
using namespace OHOS;
using namespace AAFwk;
using OHOS::AppExecFwk::ElementName;
static const int LARGE_STR_LEN = 65534;
static const int SET_COUNT = 20;
static const int LOOP_TEST = 1000;
class IntentBaseTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
public:
Intent *intentInst = nullptr;
};
void IntentBaseTest::SetUpTestCase(void)
{}
void IntentBaseTest::TearDownTestCase(void)
{}
void IntentBaseTest::SetUp(void)
{
intentInst = new (std::nothrow) Intent();
}
void IntentBaseTest::TearDown(void)
{
delete (intentInst);
intentInst = nullptr;
}
/*
* Feature: Intent
* Function: SetElement & GetElement
* SubFunction: NA
* FunctionPoints: SetElement & GetElement
* EnvConditions:NA
* CaseDescription: Verify SetElement & GetElement
*/
HWTEST_F(IntentBaseTest, AaFwk_Intent_Element_013, TestSize.Level1)
{
ElementName emptyElement;
std::string bundleName = "bundle";
std::string abilityName = "ability";
std::string sliceName = "slice";
EXPECT_EQ(emptyElement, intentInst->GetElement());
ElementName element(bundleName, abilityName, sliceName);
intentInst->SetElement(element);
ElementName newElement = intentInst->GetElement();
EXPECT_EQ(element, newElement);
}
/*
* Feature: Intent
* Function: SetEntity/GetEntity
* SubFunction: NA
* FunctionPoints: SetEntity/GetEntity
* EnvConditions: NA
* CaseDescription: Verify the function when the input string is empty
*/
HWTEST_F(IntentBaseTest, AaFwk_Intent_Entity_001, TestSize.Level1)
{
std::string setValue;
intentInst->SetEntity(setValue);
EXPECT_EQ(setValue, intentInst->GetEntity());
}
/*
* Feature: Intent
* Function: SetEntity/GetEntity
* SubFunction: NA
* FunctionPoints: SetEntity/GetEntity
* EnvConditions: NA
* CaseDescription: Verify the function when the input string contains special characters
*/
HWTEST_F(IntentBaseTest, AaFwk_Intent_Entity_002, TestSize.Level1)
{
std::string setValue("@#¥#3243adsafdf_中文");
intentInst->SetEntity(setValue);
EXPECT_EQ(setValue, intentInst->GetEntity());
}
/*
* Feature: Intent
* Function: SetEntity/GetEntity
* SubFunction: NA
* FunctionPoints: SetEntity/GetEntity
* EnvConditions: NA
* CaseDescription: Verify the function when the input string has a long size
*/
HWTEST_F(IntentBaseTest, AaFwk_Intent_Entity_003, TestSize.Level1)
{
std::string setValue(LARGE_STR_LEN, 's');
intentInst->SetEntity(setValue);
EXPECT_EQ(setValue, intentInst->GetEntity());
}
/*
* Feature: Intent
* Function: SetEntity/GetEntity
* SubFunction: NA
* FunctionPoints: SetEntity/GetEntity
* EnvConditions: NA
* CaseDescription: Verify the function when the input string is overrode
*/
HWTEST_F(IntentBaseTest, AaFwk_Intent_Entity_004, TestSize.Level1)
{
std::string setValue1("1234");
intentInst->SetEntity(setValue1);
std::string setValue2("abcd");
intentInst->SetEntity(setValue2);
EXPECT_EQ(setValue2, intentInst->GetEntity());
}
/*
* Feature: Intent
* Function: SetEntity/GetEntity
* SubFunction: NA
* FunctionPoints: SetEntity/GetEntity
* EnvConditions: NA
* CaseDescription: Verify the function when the input string is set 20 times
*/
HWTEST_F(IntentBaseTest, AaFwk_Intent_Entity_005, TestSize.Level1)
{
std::string setValue("1234");
for (int i = 0; i < SET_COUNT; i++) {
intentInst->SetEntity(setValue);
}
EXPECT_EQ(setValue, intentInst->GetEntity());
}
/*
* Feature: Intent
* Function: SetEntity/GetEntity
* SubFunction: NA
* FunctionPoints: SetEntity/GetEntity
* EnvConditions: NA
* CaseDescription: Verify the function when the input string is default
*/
HWTEST_F(IntentBaseTest, AaFwk_Intent_Entity_006, TestSize.Level1)
{
std::string setValue;
EXPECT_EQ(setValue, intentInst->GetEntity());
}
/*
* Feature: Intent
* Function: SetEntity/GetEntity
* SubFunction: NA
* FunctionPoints: SetEntity/GetEntity
* EnvConditions: NA
* CaseDescription: Verify the function when the input string contains special characters
*/
HWTEST_F(IntentBaseTest, AaFwk_Intent_Entity_007, TestSize.Level1)
{
std::string setValue("@#¥#3243adsafdf_中文");
for (int i = 0; i < LOOP_TEST; i++) {
intentInst->SetEntity(setValue);
EXPECT_EQ(setValue, intentInst->GetEntity());
}
}
@@ -1,164 +0,0 @@
/*
* 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 <cstring>
#include "ohos/aafwk/base/string_wrapper.h"
#include "ohos/aafwk/content/intent_params.h"
using namespace testing::ext;
using namespace OHOS::AAFwk;
static const int LARGE_STR_LEN = 65534;
using testParamsType = std::tuple<std::string, std::string>;
class IntentParamsTest : public testing::TestWithParam<testParamsType> {
public:
IntentParamsTest() : intentParam_(nullptr)
{}
~IntentParamsTest()
{
intentParam_ = nullptr;
}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
IntentParams *intentParam_;
};
void IntentParamsTest::SetUpTestCase(void)
{}
void IntentParamsTest::TearDownTestCase(void)
{}
void IntentParamsTest::SetUp(void)
{
intentParam_ = new (std::nothrow) IntentParams();
}
void IntentParamsTest::TearDown(void)
{
delete intentParam_;
intentParam_ = nullptr;
}
/*
* Feature: IntentParams
* Function: SetParam
* SubFunction: NA
* FunctionPoints: SetParam
* EnvConditions: NA
* CaseDescription: Verify whether parameter change.
*/
HWTEST_P(IntentParamsTest, AaFwk_IntentParams_Params, TestSize.Level1)
{
std::string keyStr = std::get<0>(GetParam());
std::string valueStr = std::get<1>(GetParam());
intentParam_->SetParam(keyStr, String::Box(valueStr));
EXPECT_EQ(valueStr, Object::ToString(intentParam_->GetParam(keyStr)));
}
INSTANTIATE_TEST_CASE_P(IntentParamsTestCaseP, IntentParamsTest,
testing::Values(testParamsType("", "asdsdsdasa"), testParamsType(std::string(LARGE_STR_LEN + 1, 's'), "sadsdsdads"),
testParamsType("#$%^&*(!@\":<>{}", "asdsdsdasa"), testParamsType("3456677", ""),
testParamsType("1234", std::string(LARGE_STR_LEN + 1, 's')),
testParamsType("2323sdasdZ", "#$%^&*(!@\":<>{}sadsdasdsaf"), testParamsType("12345667", "sdasdfdsffdgfdg"),
testParamsType("", ""),
testParamsType(std::string(LARGE_STR_LEN + 1, 'k'), std::string(LARGE_STR_LEN + 1, 'k')),
testParamsType("#$%^&*(!@\":<>{},/", "#$%^&*(!@\":<>{},/")));
/*
* Feature: IntentParams
* Function: SetParam
* SubFunction: NA
* FunctionPoints: SetParam
* EnvConditions: NA
* CaseDescription: Verify whether the insertion can be overwritten.
*/
HWTEST_F(IntentParamsTest, AaFwk_IntentParams_Params_001, TestSize.Level1)
{
std::string keyStr("123456");
std::string firstValueStr("abcdse");
intentParam_->SetParam(keyStr, String::Box(firstValueStr));
std::string secondValueStr("dffghghhg");
intentParam_->SetParam(keyStr, String::Box(secondValueStr));
EXPECT_EQ(secondValueStr, Object::ToString(intentParam_->GetParam(keyStr)));
}
/*
* Feature: IntentParams
* Function: SetParam
* SubFunction: NA
* FunctionPoints: SetParam
* EnvConditions: NA
* CaseDescription: Verify whether the GetParams can get empty params_.
*/
HWTEST_F(IntentParamsTest, AaFwk_IntentParams_Params_002, TestSize.Level1)
{
auto resultMap = intentParam_->GetParams();
EXPECT_EQ(0UL, resultMap.size());
}
/*
* Feature: IntentParams
* Function: SetParam
* SubFunction: NA
* FunctionPoints: SetParam
* EnvConditions: NA
* CaseDescription: Verify whether the GetParams can get normal params_.
*/
HWTEST_F(IntentParamsTest, AaFwk_IntentParams_Params_003, TestSize.Level1)
{
std::string firstKeyStr("123456");
std::string firstValueStr("abcdse");
intentParam_->SetParam(firstKeyStr, String::Box(firstValueStr));
std::string secondKeyStr("@#¥#¥中文%");
std::string secondValueStr("*%¥#_中文");
intentParam_->SetParam(secondKeyStr, String::Box(secondValueStr));
auto resultMap = intentParam_->GetParams();
EXPECT_EQ(2UL, resultMap.size());
auto firstIt = resultMap.find(firstKeyStr);
EXPECT_NE(firstIt, resultMap.end());
EXPECT_EQ(firstValueStr, Object::ToString(firstIt->second));
auto secondIt = resultMap.find(secondKeyStr);
EXPECT_NE(secondIt, resultMap.end());
EXPECT_EQ(secondValueStr, Object::ToString(secondIt->second));
}
/*
* Feature: IntentParams
* Function: HasParam
* SubFunction: NA
* FunctionPoints: HasParam
* EnvConditions: NA
* CaseDescription: Verify if param exist.
*/
HWTEST_F(IntentParamsTest, AaFwk_IntentParams_Params_004, TestSize.Level1)
{
std::string keyStr("abc");
std::string keyStrNotExist("def");
std::string valueStr("ghi");
intentParam_->SetParam(keyStr, String::Box(valueStr));
EXPECT_EQ(true, intentParam_->HasParam(keyStr));
EXPECT_EQ(false, intentParam_->HasParam(keyStrNotExist));
}
@@ -1,542 +0,0 @@
/*
* 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 <tuple>
#include "ohos/aafwk/content/intent.h"
#include "parcel.h"
using namespace testing::ext;
using namespace OHOS::AAFwk;
using OHOS::Parcel;
using OHOS::AppExecFwk::ElementName;
class IntentParcelableTest : public testing::Test {
public:
IntentParcelableTest()
{}
~IntentParcelableTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
enum {
FLAG_TEST_SINGLE = 0x01,
FLAG_TEST_ARRAY = 0x02,
FLAG_TEST_BOTH = 0x03,
};
bool CompareIntent(Intent &intent1, Intent &intent2, std::map<std::string, std::string> &keys);
void SendParcelTest(Intent &intent, std::map<std::string, std::string> &keys);
void AddBoolParams(Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag);
void AddByteParams(Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag);
void AddCharParams(Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag);
void AddShortParams(Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag);
void AddIntParams(Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag);
void AddLongParams(Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag);
void AddFloatParams(Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag);
void AddDoubleParams(Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag);
void AddStringParams(Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag);
std::string boolType = "bool";
std::string boolArrayType = "boolArray";
std::string byteType = "byte";
std::string byteArrayType = "byteArray";
std::string charType = "char";
std::string charArrayType = "charArray";
std::string shortType = "short";
std::string shortArrayType = "shortArray";
std::string intType = "int";
std::string intArrayType = "intArray";
std::string longType = "long";
std::string longArrayType = "longArray";
std::string floatType = "float";
std::string floatArrayType = "floatArray";
std::string doubleType = "double";
std::string doubleArrayType = "doubleArray";
std::string stringType = "string";
std::string stringArrayType = "stringArray";
};
void IntentParcelableTest::SetUpTestCase(void)
{}
void IntentParcelableTest::TearDownTestCase(void)
{}
void IntentParcelableTest::SetUp(void)
{}
void IntentParcelableTest::TearDown(void)
{}
bool IntentParcelableTest::CompareIntent(Intent &intent1, Intent &intent2, std::map<std::string, std::string> &keys)
{
EXPECT_EQ(intent1.GetAction(), intent2.GetAction());
EXPECT_EQ(intent1.GetEntity(), intent2.GetEntity());
EXPECT_EQ(intent1.GetFlags(), intent2.GetFlags());
EXPECT_EQ(intent1.GetElement(), intent2.GetElement());
for (auto it = keys.begin(); it != keys.end(); it++) {
if (it->second == boolType) {
bool v1 = intent1.GetBoolParam(it->first, false);
bool v2 = intent2.GetBoolParam(it->first, false);
EXPECT_EQ(v1, v2);
EXPECT_EQ(v1, true);
} else if (it->second == boolArrayType) {
std::vector<bool> v1 = intent1.GetBoolArrayParam(it->first);
std::vector<bool> v2 = intent2.GetBoolArrayParam(it->first);
EXPECT_EQ(v1, v2);
} else if (it->second == byteType) {
byte v1 = intent1.GetByteParam(it->first, 'j');
byte v2 = intent2.GetByteParam(it->first, 'k');
EXPECT_EQ(v1, v2);
} else if (it->second == byteArrayType) {
std::vector<byte> v1 = intent1.GetByteArrayParam(it->first);
std::vector<byte> v2 = intent2.GetByteArrayParam(it->first);
EXPECT_EQ(v1, v2);
} else if (it->second == charType) {
zchar v1 = intent1.GetCharParam(it->first, 0x01AB);
zchar v2 = intent2.GetCharParam(it->first, 0x02CD);
EXPECT_EQ(v1, v2);
} else if (it->second == charArrayType) {
std::vector<zchar> v1 = intent1.GetCharArrayParam(it->first);
std::vector<zchar> v2 = intent2.GetCharArrayParam(it->first);
EXPECT_EQ(v1, v2);
} else if (it->second == shortType) {
short default1 = 123;
short default2 = 456;
short v1 = intent1.GetShortParam(it->first, default1);
short v2 = intent2.GetShortParam(it->first, default2);
EXPECT_EQ(v1, v2);
} else if (it->second == shortArrayType) {
std::vector<short> v1 = intent1.GetShortArrayParam(it->first);
std::vector<short> v2 = intent2.GetShortArrayParam(it->first);
EXPECT_EQ(v1, v2);
} else if (it->second == intType) {
int default1 = 1230000;
int default2 = 4560000;
int v1 = intent1.GetIntParam(it->first, default1);
int v2 = intent2.GetIntParam(it->first, default2);
EXPECT_EQ(v1, v2);
} else if (it->second == intArrayType) {
std::vector<int> v1 = intent1.GetIntArrayParam(it->first);
std::vector<int> v2 = intent2.GetIntArrayParam(it->first);
EXPECT_EQ(v1, v2);
} else if (it->second == longType) {
long default1 = 1e10;
long default2 = 2e10;
long v1 = intent1.GetLongParam(it->first, default1);
long v2 = intent2.GetLongParam(it->first, default2);
EXPECT_EQ(v1, v2);
} else if (it->second == longArrayType) {
std::vector<long> v1 = intent1.GetLongArrayParam(it->first);
std::vector<long> v2 = intent2.GetLongArrayParam(it->first);
EXPECT_EQ(v1, v2);
} else if (it->second == floatType) {
float default1 = 12.3;
float default2 = 45.6;
float v1 = intent1.GetFloatParam(it->first, default1);
float v2 = intent2.GetFloatParam(it->first, default2);
EXPECT_EQ(v1, v2);
} else if (it->second == floatArrayType) {
std::vector<float> v1 = intent1.GetFloatArrayParam(it->first);
std::vector<float> v2 = intent2.GetFloatArrayParam(it->first);
EXPECT_EQ(v1, v2);
} else if (it->second == doubleType) {
double default1 = 12.3;
double default2 = 45.6;
double v1 = intent1.GetDoubleParam(it->first, default1);
double v2 = intent2.GetDoubleParam(it->first, default2);
EXPECT_EQ(v1, v2);
} else if (it->second == doubleArrayType) {
std::vector<double> v1 = intent1.GetDoubleArrayParam(it->first);
std::vector<double> v2 = intent2.GetDoubleArrayParam(it->first);
EXPECT_EQ(v1, v2);
} else if (it->second == stringType) {
std::string v1 = intent1.GetStringParam(it->first);
std::string v2 = intent2.GetStringParam(it->first);
EXPECT_EQ(v1, v2);
} else if (it->second == stringArrayType) {
std::vector<std::string> v1 = intent1.GetStringArrayParam(it->first);
std::vector<std::string> v2 = intent2.GetStringArrayParam(it->first);
EXPECT_EQ(v1, v2);
}
}
return true;
}
void IntentParcelableTest::SendParcelTest(Intent &intent, std::map<std::string, std::string> &keys)
{
size_t pos1;
size_t pos2;
Parcel data;
bool result;
pos1 = data.GetWritePosition();
result = data.WriteParcelable(&intent);
pos2 = data.GetWritePosition();
EXPECT_EQ(result, true);
GTEST_LOG_(INFO) << "SendParcelTest: pos1: " << pos1 << ", pos2: " << pos2 << ", result: " << result;
Intent *intentNew = nullptr;
intentNew = data.ReadParcelable<Intent>();
EXPECT_NE(intentNew, nullptr);
if (intentNew != nullptr) {
result = CompareIntent(intent, *intentNew, keys);
EXPECT_EQ(result, true);
delete intentNew;
}
}
/*
* Feature: Intent
* Function: parcelable
* SubFunction: NA
* FunctionPoints: parcelable
* EnvConditions: NA
* CaseDescription: Verify parcelable
*/
HWTEST_F(IntentParcelableTest, AaFwk_Intent_Parcelable_001, TestSize.Level1)
{
std::map<std::string, std::string> keys;
Intent intent;
SendParcelTest(intent, keys);
}
void IntentParcelableTest::AddBoolParams(
Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned unsigned int flag)
{
std::string key;
std::string boolKey = "boolKey";
std::string boolArrayKey = "boolArrayKey";
for (int i = 0; i < loop; i++) {
if (flag & FLAG_TEST_SINGLE) {
// bool type value
bool boolValue = true;
key = boolKey + std::to_string(i);
keys[key] = boolType;
intent.SetBoolParam(key, boolValue);
}
if (flag & FLAG_TEST_ARRAY) {
// bool array type value
std::vector<bool> boolArrayValue = {true, false, true};
key = boolArrayKey + std::to_string(i);
keys[key] = boolArrayType;
intent.SetBoolArrayParam(key, boolArrayValue);
}
}
}
void IntentParcelableTest::AddByteParams(
Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned unsigned int flag)
{
std::string key;
std::string byteKey = "byteKey";
std::string byteArrayKey = "byteArrayKey";
for (int i = 0; i < loop; i++) {
if (flag & FLAG_TEST_SINGLE) {
// byte type value
byte byteValue = 'z';
key = byteKey + std::to_string(i);
keys[key] = byteType;
intent.SetByteParam(key, byteValue);
}
if (flag & FLAG_TEST_ARRAY) {
// byte array type value
std::vector<byte> byteArrayValue = {'?', 'a', '\\'};
key = byteArrayKey + std::to_string(i);
keys[key] = byteArrayType;
intent.SetByteArrayParam(key, byteArrayValue);
}
}
}
void IntentParcelableTest::AddCharParams(
Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag)
{
std::string key;
std::string charKey = "charKey";
std::string charArrayKey = "charArrayKey";
for (int i = 0; i < loop; i++) {
if (flag & FLAG_TEST_SINGLE) {
// char type value
zchar charValue = U'';
key = charKey + std::to_string(i);
keys[key] = charType;
intent.SetCharParam(key, charValue);
}
if (flag & FLAG_TEST_ARRAY) {
// char array type value
std::vector<zchar> charArrayValue = {U'', U'', U''};
key = charArrayKey + std::to_string(i);
keys[key] = charArrayType;
intent.SetCharArrayParam(key, charArrayValue);
}
}
}
void IntentParcelableTest::AddShortParams(
Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag)
{
std::string key;
std::string shortKey = "shortKey";
std::string shortArrayKey = "shortArrayKey";
for (int i = 0; i < loop; i++) {
if (flag & FLAG_TEST_SINGLE) {
// short type value
short shortValue = 1;
key = shortKey + std::to_string(i);
keys[key] = shortType;
intent.SetShortParam(key, shortValue);
}
if (flag & FLAG_TEST_ARRAY) {
// short array type value
std::vector<short> shortArrayValue = {-1, 0, 1};
key = shortArrayKey + std::to_string(i);
keys[key] = shortArrayType;
intent.SetShortArrayParam(key, shortArrayValue);
}
}
}
void IntentParcelableTest::AddIntParams(
Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag)
{
std::string key;
std::string intKey = "intKey";
std::string intArrayKey = "intArrayKey";
for (int i = 0; i < loop; i++) {
if (flag & FLAG_TEST_SINGLE) {
// int type value
int intValue = 10;
key = intKey + std::to_string(i);
keys[key] = intType;
intent.SetIntParam(key, intValue);
}
if (flag & FLAG_TEST_ARRAY) {
// int array type value
std::vector<int> intArrayValue = {-10, 0, 10};
key = intArrayKey + std::to_string(i);
keys[key] = intArrayType;
intent.SetIntArrayParam(key, intArrayValue);
}
}
}
void IntentParcelableTest::AddLongParams(
Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag)
{
std::string key;
std::string longKey = "longKey";
std::string longArrayKey = "longArrayKey";
for (int i = 0; i < loop; i++) {
if (flag & FLAG_TEST_SINGLE) {
// long type value
long longValue = 100;
key = longKey + std::to_string(i);
keys[key] = longType;
intent.SetLongParam(key, longValue);
}
if (flag & FLAG_TEST_ARRAY) {
// long array type value
std::vector<long> longArrayValue = {-100, 0, 100};
key = longArrayKey + std::to_string(i);
keys[key] = longArrayType;
intent.SetLongArrayParam(key, longArrayValue);
}
}
}
void IntentParcelableTest::AddFloatParams(
Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag)
{
std::string key;
std::string floatKey = "floatKey";
std::string floatArrayKey = "floatArrayKey";
for (int i = 0; i < loop; i++) {
if (flag & FLAG_TEST_SINGLE) {
// float type value
float floatValue = 100.1;
key = floatKey + std::to_string(i);
keys[key] = floatType;
intent.SetFloatParam(key, floatValue);
}
if (flag & FLAG_TEST_ARRAY) {
// float array type value
std::vector<float> floatArrayValue = {-100.1, 0.1, 100.1};
key = floatArrayKey + std::to_string(i);
keys[key] = floatArrayType;
intent.SetFloatArrayParam(key, floatArrayValue);
}
}
}
void IntentParcelableTest::AddDoubleParams(
Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag)
{
std::string key;
std::string doubleKey = "doubleKey";
std::string doubleArrayKey = "doubleArrayKey";
for (int i = 0; i < loop; i++) {
if (flag & FLAG_TEST_SINGLE) {
// double type value
double doubleValue = 1000.1;
key = doubleKey + std::to_string(i);
keys[key] = doubleType;
intent.SetDoubleParam(key, doubleValue);
}
if (flag & FLAG_TEST_ARRAY) {
// double array type value
std::vector<double> doubleArrayValue = {-1000.1, 0.1, 1000.1};
key = doubleArrayKey + std::to_string(i);
keys[key] = doubleArrayType;
intent.SetDoubleArrayParam(key, doubleArrayValue);
}
}
}
void IntentParcelableTest::AddStringParams(
Intent &intent, std::map<std::string, std::string> &keys, int loop, unsigned int flag)
{
std::string key;
std::string stringKey = "stringKey";
std::string stringArrayKey = "stringArrayKey";
for (int i = 0; i < loop; i++) {
if (flag & FLAG_TEST_SINGLE) {
// string type value
string stringValue = "zzzz";
key = stringKey + std::to_string(i);
keys[key] = stringType;
intent.SetStringParam(key, stringValue);
}
if (flag & FLAG_TEST_ARRAY) {
// string array type value
std::vector<std::string> stringArrayValue = {"??", "aa", "\\\\"};
key = stringArrayKey + std::to_string(i);
keys[key] = stringArrayType;
intent.SetStringArrayParam(key, stringArrayValue);
}
}
}
/*
* Feature: Intent
* Function: parcelable
* SubFunction: NA
* FunctionPoints: parcelable
* EnvConditions: NA
* CaseDescription: Verify parcelable
*/
HWTEST_F(IntentParcelableTest, AaFwk_Intent_Parcelable_002, TestSize.Level1)
{
std::string action = "intent.action.test";
unsigned int flag = 0x789;
std::string entity = "intent.entity.test";
ElementName element("bundlename", "appname", "abilityname");
Intent intent;
intent.SetAction(action).SetEntity(entity).SetFlag(flag).SetElement(element);
int loop = 1;
std::map<std::string, std::string> keys;
AddBoolParams(intent, keys, loop, FLAG_TEST_BOTH);
AddByteParams(intent, keys, loop, FLAG_TEST_BOTH);
AddCharParams(intent, keys, loop, FLAG_TEST_BOTH);
AddShortParams(intent, keys, loop, FLAG_TEST_BOTH);
AddIntParams(intent, keys, loop, FLAG_TEST_BOTH);
AddLongParams(intent, keys, loop, FLAG_TEST_BOTH);
AddFloatParams(intent, keys, loop, FLAG_TEST_BOTH);
AddDoubleParams(intent, keys, loop, FLAG_TEST_BOTH);
AddStringParams(intent, keys, loop, FLAG_TEST_BOTH);
SendParcelTest(intent, keys);
}
/*
* Feature: Intent
* Function: parcelable
* SubFunction: NA
* FunctionPoints: parcelable
* EnvConditions: NA
* CaseDescription: Verify parcelable
*/
HWTEST_F(IntentParcelableTest, AaFwk_Intent_Parcelable_003, TestSize.Level1)
{
std::string action = "intent.action.test";
unsigned int flag = 0x789;
std::string entity = "intent.entity.test";
ElementName element("bundlename", "appname", "abilityname");
Intent intent;
intent.SetAction(action).SetEntity(entity).SetFlag(flag).SetElement(element);
int loop = 1;
std::map<std::string, std::string> keys;
AddByteParams(intent, keys, loop, FLAG_TEST_BOTH);
AddCharParams(intent, keys, loop, FLAG_TEST_BOTH);
AddShortParams(intent, keys, loop, FLAG_TEST_BOTH);
AddIntParams(intent, keys, loop, FLAG_TEST_BOTH);
AddLongParams(intent, keys, loop, FLAG_TEST_BOTH);
AddFloatParams(intent, keys, loop, FLAG_TEST_BOTH);
AddDoubleParams(intent, keys, loop, FLAG_TEST_BOTH);
AddStringParams(intent, keys, loop, FLAG_TEST_BOTH);
SendParcelTest(intent, keys);
}
/*
* Feature: Intent
* Function: parcelable
* SubFunction: NA
* FunctionPoints: parcelable
* EnvConditions: NA
* CaseDescription: Verify parcelable
*/
HWTEST_F(IntentParcelableTest, AaFwk_Intent_Parcelable_004, TestSize.Level1)
{
std::string action = "intent.action.test";
unsigned int flag = 0x789;
std::string entity = "intent.entity.test";
ElementName element("bundlename", "appname", "abilityname");
Intent intent;
intent.SetAction(action).SetEntity(entity).SetFlag(flag).SetElement(element);
int loop = 1;
std::map<std::string, std::string> keys;
AddBoolParams(intent, keys, loop, FLAG_TEST_BOTH);
SendParcelTest(intent, keys);
}
@@ -1,846 +0,0 @@
/*
* 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 <cstring>
#include "ohos/aafwk/content/intent.h"
#include "ohos/aafwk/base/array_wrapper.h"
#include "ohos/aafwk/base/float_wrapper.h"
#include "ohos/aafwk/base/string_wrapper.h"
#include "refbase.h"
using namespace testing::ext;
using namespace OHOS::AAFwk;
using namespace OHOS;
using OHOS::AppExecFwk::ElementName;
class IntentParseToUriTest : public testing::Test {
public:
IntentParseToUriTest()
{}
~IntentParseToUriTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
static const std::string URI_STRING_HEAD;
static const std::string URI_STRING_END;
};
void IntentParseToUriTest::SetUpTestCase(void)
{}
void IntentParseToUriTest::TearDownTestCase(void)
{}
void IntentParseToUriTest::SetUp(void)
{}
void IntentParseToUriTest::TearDown(void)
{}
const std::string IntentParseToUriTest::URI_STRING_HEAD("#Intent;");
const std::string IntentParseToUriTest::URI_STRING_END(";end");
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when Intent is empty
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_001, TestSize.Level1)
{
std::size_t pos = 0;
std::size_t content = 0;
std::size_t head = 0;
Intent intentOrigin;
// ToUri
std::string uri = intentOrigin.ToUri();
// check head
head = uri.find(IntentParseToUriTest::URI_STRING_HEAD, pos);
EXPECT_EQ(head, pos);
if (head != std::string::npos) {
pos += head + IntentParseToUriTest::URI_STRING_HEAD.length() - 1;
}
// check end
content = uri.find(IntentParseToUriTest::URI_STRING_END, pos);
EXPECT_EQ(content, pos);
if (content != std::string::npos) {
pos += IntentParseToUriTest::URI_STRING_END.length();
}
// check uri length
EXPECT_EQ(uri.length(), pos);
// ParseUri
Intent *intentNew = Intent::ParseUri(uri);
EXPECT_NE(intentNew, nullptr);
if (intentNew != nullptr) {
// check new Intent
EXPECT_EQ(intentNew->GetAction(), std::string(""));
EXPECT_EQ(intentNew->GetEntity(), std::string(""));
ElementName element;
EXPECT_EQ(intentNew->GetElement(), element);
EXPECT_EQ(static_cast<int>(intentNew->GetFlags()), 0);
delete intentNew;
}
}
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when Intent only has action/entity/flag/element
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_002, TestSize.Level1)
{
std::string search;
std::size_t pos = 0;
std::size_t length = 0;
std::size_t result = 0;
std::size_t head = 0;
std::string action = Intent::ACTION_PLAY;
std::string entity = Intent::ENTITY_VIDEO;
unsigned int flag = 0x0f0f0f0f;
std::string flagStr = "0x0f0f0f0f";
std::string device = "device1";
std::string bundle = "bundle1";
std::string ability = "ability1";
ElementName element(device, bundle, ability);
Intent intentOrigin;
intentOrigin.SetAction(action);
intentOrigin.SetEntity(entity);
intentOrigin.SetFlag(flag);
intentOrigin.SetElement(element);
// ToUri
std::string uri = intentOrigin.ToUri();
// check head
search = IntentParseToUriTest::URI_STRING_HEAD;
result = uri.find(search, pos);
EXPECT_EQ(result, pos);
if (result != std::string::npos) {
head = result + search.length();
}
length += head;
// check action
search = std::string("action=") + action + std::string(";");
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
if (result != std::string::npos) {
length += search.length();
}
// check entity
search = std::string("entity=") + entity + std::string(";");
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
if (result != std::string::npos) {
length += search.length();
}
// check flag
search = std::string("flag=") + flagStr + std::string(";");
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
if (result != std::string::npos) {
length += search.length();
}
// check element device
search = std::string("device=") + device + std::string(";");
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
if (result != std::string::npos) {
length += search.length();
}
// check element bundle
search = std::string("bundle=") + bundle + std::string(";");
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
if (result != std::string::npos) {
length += search.length();
}
// check element ability
search = std::string("ability=") + ability + std::string(";");
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
if (result != std::string::npos) {
length += search.length();
}
// check end
search = IntentParseToUriTest::URI_STRING_END;
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
if (result != std::string::npos) {
length += search.length() - 1;
}
// check uri length
EXPECT_EQ(uri.length(), length);
// ParseUri
Intent *intentNew = Intent::ParseUri(uri);
EXPECT_NE(intentNew, nullptr);
if (intentNew != nullptr) {
// check new intent
EXPECT_EQ(intentNew->GetAction(), action);
EXPECT_EQ(intentNew->GetEntity(), entity);
EXPECT_EQ(intentNew->GetElement().GetDeviceID(), device);
EXPECT_EQ(intentNew->GetElement().GetBundleName(), bundle);
EXPECT_EQ(intentNew->GetElement().GetAbilityName(), ability);
EXPECT_EQ(intentNew->GetFlags(), flag);
delete intentNew;
}
}
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when Intent only has parameter and the parameter
* has only 1 float type element
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_003, TestSize.Level1)
{
std::string search;
std::size_t pos = 0;
std::size_t length = 0;
std::size_t result = 0;
std::size_t delims = 0;
std::size_t head = 0;
Intent intentOrigin;
std::string keyFloat = "keyFloat";
float valueFloatOrigin = 123.4;
intentOrigin.SetFloatParam(keyFloat, valueFloatOrigin);
// ToUri
std::string uri = intentOrigin.ToUri();
// check head
search = IntentParseToUriTest::URI_STRING_HEAD;
result = uri.find(search, pos);
EXPECT_EQ(result, pos);
if (result != std::string::npos) {
head = result + search.length();
}
length += head;
// check float parameter
search = Float::SIGNATURE + std::string(".") + keyFloat + std::string("=");
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
length += search.length();
if (result != std::string::npos) {
pos = result + search.length();
delims = uri.find(";", pos);
if (delims != std::string::npos) {
substring = uri.substr(pos, delims - pos);
float valueFloatNew = Float::Unbox(Float::Parse(substring));
EXPECT_EQ(valueFloatNew, valueFloatOrigin);
length += substring.length() + 1;
}
}
// check end
search = IntentParseToUriTest::URI_STRING_END;
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
if (result != std::string::npos) {
length += search.length() - 1;
}
// check uri length
EXPECT_EQ(uri.length(), length);
// ParseUri
Intent *intentNew = Intent::ParseUri(uri);
EXPECT_NE(intentNew, nullptr);
if (intentNew != nullptr) {
// check new intent
float floatNew = intentNew->GetFloatParam(keyFloat, 0.1);
float floatOld = intentOrigin.GetFloatParam(keyFloat, 1.1);
EXPECT_EQ(floatNew, floatOld);
delete intentNew;
}
}
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when Intent only has parameter and the parameter
* has only one float and one string type element
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_004, TestSize.Level1)
{
std::string search;
std::size_t pos = 0;
std::size_t length = 0;
std::size_t result = 0;
std::size_t delims = 0;
std::size_t head = 0;
Intent intentOrigin;
std::string keyFloat = "keyFloat";
std::string keyString = "keyString";
float valueFloatOrigin = 123.4;
std::string valueStringOrigin = "abcd";
intentOrigin.SetFloatParam(keyFloat, valueFloatOrigin);
intentOrigin.SetStringParam(keyString, valueStringOrigin);
// ToUri
std::string uri = intentOrigin.ToUri();
// check head
search = IntentParseToUriTest::URI_STRING_HEAD;
result = uri.find(search, pos);
EXPECT_NE(result, std::string::npos);
EXPECT_EQ(result, pos);
if (result != std::string::npos) {
head = result + search.length();
}
length += head;
// check float parameter
search = Float::SIGNATURE + std::string(".") + keyFloat + std::string("=");
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
length += search.length();
if (result != std::string::npos) {
pos = result + search.length();
delims = uri.find(";", pos);
if (delims != std::string::npos) {
substring = uri.substr(pos, delims - pos);
float valueFloatNew = Float::Unbox(Float::Parse(substring));
EXPECT_EQ(valueFloatNew, valueFloatOrigin);
length += substring.length() + 1;
}
}
// check string parameter
search = String::SIGNATURE + std::string(".") + keyString + std::string("=");
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
length += search.length();
if (result != std::string::npos) {
pos = result + search.length();
delims = uri.find(";", result);
if (delims != std::string::npos) {
std::string substring = uri.substr(pos, delims - pos);
std::string valueStringNew = String::Unbox(String::Parse(substring));
EXPECT_EQ(valueStringNew, valueStringOrigin);
length += substring.length() + 1;
}
}
// check end
search = IntentParseToUriTest::URI_STRING_END;
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
if (result != std::string::npos) {
length += search.length() - 1;
}
// check uri length
EXPECT_EQ(uri.length(), length);
// ParseUri
Intent *intentNew = Intent::ParseUri(uri);
EXPECT_NE(intentNew, nullptr);
if (intentNew != nullptr) {
// check new intent
float floatNew = intentNew->GetFloatParam(keyFloat, 0);
float floatOld = intentOrigin.GetFloatParam(keyFloat, 1);
EXPECT_EQ(floatNew, floatOld);
std::string stringNew = intentNew->GetStringParam(keyString);
std::string stringOld = intentOrigin.GetStringParam(keyString);
EXPECT_EQ(stringNew, stringOld);
delete intentNew;
}
}
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when Intent only has parameter and the parameter
* has only one float array type element
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_005, TestSize.Level1)
{
std::string search;
std::size_t pos = 0;
std::size_t length = 0;
std::size_t result = 0;
std::size_t delims = 0;
std::size_t head = 0;
Intent intentOrigin;
std::string keyFloatArray = "keyFloatArray";
std::vector<float> valueFloatArrayOrigin = {1.1, 2.1, 3.1};
intentOrigin.SetFloatArrayParam(keyFloatArray, valueFloatArrayOrigin);
// ToUri
std::string uri = intentOrigin.ToUri();
// check head
search = IntentParseToUriTest::URI_STRING_HEAD;
result = uri.find(search, pos);
EXPECT_NE(result, std::string::npos);
EXPECT_EQ(result, pos);
if (result != std::string::npos) {
head = result + search.length();
}
length += head;
// check float array parameter
search = Array::SIGNATURE + std::string(".") + keyFloatArray + std::string("=");
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
length += search.length();
if (result != std::string::npos) {
pos = result + search.length();
delims = uri.find(";", result);
if (delims != std::string::npos) {
std::string substring = uri.substr(pos, delims - pos);
sptr<IArray> array = Array::Parse(substring);
std::vector<float> valueFloatArrayNew;
auto func = [&](IInterface *object) { valueFloatArrayNew.push_back(Float::Unbox(IFloat::Query(object))); };
Array::ForEach(array, func);
EXPECT_EQ(valueFloatArrayNew, valueFloatArrayOrigin);
length += substring.length() + 1;
}
}
// check end
search = IntentParseToUriTest::URI_STRING_END;
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
if (result != std::string::npos) {
length += search.length() - 1;
}
// check uri length
EXPECT_EQ(uri.length(), length);
// ParseUri
Intent *intentNew = Intent::ParseUri(uri);
EXPECT_NE(intentNew, nullptr);
if (intentNew != nullptr) {
// check new intent
std::vector<float> arrayNew = intentNew->GetFloatArrayParam(keyFloatArray);
std::vector<float> arrayOld = intentOrigin.GetFloatArrayParam(keyFloatArray);
EXPECT_EQ(arrayNew, arrayOld);
delete intentNew;
}
}
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when Intent only has parameter and the parameter
* has only one int array and one string array type element
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_006, TestSize.Level1)
{
std::string search;
std::size_t pos = 0;
std::size_t length = 0;
std::size_t result = 0;
std::size_t delims = 0;
std::size_t head = 0;
Intent intentOrigin;
std::string keyFloatArray = "keyFloatArray";
std::string keyStringArray = "keyStringArray";
std::vector<float> valueFloatArrayOrigin = {1.1, 2.1, 3.1};
std::vector<std::string> valueStringArrayOrigin = {"aa", "bb", "cc"};
intentOrigin.SetFloatArrayParam(keyFloatArray, valueFloatArrayOrigin);
intentOrigin.SetStringArrayParam(keyStringArray, valueStringArrayOrigin);
// ToUri
std::string uri = intentOrigin.ToUri();
// check head
search = IntentParseToUriTest::URI_STRING_HEAD;
result = uri.find(search, pos);
EXPECT_NE(result, std::string::npos);
EXPECT_EQ(result, pos);
if (result != std::string::npos) {
head = result + search.length();
}
length += head;
// check int array parameter
search = Array::SIGNATURE + std::string(".") + keyFloatArray + std::string("=");
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
length += search.length();
if (result != std::string::npos) {
pos = result + search.length();
delims = uri.find(";", result);
if (delims != std::string::npos) {
std::string substring = uri.substr(pos, delims - pos);
sptr<IArray> array = Array::Parse(substring);
std::vector<float> valueFloatArrayNew;
auto func = [&](IInterface *object) { valueFloatArrayNew.push_back(Float::Unbox(IFloat::Query(object))); };
Array::ForEach(array, func);
EXPECT_EQ(valueFloatArrayNew, valueFloatArrayOrigin);
length += substring.length() + 1;
}
}
// check string array parameter
search = Array::SIGNATURE + std::string(".") + keyStringArray + std::string("=");
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
length += search.length();
if (result != std::string::npos) {
pos = result + search.length();
delims = uri.find(";", result);
if (delims != std::string::npos) {
std::string substring = uri.substr(pos, delims - pos);
sptr<IArray> array = Array::Parse(substring);
std::vector<std::string> valueStringArrayNew;
auto func = [&](IInterface *object) {
valueStringArrayNew.push_back(String::Unbox(IString::Query(object)));
};
Array::ForEach(array, func);
EXPECT_EQ(valueStringArrayNew, valueStringArrayOrigin);
length += substring.length() + 1;
}
}
// check end
search = IntentParseToUriTest::URI_STRING_END;
result = uri.find(search);
EXPECT_NE(result, std::string::npos);
EXPECT_GE(result, head);
if (result != std::string::npos) {
length += search.length() - 1;
}
// check uri length
EXPECT_EQ(uri.length(), length);
// ParseUri
Intent *intentNew = Intent::ParseUri(uri);
EXPECT_NE(intentNew, nullptr);
if (intentNew != nullptr) {
// check new intent
std::vector<float> arrayFloatNew = intentNew->GetFloatArrayParam(keyFloatArray);
std::vector<float> arrayFloatOld = intentOrigin.GetFloatArrayParam(keyFloatArray);
EXPECT_EQ(arrayFloatNew, arrayFloatOld);
std::vector<std::string> arrayStringNew = intentNew->GetStringArrayParam(keyStringArray);
std::vector<std::string> arrayStringOld = intentOrigin.GetStringArrayParam(keyStringArray);
EXPECT_EQ(arrayStringNew, arrayStringOld);
delete intentNew;
}
}
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when the length of input string is 0
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_008, TestSize.Level1)
{
std::string uri;
EXPECT_EQ(static_cast<int>(uri.length()), 0);
Intent *intent = Intent::ParseUri(uri);
EXPECT_EQ(intent, nullptr);
if (intent != nullptr) {
delete intent;
}
}
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when the action etc. are empty
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_009, TestSize.Level1)
{
std::string empty;
std::string uri = "#Intent;action=;entity=;device=;bundle=;ability=;flag=;end";
EXPECT_NE(static_cast<int>(uri.length()), 0);
Intent *intent = Intent::ParseUri(uri);
EXPECT_NE(intent, nullptr);
if (intent != nullptr) {
EXPECT_EQ(intent->GetAction(), empty);
EXPECT_EQ(intent->GetEntity(), empty);
EXPECT_EQ(intent->GetFlags(), (unsigned int)0);
ElementName element;
EXPECT_EQ(intent->GetElement(), element);
EXPECT_EQ(intent->HasParameter(empty), false);
delete intent;
}
}
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when flag is not number
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_010, TestSize.Level1)
{
std::string uri = "#Intent;action=intent.action.VIEW;flag=\"123\";end";
EXPECT_NE(static_cast<int>(uri.length()), 0);
Intent *intent = Intent::ParseUri(uri);
EXPECT_EQ(intent, nullptr);
}
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when head is not "#Intent"
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_011, TestSize.Level1)
{
std::string uri = "action=intent.action.VIEW;end";
EXPECT_NE(static_cast<int>(uri.length()), 0);
Intent *intent = Intent::ParseUri(uri);
EXPECT_EQ(intent, nullptr);
}
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when flag is empty
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_012, TestSize.Level1)
{
std::string uri = "#Intent;flag=;end";
EXPECT_NE(static_cast<int>(uri.length()), 0);
Intent *intent = Intent::ParseUri(uri);
EXPECT_NE(intent, nullptr);
if (intent != nullptr) {
EXPECT_EQ(intent->GetFlags(), static_cast<unsigned int>(0));
delete intent;
}
}
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when x is capital
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_013, TestSize.Level1)
{
unsigned int flag = 0X12345678;
std::string uri = "#Intent;flag=0X12345678;end";
EXPECT_NE(static_cast<int>(uri.length()), 0);
Intent *intent = Intent::ParseUri(uri);
EXPECT_NE(intent, nullptr);
if (intent != nullptr) {
EXPECT_EQ(intent->GetFlags(), flag);
delete intent;
}
}
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when special character
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_014, TestSize.Level1)
{
std::string action = "\\";
std::string entity = "../../../jj/j=075/./.;;/07507399/\\\\;;--==.com.\a\b\tfoobar.vide\073\\075";
unsigned int flag = 0x0f0f0f0f;
std::string flagStr = "0x0f0f0f0f";
std::string key = "\\kkk=.=;";
std::string value = "==\\\\\\.;\\;\\;\\=\\\073075\\\\075073";
Intent intentOrigin;
intentOrigin.SetAction(action);
intentOrigin.SetEntity(entity);
intentOrigin.SetFlag(flag);
intentOrigin.SetStringParam(key, value);
// ToUri
std::string uri = intentOrigin.ToUri();
// ParseUri
Intent *intentNew = Intent::ParseUri(uri);
EXPECT_NE(intentNew, nullptr);
if (intentNew != nullptr) {
// check new intent
EXPECT_EQ(intentNew->GetAction(), action);
EXPECT_EQ(intentNew->GetEntity(), entity);
EXPECT_EQ(intentNew->GetFlags(), flag);
EXPECT_EQ(intentNew->GetStringParam(key), value);
delete intentNew;
}
}
/*
* Feature: Intent
* Function: ParseUri and ToUri
* SubFunction: NA
* FunctionPoints: ParseUri and ToUri
* EnvConditions: NA
* CaseDescription: Verify the function when no '=' or only has a '='
*/
HWTEST_F(IntentParseToUriTest, AaFwk_Intent_ParseUri_ToUri_015, TestSize.Level1)
{
std::string uri = "#Intent;action;end";
Intent *intent = Intent::ParseUri(uri);
EXPECT_EQ(intent, nullptr);
uri = "#Intent;entity;end";
intent = Intent::ParseUri(uri);
EXPECT_EQ(intent, nullptr);
uri = "#Intent;device;end";
intent = Intent::ParseUri(uri);
EXPECT_EQ(intent, nullptr);
uri = "#Intent;bundle;end";
intent = Intent::ParseUri(uri);
EXPECT_EQ(intent, nullptr);
uri = "#Intent;ability;end";
intent = Intent::ParseUri(uri);
EXPECT_EQ(intent, nullptr);
uri = "#Intent;flag;end";
intent = Intent::ParseUri(uri);
EXPECT_EQ(intent, nullptr);
uri = "#Intent;param;end";
intent = Intent::ParseUri(uri);
EXPECT_EQ(intent, nullptr);
uri = "#Intent;=;end";
intent = Intent::ParseUri(uri);
EXPECT_NE(intent, nullptr);
if (intent != nullptr) {
delete intent;
}
uri = "#Intent;abc=;end";
intent = Intent::ParseUri(uri);
EXPECT_NE(intent, nullptr);
if (intent != nullptr) {
delete intent;
}
uri = "#Intent;=abc;end";
intent = Intent::ParseUri(uri);
EXPECT_NE(intent, nullptr);
if (intent != nullptr) {
delete intent;
}
uri = "#Intent;xxxx=yyy;end";
intent = Intent::ParseUri(uri);
EXPECT_NE(intent, nullptr);
if (intent != nullptr) {
delete intent;
}
uri = "#Intent;;;;;;end";
intent = Intent::ParseUri(uri);
EXPECT_NE(intent, nullptr);
if (intent != nullptr) {
delete intent;
}
}
+12 -14
View File
@@ -25,11 +25,10 @@ namespace OHOS {
namespace AAFwk {
class PatternsMatcherBaseTest : public testing::Test {
public:
PatternsMatcherBaseTest()
PatternsMatcherBaseTest()
{}
~PatternsMatcherBaseTest()
{
}
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
@@ -51,8 +50,7 @@ void PatternsMatcherBaseTest::SetUp(void)
}
void PatternsMatcherBaseTest::TearDown(void)
{
}
{}
/**
* @tc.number: AaFwk_PatternsMatcher_Parcelable_0100
@@ -61,7 +59,7 @@ void PatternsMatcherBaseTest::TearDown(void)
*/
HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Parcelable_0100, Function | MediumTest | Level1)
{
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("1234", MatchType::PATTERN_LITERAL);
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("1234", MatchType::DEFAULT);
if (PatternsMatcherIn_ != nullptr) {
Parcel in;
PatternsMatcherIn_->Marshalling(in);
@@ -80,7 +78,7 @@ HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Parcelable_0100, Functio
*/
HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Parcelable_0200, Function | MediumTest | Level1)
{
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("@#¥#3243adsafdf_中文", MatchType::PATTERN_PREFIX);
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("@#¥#3243adsafdf_中文", MatchType::PREFIX);
if (PatternsMatcherIn_ != nullptr) {
Parcel in;
PatternsMatcherIn_->Marshalling(in);
@@ -99,7 +97,7 @@ HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Parcelable_0200, Functio
*/
HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Parcelable_0300, Function | MediumTest | Level1)
{
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("", MatchType::PATTERN_SIMPLE_GLOB);
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("", MatchType::GLOBAL);
if (PatternsMatcherIn_ != nullptr) {
Parcel in;
PatternsMatcherIn_->Marshalling(in);
@@ -118,7 +116,7 @@ HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Parcelable_0300, Functio
*/
HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Match_0100, Function | MediumTest | Level1)
{
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("abcdefg", MatchType::PATTERN_LITERAL);
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("abcdefg", MatchType::DEFAULT);
if (PatternsMatcherIn_ != nullptr) {
EXPECT_EQ(PatternsMatcherIn_->match("abcdefg"), true);
EXPECT_EQ(PatternsMatcherIn_->match("Abcdefg"), false);
@@ -132,7 +130,7 @@ HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Match_0100, Function | M
*/
HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Match_0200, Function | MediumTest | Level1)
{
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("abcdefg", MatchType::PATTERN_PREFIX);
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("abcdefg", MatchType::PREFIX);
if (PatternsMatcherIn_ != nullptr) {
EXPECT_EQ(PatternsMatcherIn_->match("abcdefgABCDEFG"), true);
EXPECT_EQ(PatternsMatcherIn_->match("AbcdefgABCDEFG"), false);
@@ -146,7 +144,7 @@ HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Match_0200, Function | M
*/
HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Match_0300, Function | MediumTest | Level1)
{
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("abc*defg.", MatchType::PATTERN_REGEX);
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("abc*defg.", MatchType::PATTERN);
if (PatternsMatcherIn_ != nullptr) {
EXPECT_EQ(PatternsMatcherIn_->match("abcdefgG"), true);
EXPECT_EQ(PatternsMatcherIn_->match("abcccccdefgG"), true);
@@ -162,7 +160,7 @@ HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Match_0300, Function | M
*/
HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Match_0400, Function | MediumTest | Level1)
{
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("abc*ABC*123", MatchType::PATTERN_SIMPLE_GLOB);
PatternsMatcherIn_ = std::make_shared<PatternsMatcher>("abc*ABC*123", MatchType::GLOBAL);
if (PatternsMatcherIn_ != nullptr) {
EXPECT_EQ(PatternsMatcherIn_->match("abcABC123"), true);
EXPECT_EQ(PatternsMatcherIn_->match("abcdefgABCDEFG123"), true);
@@ -172,5 +170,5 @@ HWTEST_F(PatternsMatcherBaseTest, AaFwk_PatternsMatcher_Match_0400, Function | M
EXPECT_EQ(PatternsMatcherIn_->match("abcABC12345"), false);
}
}
}
}
} // namespace AAFwk
} // namespace OHOS
+23 -29
View File
@@ -26,7 +26,6 @@ using namespace testing::ext;
using namespace OHOS::AAFwk;
using OHOS::Parcel;
namespace OHOS {
namespace AAFwk {
static const int LARGE_STR_LEN = 65534;
@@ -36,8 +35,7 @@ public:
SkillsBaseTest()
{}
~SkillsBaseTest()
{
}
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
@@ -59,8 +57,7 @@ void SkillsBaseTest::SetUp(void)
}
void SkillsBaseTest::TearDown(void)
{
}
{}
/**
* @tc.number: AaFwk_Skills_Parcelable_0100
@@ -89,7 +86,7 @@ HWTEST_F(SkillsBaseTest, AaFwk_Skills_Parcelable_0100, Function | MediumTest | L
Parcel in;
std::shared_ptr<Skills> SkillsOut_(Skills::Unmarshalling(in));
SkillsIn_->Marshalling(in);
if(SkillsOut_ != nullptr){
if (SkillsOut_ != nullptr) {
CompareSkills(SkillsIn_, SkillsOut_);
EXPECT_EQ(valueBool, Boolean::Unbox(IBoolean::Query(SkillsOut_->GetWantParams().GetParam(keyStr))));
}
@@ -118,17 +115,17 @@ HWTEST_F(SkillsBaseTest, AaFwk_Skills_Parcelable_0200, Function | MediumTest | L
std::string keyStr = "@#¥#3243adsafdf_中文";
long valueLong = 12345L;
wantParams.SetParam(keyStr, Long::Box(valueLong));
EXPECT_EQ(valueLong, Long::Unbox(ILong::Query(wantParams.GetParam(keyStr))));
EXPECT_EQ(valueLong, Long::Unbox(ILong::Query(wantParams.GetParam(keyStr))));
SkillsIn_->SetWantParams(wantParams);
Parcel in;
SkillsIn_->Marshalling(in);
std::shared_ptr<Skills> SkillsOut_(Skills::Unmarshalling(in));
if(SkillsOut_ != nullptr){
if (SkillsOut_ != nullptr) {
CompareSkills(SkillsIn_, SkillsOut_);
EXPECT_EQ(valueLong, Long::Unbox(ILong::Query(SkillsOut_->GetWantParams().GetParam(keyStr))));
EXPECT_EQ(valueLong, Long::Unbox(ILong::Query(SkillsOut_->GetWantParams().GetParam(keyStr))));
}
}
@@ -156,15 +153,14 @@ HWTEST_F(SkillsBaseTest, AaFwk_Skills_Parcelable_0300, Function | MediumTest | L
int valueInt = 123;
wantParams.SetParam(keyStr, Integer::Box(valueInt));
SkillsIn_->SetWantParams(wantParams);
EXPECT_EQ(valueInt, Integer::Unbox(IInteger::Query(wantParams.GetParam(keyStr))));
EXPECT_EQ(valueInt, Integer::Unbox(IInteger::Query(wantParams.GetParam(keyStr))));
Parcel in;
SkillsIn_->Marshalling(in);
std::shared_ptr<Skills> SkillsOut_(Skills::Unmarshalling(in));
if(SkillsOut_ != nullptr){
if (SkillsOut_ != nullptr) {
CompareSkills(SkillsIn_, SkillsOut_);
EXPECT_EQ(valueInt, Integer::Unbox(IInteger::Query(SkillsOut_->GetWantParams().GetParam(keyStr))));
}
@@ -212,7 +208,7 @@ HWTEST_F(SkillsBaseTest, AaFwk_Skills_Parcelable_0400, Function | MediumTest | L
SkillsIn_->Marshalling(in);
std::shared_ptr<Skills> SkillsOut_(Skills::Unmarshalling(in));
if(SkillsOut_ != nullptr){
if (SkillsOut_ != nullptr) {
CompareSkills(SkillsIn_, SkillsOut_);
EXPECT_EQ(valueString, String::Unbox(IString::Query(SkillsOut_->GetWantParams().GetParam(keyStr))));
}
@@ -333,7 +329,7 @@ HWTEST_F(SkillsBaseTest, AaFwk_Skills_Path_0300, Function | MediumTest | Level1)
{
std::string empty;
std::string path = "paths.system.test";
PatternsMatcher pm(path, MatchType::PATTERN_LITERAL);
PatternsMatcher pm(path, MatchType::DEFAULT);
base_->AddPath(pm);
EXPECT_EQ(1, base_->CountPaths());
@@ -583,7 +579,7 @@ HWTEST_F(SkillsBaseTest, AaFwk_Skills_Types_0100, Function | MediumTest | Level1
GTEST_LOG_(INFO) << "---------------1 ";
EXPECT_EQ(empty, base_->GetAuthority(0));
GTEST_LOG_(INFO) << "---------------2 ";
base_->RemoveAuthority(types);
EXPECT_EQ(0, base_->CountTypes());
EXPECT_EQ(false, base_->HasAuthority(types));
@@ -634,13 +630,13 @@ HWTEST_F(SkillsBaseTest, AaFwk_Skills_Path_0200, Function | MediumTest | Level1)
{
std::string empty;
std::string path = "path.system.test";
base_->AddPath(path, MatchType::PATTERN_LITERAL);
base_->AddPath(path, MatchType::DEFAULT);
EXPECT_EQ(1, base_->CountPaths());
EXPECT_EQ(true, base_->HasPath(path));
EXPECT_EQ(path, base_->GetPath(0));
base_->RemovePath(path, MatchType::PATTERN_LITERAL);
base_->RemovePath(path, MatchType::DEFAULT);
EXPECT_EQ(0, base_->CountPaths());
EXPECT_EQ(false, base_->HasPath(path));
}
@@ -827,7 +823,7 @@ HWTEST_F(SkillsBaseTest, AaFwk_Skills_addremoveType_0100, Function | MediumTest
{
std::string patternStr = std::string("systems/*t");
PatternsMatcher pattern(patternStr, MatchType::PATTERN_LITERAL);
PatternsMatcher pattern(patternStr, MatchType::DEFAULT);
base_->AddType(pattern);
std::string type1 = base_->GetType(0);
@@ -840,7 +836,7 @@ HWTEST_F(SkillsBaseTest, AaFwk_Skills_addremoveType_0100, Function | MediumTest
base_->AddType(pattern);
std::string patternStr2 = std::string("systems/*test");
PatternsMatcher pattern2(patternStr2, MatchType::PATTERN_PREFIX);
PatternsMatcher pattern2(patternStr2, MatchType::PREFIX);
base_->AddType(pattern2);
std::string type2 = base_->GetType(1);
EXPECT_EQ(patternStr2, type2);
@@ -849,12 +845,12 @@ HWTEST_F(SkillsBaseTest, AaFwk_Skills_addremoveType_0100, Function | MediumTest
EXPECT_EQ(0, base_->CountEntities());
std::string patternStr3 = std::string("systems/*test3");
base_->AddType(patternStr3, MatchType::PATTERN_SIMPLE_GLOB);
base_->AddType(patternStr3, MatchType::GLOBAL);
std::string type3 = base_->GetType(1);
EXPECT_EQ(patternStr3, type3);
base_->RemoveType(patternStr3, MatchType::PATTERN_SIMPLE_GLOB);
base_->RemoveType(patternStr3, MatchType::GLOBAL);
EXPECT_EQ(0, base_->CountEntities());
}
@@ -862,11 +858,10 @@ HWTEST_F(SkillsBaseTest, AaFwk_Skills_addremoveType_0100, Function | MediumTest
using testParamsType = std::tuple<std::string, std::string>;
class SkillsParamsTest : public testing::TestWithParam<testParamsType> {
public:
SkillsParamsTest()
SkillsParamsTest()
{}
~SkillsParamsTest()
{
}
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
@@ -886,8 +881,7 @@ void SkillsParamsTest::SetUp(void)
}
void SkillsParamsTest::TearDown(void)
{
}
{}
/**
* @tc.number: AaFwk_Skills_Params_0100
@@ -913,5 +907,5 @@ INSTANTIATE_TEST_CASE_P(SkillsParamsTestCaseP, SkillsParamsTest,
testParamsType(std::string(LARGE_STR_LEN + 1, 'k'), std::string(LARGE_STR_LEN + 1, 'k')),
testParamsType("#$%^&*(!@\":<>{},/", "#$%^&*(!@\":<>{},/")));
}
}
} // namespace AAFwk
} // namespace OHOS
@@ -0,0 +1,339 @@
/*
* 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>
#define private public
#include "ohos/aafwk/content/want_params_wrapper.h"
#undef protected
#include "ohos/aafwk/base/string_wrapper.h"
using namespace testing::ext;
using namespace OHOS;
using namespace AAFwk;
namespace {
const std::string STRING_WANT_PARAMS_KEY_01 = "key01";
const std::string STRING_WANT_PARAMS_VALUE_01 = "value01";
const std::string STRING_WANT_PARAMS_STRING_01 = "{\"key01\":{\"9\":\"value01\"}}";
const std::string STRING_WANT_PARAMS_KEY_02 = "key02";
const std::string STRING_WANT_PARAMS_VALUE_02 = "value02";
const std::string STRING_WANT_PARAMS_STRING_0201 =
"{\"key01\":{\"21\":{\"key02\":{\"9\":\"value02\"}}},\"key02\":{\"9\":\"value02\"}}";
} // namespace
class WantParamWrapperBaseTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp() override;
void TearDown() override;
WantParams wantParams_;
std::shared_ptr<WantParamWrapper> wantParamWrapperPtr_;
};
void WantParamWrapperBaseTest::SetUpTestCase()
{}
void WantParamWrapperBaseTest::TearDownTestCase(void)
{}
void WantParamWrapperBaseTest::SetUp(void)
{
wantParams_ = {};
wantParams_.SetParam(STRING_WANT_PARAMS_KEY_01, String::Box(STRING_WANT_PARAMS_VALUE_01));
wantParamWrapperPtr_ = std::make_shared<WantParamWrapper>(wantParams_);
}
void WantParamWrapperBaseTest::TearDown(void)
{}
/**
* @tc.number: Want_Param_Wrapper_0100
* @tc.name: GetValue
* @tc.desc: Verify the "GetValue" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_0100, Function | MediumTest | Level1)
{
WantParams wantParams;
ErrCode result = wantParamWrapperPtr_->GetValue(wantParams);
EXPECT_EQ(result, ERR_OK);
EXPECT_EQ(wantParams_ == wantParams, true);
}
/**
* @tc.number: Want_Param_Wrapper_0200
* @tc.name: GetValue
* @tc.desc: Verify the "GetValue" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_0200, Function | MediumTest | Level1)
{
WantParams wantParams;
ErrCode result = wantParamWrapperPtr_->GetValue(wantParams);
EXPECT_EQ(result, ERR_OK);
// make another empty WantParams
WantParams wantParamsEmpty = {};
EXPECT_EQ(wantParams_ == wantParamsEmpty, false);
}
/**
* @tc.number: Want_Param_Wrapper_0300
* @tc.name: Equals
* @tc.desc: Verify the "Equals" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_0300, Function | MediumTest | Level1)
{
WantParams wantParams;
wantParams.SetParam(STRING_WANT_PARAMS_KEY_01, String::Box(STRING_WANT_PARAMS_VALUE_01));
WantParamWrapper wantParamWrapper(wantParams);
bool result = wantParamWrapperPtr_->Equals(wantParamWrapper);
EXPECT_EQ(result, true);
}
/**
* @tc.number: Want_Param_Wrapper_0400
* @tc.name: Equals
* @tc.desc: Verify the "Equals" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_0400, Function | MediumTest | Level1)
{
WantParams wantParams;
WantParamWrapper wantParamWrapper(wantParams);
bool result = wantParamWrapperPtr_->Equals(wantParamWrapper);
EXPECT_EQ(result, false);
}
/**
* @tc.number: Want_Param_Wrapper_0500
* @tc.name: Box
* @tc.desc: Verify the "Box" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_0500, Function | MediumTest | Level1)
{
auto wantParamsPtr = WantParamWrapper::Box(wantParams_);
WantParams wantParams;
ErrCode result = wantParamsPtr->GetValue(wantParams);
EXPECT_EQ(result, ERR_OK);
EXPECT_EQ(wantParams_ == wantParams, true);
}
/**
* @tc.number: Want_Param_Wrapper_0600
* @tc.name: Box
* @tc.desc: Verify the "Box" function with am empty object.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_0600, Function | MediumTest | Level1)
{
auto wantParamsPtr = WantParamWrapper::Box({});
ASSERT_NE(wantParamsPtr, nullptr);
WantParams wantParams;
ErrCode result = wantParamsPtr->GetValue(wantParams);
EXPECT_EQ(result, ERR_OK);
// make another empty WantParams
WantParams wantParamsEmpty = {};
EXPECT_EQ(wantParams == wantParamsEmpty, true);
}
/**
* @tc.number: Want_Param_Wrapper_0700
* @tc.name: Unbox
* @tc.desc: Verify the "Unbox" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_0700, Function | MediumTest | Level1)
{
auto wantParamsPtr = WantParamWrapper::Box(wantParams_);
auto wantParams = WantParamWrapper::Unbox(wantParamsPtr);
EXPECT_EQ(wantParams_ == wantParams, true);
}
/**
* @tc.number: Want_Param_Wrapper_0800
* @tc.name: Unbox
* @tc.desc: Verify the "Unbox" function with a nullptr
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_0800, Function | MediumTest | Level1)
{
auto wantParams = WantParamWrapper::Unbox(nullptr);
// make another empty WantParams
WantParams wantParamsEmpty = {};
EXPECT_EQ(wantParams == wantParamsEmpty, true);
}
/**
* @tc.number: Want_Param_Wrapper_0900
* @tc.name: ValidateStr
* @tc.desc: Verify the "ValidateStr" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_0900, Function | MediumTest | Level1)
{
bool result = WantParamWrapper::ValidateStr("{");
EXPECT_EQ(result, false);
}
/**
* @tc.number: Want_Param_Wrapper_1000
* @tc.name: ValidateStr
* @tc.desc: Verify the "ValidateStr" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_1000, Function | MediumTest | Level1)
{
bool result = WantParamWrapper::ValidateStr("}");
EXPECT_EQ(result, false);
}
/**
* @tc.number: Want_Param_Wrapper_1100
* @tc.name: ValidateStr
* @tc.desc: Verify the "ValidateStr" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_1100, Function | MediumTest | Level1)
{
bool result = WantParamWrapper::ValidateStr("}{");
EXPECT_EQ(result, false);
}
/**
* @tc.number: Want_Param_Wrapper_1200
* @tc.name: ValidateStr
* @tc.desc: Verify the "ValidateStr" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_1200, Function | MediumTest | Level1)
{
bool result = WantParamWrapper::ValidateStr("{\"\"}");
EXPECT_EQ(result, false);
}
/**
* @tc.number: Want_Param_Wrapper_1300
* @tc.name: Parse
* @tc.desc: Verify the "Parse" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_1300, Function | MediumTest | Level1)
{
auto wantParamsPtr = WantParamWrapper::Parse("");
auto wantParams = WantParamWrapper::Unbox(wantParamsPtr);
// make another empty WantParams
WantParams wantParamsEmpty = {};
EXPECT_EQ(wantParams == wantParamsEmpty, true);
}
/**
* @tc.number: Want_Param_Wrapper_1400
* @tc.name: Parse
* @tc.desc: Verify the "Parse" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_1400, Function | MediumTest | Level1)
{
auto wantParamsPtr = WantParamWrapper::Parse("{}");
auto wantParams = WantParamWrapper::Unbox(wantParamsPtr);
// make another empty WantParams
WantParams wantParamsEmpty = {};
EXPECT_EQ(wantParams == wantParamsEmpty, true);
}
/**
* @tc.number: Want_Param_Wrapper_1500
* @tc.name: ToString
* @tc.desc: Verify the "ToString" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_1500, Function | MediumTest | Level1)
{
auto wantParamsString = wantParamWrapperPtr_->ToString();
EXPECT_EQ(wantParamsString, STRING_WANT_PARAMS_STRING_01);
}
/**
* @tc.number: Want_Param_Wrapper_1600
* @tc.name: ToString
* @tc.desc: Verify the "ToString" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_1600, Function | MediumTest | Level1)
{
WantParams wantParams = {};
WantParamWrapper wantParamWrapper(wantParams);
auto wantParamsString = wantParamWrapper.ToString();
EXPECT_EQ(wantParamsString, "{}");
}
/**
* @tc.number: Want_Param_Wrapper_1700
* @tc.name: ToString
* @tc.desc: Verify the "ToString" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_1700, Function | MediumTest | Level1)
{
WantParams wantParams = {};
wantParams.SetParam(STRING_WANT_PARAMS_KEY_02, String::Box(STRING_WANT_PARAMS_VALUE_02));
wantParams.SetParam(STRING_WANT_PARAMS_KEY_01, WantParamWrapper::Box(wantParams));
WantParamWrapper wantParamWrapper(wantParams);
auto wantParamsString = wantParamWrapper.ToString();
EXPECT_EQ(wantParamsString, STRING_WANT_PARAMS_STRING_0201);
}
/**
* @tc.number: Want_Param_Wrapper_1800
* @tc.name: from ToString to Parse
* @tc.desc: Verify the "from ToString to Parse" function.
*/
HWTEST_F(WantParamWrapperBaseTest, Want_Param_Wrapper_1800, Function | MediumTest | Level1)
{
auto wantParamsString = wantParamWrapperPtr_->ToString();
EXPECT_EQ(wantParamsString, STRING_WANT_PARAMS_STRING_01);
auto wantParamsPtr = WantParamWrapper::Parse(wantParamsString);
auto wantParams = WantParamWrapper::Unbox(wantParamsPtr);
EXPECT_EQ(wantParams_ == wantParams, true);
}
+33 -34
View File
@@ -438,7 +438,6 @@ HWTEST_F(WantBaseTest, AaFwk_Want_Parcelable_0500, Function | MediumTest | Level
WantIn_->SetElement(element);
WantParams wantParams;
std::string keyStr = "system.test.wantparams.key";
std::string MIMEKEY = "mime-type";
wantParams.SetParam(MIMEKEY, String::Box("system.test.uritype"));
@@ -475,6 +474,14 @@ HWTEST_F(WantBaseTest, AaFwk_Want_Parcelable_0500, Function | MediumTest | Level
std::vector<std::string> stringArrayValue = {"stringtest1", "string@test2", "string@!#test2"};
WantIn_->SetParam(std::string("string_arraykey"), stringArrayValue);
Want wantCopy(*WantIn_);
std::vector<std::string> teststringArrayValue1 = WantIn_->GetStringArrayParam(std::string("string_arraykey"));
std::vector<std::string> teststringArrayValue2 = wantCopy.GetStringArrayParam(std::string("string_arraykey"));
bool copyarraycompare = CompareArrayData<std::string>(teststringArrayValue1, teststringArrayValue1);
EXPECT_EQ(copyarraycompare, true);
std::string str = (copyarraycompare == true) ? "true" : "false";
GTEST_LOG_(INFO) << "copyarraycompare=" << str.c_str();
Parcel in;
bool result = false;
result = WantIn_->Marshalling(in);
@@ -2153,7 +2160,7 @@ HWTEST_F(WantCharArrayParamTest, AaFwk_Want_Parameters_CharArray_0200, Function
*/
HWTEST_F(WantCharArrayParamTest, AaFwk_Want_Parameters_CharArray_0300, Function | MediumTest | Level1)
{
std::string emptyStr("");
std::string emptyStr("ff");
std::vector<zchar> firstValue({U'', U''});
std::vector<zchar> secondValue({U'', U''});
std::vector<zchar> thirdValue({U'', U''});
@@ -2258,7 +2265,7 @@ HWTEST_F(WantCharParamTest, AaFwk_Want_Parameters_Char_0200, Function | MediumTe
*/
HWTEST_F(WantCharParamTest, AaFwk_Want_Parameters_Char_0300, Function | MediumTest | Level1)
{
std::string emptyStr("");
std::string emptyStr("jj");
zchar firstValue = U'';
zchar secondValue = U'';
zchar thirdValue = U'';
@@ -2369,7 +2376,7 @@ HWTEST_F(WantDoubleArrayParamTest, AaFwk_Want_DoubleArray_0200, Function | Mediu
HWTEST_F(WantDoubleArrayParamTest, AaFwk_Want_DoubleArray_0300, Function | MediumTest | Level1)
{
std::vector<double> defaultValue;
std::string setKey1 = "";
std::string setKey1 = "cc";
std::string setKey2 = "aa";
std::vector<double> setValue1 = {1.1, 2.1};
std::vector<double> setValue2 = {5.1, 6.1};
@@ -2481,7 +2488,7 @@ HWTEST_F(WantFloatArrayParamTest, AaFwk_Want_FloatArray_0200, Function | MediumT
HWTEST_F(WantFloatArrayParamTest, AaFwk_Want_FloatArray_0300, Function | MediumTest | Level1)
{
std::vector<float> defaultValue;
std::string setKey1 = "";
std::string setKey1 = "hh";
std::string setKey2 = "aa";
std::vector<float> setValue1 = {1.1, 2.1};
want_->SetParam(setKey1, setValue1);
@@ -2590,7 +2597,7 @@ HWTEST_F(WantLongArrayParamTest, AaFwk_Want_LongArray_0200, Function | MediumTes
HWTEST_F(WantLongArrayParamTest, AaFwk_Want_LongArray_0300, Function | MediumTest | Level1)
{
std::vector<long> defaultValue;
std::string setKey1 = "";
std::string setKey1 = "bb";
std::string setKey2 = "aa";
std::vector<long> setValue1 = {1, 2};
want_->SetParam(setKey1, setValue1);
@@ -2698,7 +2705,7 @@ HWTEST_F(WantShortArrayParamTest, AaFwk_Want_ShortArray_0200, Function | MediumT
*/
HWTEST_F(WantShortArrayParamTest, AaFwk_Want_ShortArray_0300, Function | MediumTest | Level1)
{
std::string emptyStr("");
std::string emptyStr("hh");
std::vector<short> firstValue({1, 4, -9});
std::vector<short> secondValue({1, 8, -9});
std::vector<short> thirdValue({1, 4, 9});
@@ -2741,9 +2748,7 @@ public:
want_ = nullptr;
}
~WantShortParamTest()
{
want_ = nullptr;
}
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
@@ -2803,7 +2808,7 @@ HWTEST_F(WantShortParamTest, AaFwk_Want_Short_0200, Function | MediumTest | Leve
*/
HWTEST_F(WantShortParamTest, AaFwk_Want_Short_0300, Function | MediumTest | Level1)
{
std::string emptyStr("");
std::string emptyStr("bb");
short firstValue = 1;
short secondValue = 2;
short thirdValue = 4;
@@ -2849,14 +2854,12 @@ public:
want_ = nullptr;
}
~WantStringArrayParamTest()
{
want_ = nullptr;
}
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
std::shared_ptr<Want> want_;
std::shared_ptr<Want> want_ = nullptr;
};
void WantStringArrayParamTest::SetUpTestCase(void)
@@ -2918,7 +2921,7 @@ HWTEST_F(WantStringArrayParamTest, AaFwk_Want_StringArray_0300, Function | Mediu
std::vector<std::string> defaultValue;
std::vector<std::string> setValue1 = {"aaa", "2132"};
std::vector<std::string> setValue2 = {"1*中_aR", "dbdb"};
std::string key1 = "";
std::string key1 = "cc";
std::string key2 = "aa";
want_->SetParam(key1, setValue1);
want_->SetParam(key1, setValue1);
@@ -2963,9 +2966,7 @@ public:
want_ = nullptr;
}
~WantStringParamTest()
{
want_ = nullptr;
}
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
@@ -3029,7 +3030,7 @@ HWTEST_F(WantStringParamTest, AaFwk_Want_String_0300, Function | MediumTest | Le
std::string defaultStrValue;
std::string setValue1 = "aaa";
std::string setValue2 = "1*中_aR";
std::string key1 = "";
std::string key1 = "dd";
std::string key2 = "aa";
want_->SetParam(key1, setValue1);
want_->SetParam(key1, setValue1);
@@ -3067,14 +3068,12 @@ public:
want_ = nullptr;
}
~WantLongParamTest()
{
want_ = nullptr;
}
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
std::shared_ptr<Want> want_;
std::shared_ptr<Want> want_ = nullptr;
};
void WantLongParamTest::SetUpTestCase(void)
@@ -3108,8 +3107,8 @@ HWTEST_P(WantLongParamTest, AaFwk_Want_LongParam_0100, Function | MediumTest | L
}
INSTANTIATE_TEST_CASE_P(WantLongParamTestCaseP, WantLongParamTest,
testing::Values(testLongType("", "aa", -1, 100, 100), testLongType("", "", -9, -41, -9),
testLongType("1*中_aR", "aa", 50, 5, 5), testLongType("1*中_aR", "1*中_aR", -5000, 5000, -5000)));
testing::Values(testLongType("b1", "b1", -1, 100, -1), testLongType("b3", "b4", 600, 200, 200),
testLongType("b5", "b5", 50, 6, 50), testLongType("b6", "b7", 1000, 2200, 2200)));
/**
* @tc.number: AaFwk_Want_LongParam_0200
@@ -3130,7 +3129,7 @@ HWTEST_F(WantLongParamTest, AaFwk_Want_LongParam_0200, Function | MediumTest | L
*/
HWTEST_F(WantLongParamTest, AaFwk_Want_LongParam_0300, Function | MediumTest | Level1)
{
std::string setKey1 = "";
std::string setKey1 = "dd";
std::string setKey2 = "aa";
long setValue1 = 1;
long setValue2 = 5;
@@ -3238,7 +3237,7 @@ HWTEST_F(WantIntParamTest, AaFwk_Want_IntParam_0200, Function | MediumTest | Lev
*/
HWTEST_F(WantIntParamTest, AaFwk_Want_IntParam_0300, Function | MediumTest | Level1)
{
std::string emptyStr("");
std::string emptyStr("bb");
int firstValue = 1;
int secondValue = 2;
int thirdValue = 4;
@@ -3348,7 +3347,7 @@ HWTEST_F(WantIntArrayParamTest, AaFwk_Want_IntArrayParam_0200, Function | Medium
*/
HWTEST_F(WantIntArrayParamTest, AaFwk_Want_IntArrayParam_0300, Function | MediumTest | Level1)
{
std::string emptyStr("");
std::string emptyStr("cc");
std::vector<int> firstValue({1, 4, -9});
std::vector<int> secondValue({1, 8, -9});
std::vector<int> thirdValue({1, 4, 9});
@@ -3455,7 +3454,7 @@ HWTEST_F(WantFloatParamTest, AaFwk_Want_FloatParam_0200, Function | MediumTest |
*/
HWTEST_F(WantFloatParamTest, AaFwk_Want_FloatParam_0300, Function | MediumTest | Level1)
{
std::string setKey1 = "";
std::string setKey1 = "ee";
std::string setKey2 = "aa";
float setValue1 = 1.1;
float setValue2 = 5.1;
@@ -3564,7 +3563,7 @@ HWTEST_F(WantDoubleParamTest, AaFwk_Want_DoubleParam_0300, Function | MediumTest
*/
HWTEST_F(WantDoubleParamTest, AaFwk_Want_DoubleParam_0400, Function | MediumTest | Level1)
{
std::string setKey1 = "";
std::string setKey1 = "ff";
std::string setKey2 = "aa";
double setValue1 = 1.1;
double setValue2 = 5.1;
@@ -3673,7 +3672,7 @@ HWTEST_F(WantByteArrayParamTest, AaFwk_Want_ByteArray_0200, Function | MediumTes
*/
HWTEST_F(WantByteArrayParamTest, AaFwk_Want_ByteArray_0300, Function | MediumTest | Level1)
{
std::string emptyStr("");
std::string emptyStr("gg");
std::vector<byte> firstValue({'a', '2'});
std::vector<byte> secondValue({'1', 'd'});
std::vector<byte> thirdValue({'t', '3'});
@@ -3756,8 +3755,8 @@ HWTEST_P(WantBoolParamTest, AaFwk_Want_BoolParam_0100, Function | MediumTest | L
}
INSTANTIATE_TEST_CASE_P(WantBoolParamTestCaseP, WantBoolParamTest,
testing::Values(testBoolType("", "aa", true, true, true), testBoolType("", "aa", true, false, false),
testBoolType("", "", true, true, true), testBoolType("", "", true, false, true),
testing::Values(testBoolType("b1", "aa", true, true, true), testBoolType("b1", "aa", true, false, false),
testBoolType("b2", "b2", true, true, true), testBoolType("b3", "b3", true, false, true),
testBoolType("123", "123", true, false, true), testBoolType("123", "aa", true, false, false),
testBoolType("-~*&%¥", "-~*&%¥", true, false, true), testBoolType("-~*&%¥", "aa", true, false, false),
testBoolType("中文", "中文", true, false, true), testBoolType("中文", "aa", true, false, false),
+9 -1
View File
@@ -37,6 +37,7 @@ config("module_private_config") {
"//foundation/aafwk/standard/services/common/include",
"//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include",
"//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility",
"//foundation/aafwk/standard/services/abilitymgr/include",
]
}
@@ -50,8 +51,11 @@ ohos_moduletest("ability_moduletest") {
"//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility/demo_ability_test.cpp",
"//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility/mock_lifecycle_observer.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_connect_callback_stub.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_proxy.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_stub.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_mission_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_record_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_scheduler_proxy.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_scheduler_stub.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/caller_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/image_info.cpp",
@@ -60,8 +64,10 @@ ohos_moduletest("ability_moduletest") {
"//foundation/aafwk/standard/services/abilitymgr/src/mission_record_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/mission_snapshot_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/mission_stack_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/recent_mission_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/sender_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/stack_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/want_sender_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/wants_info.cpp",
"moduletest/cpp/abilitytest/ability_test.cpp",
]
@@ -103,8 +109,10 @@ ohos_moduletest("ability_conetxt_test") {
"//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility/demo_ability_test.cpp",
"//foundation/aafwk/standard/frameworks/kits/test/mock/DemoAbility/mock_lifecycle_observer.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_connect_callback_stub.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_proxy.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_manager_stub.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_record_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_scheduler_proxy.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/ability_scheduler_stub.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/caller_info.cpp",
"//foundation/aafwk/standard/services/abilitymgr/src/lifecycle_state_info.cpp",
+8 -8
View File
@@ -25,18 +25,18 @@
namespace OHOS {
namespace AAFwk {
std::shared_ptr<AbilityManagerClient> AbilityManagerClient::instance_ = nullptr;
std::mutex AbilityManagerClient::mutex_;
std::shared_ptr<AbilityManagerClient> mockMTInstance_ = nullptr;
std::mutex mockMTMutex_;
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>();
if (mockMTInstance_ == nullptr) {
std::lock_guard<std::mutex> lock_l(mockMTMutex_);
if (mockMTInstance_ == nullptr) {
mockMTInstance_ = std::make_shared<AbilityManagerClient>();
}
}
return instance_;
return mockMTInstance_;
}
AbilityManagerClient::AbilityManagerClient()
@@ -169,7 +169,7 @@ ErrCode AbilityManagerClient::DumpState(const std::string &args, std::vector<std
ErrCode AbilityManagerClient::Connect()
{
std::lock_guard<std::mutex> lock(mutex_);
std::lock_guard<std::mutex> lock(mockMTMutex_);
remoteObject_ =
OHOS::DelayedSingleton<AppExecFwk::SysMrgClient>::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID);
if (remoteObject_ == nullptr) {
@@ -170,7 +170,7 @@ int MockAbilityManagerService::StopServiceAbility(const Want &want)
}
int MockAbilityManagerService::GetRecentMissions(
const int32_t numMax, const int32_t flags, std::vector<RecentMissionInfo> &recentList)
const int32_t numMax, const int32_t flags, std::vector<AbilityMissionInfo> &recentList)
{
return 0;
}
@@ -208,5 +208,31 @@ ErrCode MockAbilityManagerService::ReleaseDataAbility(
}
return -1;
}
int MockAbilityManagerService::MoveMissionToEnd(const sptr<IRemoteObject> &token, const bool nonFirst)
{
return 0;
}
bool MockAbilityManagerService::IsFirstInMission(const sptr<IRemoteObject> &token)
{
return true;
}
int MockAbilityManagerService::CompelVerifyPermission(
const std::string &permission, int pid, int uid, std::string &message)
{
return 0;
}
int MockAbilityManagerService::PowerOff()
{
return 0;
}
int MockAbilityManagerService::PowerOn()
{
return 0;
}
} // namespace AAFwk
} // namespace OHOS
@@ -66,15 +66,41 @@ public:
MOCK_METHOD1(MoveMissionToTop, int(int32_t missionId));
MOCK_METHOD1(KillProcess, int(const std::string &bundleName));
MOCK_METHOD1(UninstallApp, int(const std::string &bundleName));
MOCK_METHOD2(
GetWantSender, sptr<IWantSender>(const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken));
MOCK_METHOD2(SendWantSender, int(const sptr<IWantSender> &target, const SenderInfo &senderInfo));
MOCK_METHOD1(CancelWantSender, void(const sptr<IWantSender> &sender));
MOCK_METHOD1(GetPendingWantUid, int(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantUserId, int(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantBundleName, std::string(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantCode, int(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantType, int(const sptr<IWantSender> &target));
MOCK_METHOD2(RegisterCancelListener, void(const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver));
MOCK_METHOD2(UnregisterCancelListener, void(const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver));
MOCK_METHOD2(GetPendingRequestWant, int(const sptr<IWantSender> &target, std::shared_ptr<Want> &want));
int MoveMissionToEnd(const sptr<IRemoteObject> &token, const bool nonFirst) override;
bool IsFirstInMission(const sptr<IRemoteObject> &token) override;
int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) override;
int GetRecentMissions(
const int32_t numMax, const int32_t flags, std::vector<RecentMissionInfo> &recentList) override;
const int32_t numMax, const int32_t flags, std::vector<AbilityMissionInfo> &recentList) override;
int GetMissionSnapshot(const int32_t missionId, MissionSnapshotInfo &snapshot) override;
int RemoveMission(int id) override;
int RemoveStack(int id) override;
int PowerOff() override;
int PowerOn() override;
int LockMission(int missionId) override
{
return 0;
};
int UnlockMission(int missionId) override
{
return 0;
};
AbilityLifeCycleState curstate_ = AbilityLifeCycleState::ABILITY_STATE_INITIAL;
sptr<IAbilityScheduler> abilityScheduler_; // kit interface used to schedule ability life
@@ -180,5 +180,30 @@ int MockServiceAbilityManagerService::RemoveStack(int id)
{
return 0;
}
int MockServiceAbilityManagerService::MoveMissionToEnd(const sptr<IRemoteObject> &token, const bool nonFirst)
{
return 0;
}
bool MockServiceAbilityManagerService::IsFirstInMission(const sptr<IRemoteObject> &token)
{
return true;
}
int MockServiceAbilityManagerService::CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message)
{
return 0;
}
int MockServiceAbilityManagerService::PowerOff()
{
return 0;
}
int MockServiceAbilityManagerService::PowerOn()
{
return 0;
}
} // namespace AAFwk
} // namespace OHOS
@@ -62,11 +62,36 @@ public:
MOCK_METHOD1(MoveMissionToTop, int(int32_t missionId));
MOCK_METHOD1(KillProcess, int(const std::string &bundleName));
MOCK_METHOD1(UninstallApp, int(const std::string &bundleName));
MOCK_METHOD2(
GetWantSender, sptr<IWantSender>(const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken));
MOCK_METHOD2(SendWantSender, int(const sptr<IWantSender> &target, const SenderInfo &senderInfo));
MOCK_METHOD1(CancelWantSender, void(const sptr<IWantSender> &sender));
MOCK_METHOD1(GetPendingWantUid, int(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantUserId, int(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantBundleName, std::string(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantCode, int(const sptr<IWantSender> &target));
MOCK_METHOD1(GetPendingWantType, int(const sptr<IWantSender> &target));
MOCK_METHOD2(RegisterCancelListener, void(const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver));
MOCK_METHOD2(UnregisterCancelListener, void(const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver));
MOCK_METHOD2(GetPendingRequestWant, int(const sptr<IWantSender> &target, std::shared_ptr<Want> &want));
int MoveMissionToEnd(const sptr<IRemoteObject> &token, const bool nonFirst) override;
bool IsFirstInMission(const sptr<IRemoteObject> &token) override;
int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) override;
int RemoveMission(int id) override;
int RemoveStack(int id) override;
int PowerOff() override;
int PowerOn() override;
int LockMission(int missionId) override
{
return 0;
};
int UnlockMission(int missionId) override
{
return 0;
};
sptr<IAbilityScheduler> AcquireDataAbility(
const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken) override
{
@@ -80,7 +105,7 @@ public:
}
int GetRecentMissions(
const int32_t numMax, const int32_t flags, std::vector<RecentMissionInfo> &recentList) override
const int32_t numMax, const int32_t flags, std::vector<AbilityMissionInfo> &recentList) override
{
return 0;
}
@@ -26,6 +26,7 @@ config("ability_manager_public_config") {
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr",
"//foundation/appexecfwk/standard/kits/appkit/native/app/include",
]
cflags = []
if (target_cpu == "arm") {
@@ -37,8 +38,11 @@ ohos_shared_library("ability_manager") {
sources = [
"${services_path}/abilitymgr/src/ability_connect_callback_stub.cpp",
"${services_path}/abilitymgr/src/ability_manager_client.cpp",
"${services_path}/abilitymgr/src/ability_manager_proxy.cpp",
"${services_path}/abilitymgr/src/ability_manager_stub.cpp",
"${services_path}/abilitymgr/src/ability_mission_info.cpp",
"${services_path}/abilitymgr/src/ability_record_info.cpp",
"${services_path}/abilitymgr/src/ability_scheduler_proxy.cpp",
"${services_path}/abilitymgr/src/ability_scheduler_stub.cpp",
"${services_path}/abilitymgr/src/caller_info.cpp",
"${services_path}/abilitymgr/src/image_info.cpp",
@@ -47,8 +51,10 @@ ohos_shared_library("ability_manager") {
"${services_path}/abilitymgr/src/mission_record_info.cpp",
"${services_path}/abilitymgr/src/mission_snapshot_info.cpp",
"${services_path}/abilitymgr/src/mission_stack_info.cpp",
"${services_path}/abilitymgr/src/recent_mission_info.cpp",
"${services_path}/abilitymgr/src/sender_info.cpp",
"${services_path}/abilitymgr/src/stack_info.cpp",
"${services_path}/abilitymgr/src/want_sender_info.cpp",
"${services_path}/abilitymgr/src/wants_info.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/task_handler.cpp",
"//foundation/aafwk/standard/frameworks/kits/ability/native/src/task_handler_client.cpp",
]
@@ -9,7 +9,7 @@
# 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.
# limitations under the License.
ability_manager_headers = {
header_files = [
@@ -24,6 +24,11 @@ ability_manager_headers = {
"stack_info.h",
"mission_record_info.h",
"ability_record_info.h",
"wants_info.h",
"sender_info.h",
"want_sender_info.h",
"want_sender_interface.h",
"want_receiver_interface.h",
]
header_base = "interfaces/innerkits/ability_manager/include"
}
@@ -220,7 +220,7 @@ public:
* of {@link #RECENT_WITH_EXCLUDED} and {@link #RECENT_IGNORE_UNAVAILABLE}.
* @return Returns ERR_OK on success, others on failure.
*/
ErrCode GetRecentMissions(const int32_t numMax, const int32_t flags, std::vector<RecentMissionInfo> &recentList);
ErrCode GetRecentMissions(const int32_t numMax, const int32_t flags, std::vector<AbilityMissionInfo> &recentList);
/**
* Get mission snapshot by mission id
@@ -239,6 +239,15 @@ public:
*/
ErrCode MoveMissionToTop(int32_t missionId);
/**
* Requires that tasks associated with a given capability token be moved to the background
*
* @param token ability token
* @param nonFirst If nonfirst is false and not the lowest ability of the mission, you cannot move mission to end
* @return Returns ERR_OK on success, others on failure.
*/
ErrCode MoveMissionToEnd(const sptr<IRemoteObject> &token, const bool nonFirst);
/**
* Remove the specified mission from the stack by missionid
*
@@ -263,6 +272,63 @@ public:
*/
ErrCode KillProcess(const std::string &bundleName);
/**
* @brief Checks whether this ability is the first ability in a mission.
*
* @return Returns true is first in Mission.
*/
ErrCode IsFirstInMission(const sptr<IRemoteObject> &token);
ErrCode CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message);
/**
* Save the top ability States and move them to the background
* @return Returns ERR_OK on success, others on failure.
*/
ErrCode PowerOff();
/**
* Restore the state before top ability poweroff
* @return Returns ERR_OK on success, others on failure.
*/
ErrCode PowerOn();
/**
* Sets the application to start its ability in lock mission mode.
* @param missionId luck mission id
* @return Returns ERR_OK on success, others on failure.
*/
ErrCode LockMission(int missionId);
/**
* Unlocks this ability by exiting the lock mission mode.
* @param missionId unluck mission id
* @return Returns ERR_OK on success, others on failure.
*/
ErrCode UnlockMission(int missionId);
sptr<IWantSender> GetWantSender(const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken);
ErrCode SendWantSender(const sptr<IWantSender> &target, const SenderInfo &senderInfo);
void CancelWantSender(const sptr<IWantSender> &sender);
ErrCode GetPendingWantUid(const sptr<IWantSender> &target, int32_t &uid);
ErrCode GetPendingWantUserId(const sptr<IWantSender> &target, int32_t &userId);
ErrCode GetPendingWantBundleName(const sptr<IWantSender> &target, std::string &bundleName);
ErrCode GetPendingWantCode(const sptr<IWantSender> &target, int32_t &code);
ErrCode GetPendingWantType(const sptr<IWantSender> &target, int32_t &type);
void RegisterCancelListener(const sptr<IWantSender> &sender, const sptr<IWantReceiver> &recevier);
void UnregisterCancelListener(const sptr<IWantSender> &sender, const sptr<IWantReceiver> &recevier);
ErrCode GetPendingRequestWant(const sptr<IWantSender> &target, std::shared_ptr<Want> &want);
private:
static std::mutex mutex_;
static std::shared_ptr<AbilityManagerClient> instance_;
@@ -173,6 +173,32 @@ enum {
* Result(2097185) for check permission failed.
*/
CHECK_PERMISSION_FAILED,
/**
* Result(2097186) for waiting ability lifecycle complete.
*/
POWER_OFF_WAITING,
/**
* Result(2097187) for power off failed.
*/
POWER_OFF_FAILED,
/**
* Result(2097188) for power on failed.
*/
POWER_ON_FAILED,
/**
* Result(2097189) for ability no first in mission.
*/
NO_FIRST_IN_MISSION,
/**
* Result(2097190) for lock mission errors.
*/
LOCK_MISSION_DENY_FAILED,
/**
* Result(2097191) for unlock mission errors.
*/
UNLOCK_MISSION_DENY_FAILED,
};
enum {
@@ -24,10 +24,14 @@
#include "ability_connect_callback_interface.h"
#include "ability_scheduler_interface.h"
#include "mission_snapshot_info.h"
#include "recent_mission_info.h"
#include "ability_mission_info.h"
#include "stack_info.h"
#include "uri.h"
#include "want.h"
#include "want_sender_info.h"
#include "sender_info.h"
#include "want_sender_interface.h"
#include "want_receiver_interface.h"
namespace OHOS {
namespace AAFwk {
@@ -222,7 +226,7 @@ public:
* @return Returns ERR_OK on success, others on failure.
*/
virtual int GetRecentMissions(
const int32_t numMax, const int32_t flags, std::vector<RecentMissionInfo> &recentList) = 0;
const int32_t numMax, const int32_t flags, std::vector<AbilityMissionInfo> &recentList) = 0;
/**
* Get mission snapshot by mission id
@@ -241,6 +245,15 @@ public:
*/
virtual int MoveMissionToTop(int32_t missionId) = 0;
/**
* Requires that tasks associated with a given capability token be moved to the background
*
* @param token ability token
* @param nonFirst If nonfirst is false and not the lowest ability of the mission, you cannot move mission to end
* @return Returns ERR_OK on success, others on failure.
*/
virtual int MoveMissionToEnd(const sptr<IRemoteObject> &token, const bool nonFirst) = 0;
/**
* Remove the specified mission from the stack by missionid
*
@@ -273,6 +286,73 @@ public:
*/
virtual int UninstallApp(const std::string &bundleName) = 0;
/** Checks whether this ability is the first ability in a mission.
* @param lostToken, the token of ability
* @return Returns true is first in Mission.
*/
virtual bool IsFirstInMission(const sptr<IRemoteObject> &token) = 0;
/**
* Checks whether a specified permission has been granted to the process identified by pid and uid
*
* @param permission Indicates the permission to check.
* @param pid Indicates the ID of the process to check.
* @param uid Indicates the UID of the process to check.
* @param message Describe success or failure
*
* @return Returns ERR_OK on success, others on failure.
*/
virtual int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) = 0;
/**
* Save the top ability States and move them to the background
* @return Returns ERR_OK on success, others on failure.
*/
virtual int PowerOff() = 0;
/**
* Restore the state before top ability poweroff
* @return Returns ERR_OK on success, others on failure.
*/
virtual int PowerOn() = 0;
/**
* Sets the application to start its ability in lock mission mode.
* @param missionId luck mission id
* @return Returns ERR_OK on success, others on failure.
*/
virtual int LockMission(int missionId) = 0;
/**
* Unlocks this ability by exiting the lock mission mode.
* @param missionId unluck mission id
* @return Returns ERR_OK on success, others on failure.
*/
virtual int UnlockMission(int missionId) = 0;
virtual sptr<IWantSender> GetWantSender(
const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken) = 0;
virtual int SendWantSender(const sptr<IWantSender> &target, const SenderInfo &senderInfo) = 0;
virtual void CancelWantSender(const sptr<IWantSender> &sender) = 0;
virtual int GetPendingWantUid(const sptr<IWantSender> &target) = 0;
virtual int GetPendingWantUserId(const sptr<IWantSender> &target) = 0;
virtual std::string GetPendingWantBundleName(const sptr<IWantSender> &target) = 0;
virtual int GetPendingWantCode(const sptr<IWantSender> &target) = 0;
virtual int GetPendingWantType(const sptr<IWantSender> &target) = 0;
virtual void RegisterCancelListener(const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver) = 0;
virtual void UnregisterCancelListener(const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver) = 0;
virtual int GetPendingRequestWant(const sptr<IWantSender> &target, std::shared_ptr<Want> &want) = 0;
enum {
// ipc id 1-1000 for kit
// ipc id for terminating ability (1)
@@ -332,6 +412,27 @@ public:
// ipc id for terminate ability by callerToken and request code (19)
TERMINATE_ABILITY_BY_CALLER,
// ipc id for isfirstinmission app (28)
IS_FIRST_IN_MISSION,
// ipc id for move mission to end (29)
MOVE_MISSION_TO_END,
// ipc id for compel verify permission (30)
COMPEL_VERIFY_PERMISSION,
// ipc id for power off (31)
POWER_OFF,
// ipc id for power off (32)
POWER_ON,
// ipc id for luck mission (33)
LUCK_MISSION,
// ipc id for unluck mission (34)
UNLUCK_MISSION,
// ipc id 1001-2000 for DMS
// ipc id for starting ability (1001)
START_ABILITY = 1001,
@@ -345,9 +446,31 @@ public:
// ipc id for disconnecting ability (1004)
STOP_SERVICE_ABILITY,
// ipc id for disconnecting ability (1004)
// ipc id for starting ability by caller(1005)
START_ABILITY_ADD_CALLER,
GET_PENDING_WANT_SENDER,
SEND_PENDING_WANT_SENDER,
CANCEL_PENDING_WANT_SENDER,
GET_PENDING_WANT_UID,
GET_PENDING_WANT_BUNDLENAME,
GET_PENDING_WANT_USERID,
GET_PENDING_WANT_TYPE,
GET_PENDING_WANT_CODE,
REGISTER_CANCEL_LISTENER,
UNREGISTER_CANCEL_LISTENER,
GET_PENDING_REQUEST_WANT,
// ipc id 2001-3000 for tools
// ipc id for dumping state (2001)
DUMP_STATE = 2001,
@@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef OHOS_AAFWK_INTERFACES_INNERKITS_RECENT_MISSION_INFO_H
#define OHOS_AAFWK_INTERFACES_INNERKITS_RECENT_MISSION_INFO_H
#ifndef OHOS_AAFWK_INTERFACES_INNERKITS_ABILITY_MISSION_INFO_H
#define OHOS_AAFWK_INTERFACES_INNERKITS_ABILITY_MISSION_INFO_H
#include <string>
@@ -26,12 +26,13 @@
namespace OHOS {
namespace AAFwk {
/**
* @struct RecentMissionInfo
* RecentMissionInfo is used to save informations about recent mission.
* @struct AbilityMissionInfo
* AbilityMissionInfo is used to save informations about ability mission.
*/
struct RecentMissionInfo : public Parcelable {
struct AbilityMissionInfo : public Parcelable {
int32_t id = -1;
int32_t runingState = -1;
int32_t missionStackId = -1;
Want baseWant;
AppExecFwk::ElementName baseAbility;
AppExecFwk::ElementName topAbility;
@@ -40,8 +41,8 @@ struct RecentMissionInfo : public Parcelable {
bool ReadFromParcel(Parcel &parcel);
virtual bool Marshalling(Parcel &parcel) const override;
static RecentMissionInfo *Unmarshalling(Parcel &parcel);
static AbilityMissionInfo *Unmarshalling(Parcel &parcel);
};
} // namespace AAFwk
} // namespace OHOS
#endif // OHOS_AAFWK_INTERFACES_INNERKITS_RECENT_MISSION_INFO_H
#endif // OHOS_AAFWK_INTERFACES_INNERKITS_ABILITY_MISSION_INFO_H
@@ -196,6 +196,12 @@ public:
*/
virtual int BatchInsert(const Uri &uri, const std::vector<ValuesBucket> &values) = 0;
/**
* @brief Displays a system-defined message to the user, prompting the user how to exit the lock mission mode.
*
*/
virtual void DisplayUnlockMissionMessage() = 0;
enum {
// ipc id for scheduling ability to a state of life cycle
SCHEDULE_ABILITY_TRANSACTION = 0,
@@ -247,6 +253,9 @@ public:
// ipc id for scheduling BatchInsert
SCHEDULE_BATCHINSERT,
// ipc id for display unlock message
DISPLAY_UNLOCK_MISSION_MESSAGE
};
};
} // namespace AAFwk
@@ -43,6 +43,7 @@ struct LifeCycleStateInfo : public Parcelable {
AbilityLifeCycleState state = AbilityLifeCycleState::ABILITY_STATE_INITIAL;
bool isNewWant = false;
int missionId = -1;
int stackId = -1;
CallerInfo caller;
bool ReadFromParcel(Parcel &parcel);
@@ -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 OHOS_AAFWK_INTERFACES_SENDER_INFO_H
#define OHOS_AAFWK_INTERFACES_SENDER_INFO_H
#include <string>
#include "parcel.h"
#include "want.h"
#include "want_receiver_interface.h"
namespace OHOS {
namespace AAFwk {
struct SenderInfo : public Parcelable {
int32_t code;
Want want;
std::string resolvedType;
sptr<IWantReceiver> finishedReceiver;
std::string requiredPermission;
bool ReadFromParcel(Parcel &parcel);
virtual bool Marshalling(Parcel &parcel) const override;
static SenderInfo *Unmarshalling(Parcel &parcel);
};
} // namespace AAFwk
} // namespace OHOS
#endif // OHOS_AAFWK_INTERFACES_SENDER_INFO_H
@@ -0,0 +1,39 @@
/*
* 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_WANT_RECEIVER_INTERFACE_H
#define OHOS_AAFWK_WANT_RECEIVER_INTERFACE_H
#include <iremote_broker.h>
#include "want.h"
#include "want_params.h"
namespace OHOS {
namespace AAFwk {
class IWantReceiver : public OHOS::IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.aafwk.WantReceiver");
virtual void Send(const int32_t resultCode) = 0;
virtual void PerformReceive(const Want &want, int resultCode, const std::string &data, const WantParams &extras,
bool serialized, bool sticky, int sendingUser) = 0;
enum {
WANT_RECEIVER_SEND = 0,
WANT_RECEIVER_PERFORM_RECEIVE,
};
};
} // namespace AAFwk
} // namespace OHOS
#endif // OHOS_AAFWK_WANT_RECEIVER_INTERFACE_H
@@ -0,0 +1,45 @@
/*
* 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_INTERFACES_INNERKITS_WANT_SENDER_INFO_H
#define OHOS_AAFWK_INTERFACES_INNERKITS_WANT_SENDER_INFO_H
#include <string>
#include <vector>
#include "parcel.h"
#include "wants_info.h"
namespace OHOS {
namespace AAFwk {
struct WantSenderInfo : public Parcelable {
int32_t type;
std::string bundleName;
std::string resultWho;
int32_t requestCode;
std::vector<WantsInfo> allWants;
int32_t flags;
int32_t userId;
bool ReadFromParcel(Parcel &parcel);
virtual bool Marshalling(Parcel &parcel) const override;
static WantSenderInfo *Unmarshalling(Parcel &parcel);
};
} // namespace AAFwk
} // namespace OHOS
#endif // OHOS_AAFWK_INTERFACES_INNERKITS_WANT_SENDER_INFO_H
@@ -13,16 +13,25 @@
* limitations under the License.
*/
#ifndef FOUNDATION_APPEXECFWK_OHOS_RAWFILEDESCRIPTOR_H
#define FOUNDATION_APPEXECFWK_OHOS_RAWFILEDESCRIPTOR_H
#ifndef OHOS_AAFWK_WANT_SENDER_INTERFACE_H
#define OHOS_AAFWK_WANT_SENDER_INTERFACE_H
#include <iremote_broker.h>
#include "want.h"
#include "sender_info.h"
namespace OHOS {
namespace AppExecFwk {
class RawFileDescriptor {
namespace AAFwk {
class IWantSender : public OHOS::IRemoteBroker {
public:
RawFileDescriptor() = default;
~RawFileDescriptor() = default;
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.aafwk.WantSender");
virtual void Send(SenderInfo &senderInfo) = 0;
enum {
WANT_SENDER_SEND = 0,
};
};
} // namespace AppExecFwk
} // namespace AAFwk
} // namespace OHOS
#endif // FOUNDATION_APPEXECFWK_OHOS_RAWFILEDESCRIPTOR_H
#endif // OHOS_AAFWK_WANT_SENDER_INTERFACE_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 OHOS_AAFWK_INTERFACES_INNERKITS_WANTS_INFO_H
#define OHOS_AAFWK_INTERFACES_INNERKITS_WANTS_INFO_H
#include <string>
#include "parcel.h"
#include "want.h"
namespace OHOS {
namespace AAFwk {
struct WantsInfo : public Parcelable {
Want want;
std::string resolvedTypes;
bool ReadFromParcel(Parcel &parcel);
virtual bool Marshalling(Parcel &parcel) const override;
static WantsInfo *Unmarshalling(Parcel &parcel);
};
} // namespace AAFwk
} // namespace OHOS
#endif // OHOS_AAFWK_INTERFACES_INNERKITS_WANTS_INFO_H
+2
View File
@@ -36,6 +36,7 @@ config("want_public_config") {
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content",
"//foundation/aafwk/standard/frameworks/kits/content/cpp/src",
]
}
@@ -50,6 +51,7 @@ ohos_shared_library("want") {
"${wantImpl}/skills.cpp",
"${wantImpl}/want.cpp",
"${wantImpl}/want_params.cpp",
"${wantImpl}/want_params_wrapper.cpp",
]
deps = [
+4 -4
View File
@@ -18,10 +18,10 @@
namespace OHOS {
namespace AAFwk {
enum class MatchType {
PATTERN_LITERAL = 0,
PATTERN_PREFIX = 1,
PATTERN_REGEX = 2,
PATTERN_SIMPLE_GLOB = 3,
DEFAULT = 0,
PREFIX = 1,
PATTERN = 2,
GLOBAL = 3,
};
}
} // namespace OHOS
+11 -10
View File
@@ -434,16 +434,17 @@ public:
static Skills *Unmarshalling(Parcel &parcel);
private:
static const int NO_MATCH_TYPE = -1;
static const int NO_MATCH_DATA = -2;
static const int NO_MATCH_ACTION = -3;
static const int NO_MATCH_CATEGORY = -4;
static const int MATCH_CATEGORY_EMPTY = 0x0100000;
static const int MATCH_CATEGORY_SCHEME = 0x0200000;
static const int MATCH_CATEGORY_PATH = 0x0500000;
static const int MATCH_CATEGORY_SCHEME_SPECIFIC_PART = 0x0580000;
static const int MATCH_CATEGORY_TYPE = 0x0600000;
static const int MATCH_ADJUSTMENT_NORMAL = 0x8000;
static const int DISMATCH_TYPE = -101;
static const int DISMATCH_DATA = -102;
static const int DISMATCH_ACTION = -103;
static const int DISMATCH_ENTITIES = -104;
static const int RESULT_EMPTY = 0x10000;
static const int RESULT_SCHEME = 0x20000;
static const int RESULT_PATH = 0x50000;
static const int RESULT_SCHEME_SPECIFIC_PART = 0x58000;
static const int RESULT_TYPE = 0x60000;
static const int RESULT_NORMAL = 0x800;
std::vector<std::string> entities_;
std::vector<std::string> actions_;
@@ -755,7 +755,7 @@ public:
// entity definition
static const std::string ENTITY_HOME;
static const std::string ENTITY_VIDEO;
static const std::string FLAG_HW_HOME_INTENT_FROM_SYSTEM;
static const std::string FLAG_HOME_INTENT_FROM_SYSTEM;
// flag definition
static unsigned int FLAG_ABILITY_NEW_MISSION;
@@ -33,6 +33,17 @@ public:
inline ~WantParams()
{}
WantParams &operator=(const WantParams &other);
bool operator==(const WantParams &other);
static sptr<IInterface> GetInterfaceByType(int typeId, const std::string &value);
static bool CompareInterface(const sptr<IInterface> iIt1, const sptr<IInterface> iIt2, int typeId);
static int GetDataType(const sptr<IInterface> iIt);
static std::string GetStringByType(const sptr<IInterface> iIt, int typeId);
void SetParam(const std::string &key, IInterface *value);
sptr<IInterface> GetParam(const std::string &key) const;
@@ -76,6 +87,8 @@ private:
VALUE_TYPE_DOUBLEARRAY = 18,
VALUE_TYPE_STRINGARRAY = 19,
VALUE_TYPE_CHARSEQUENCEARRAY = 20,
VALUE_TYPE_WANTPARAMS = 21,
VALUE_TYPE_ARRAY = 22,
};
bool WriteArrayToParcel(Parcel &parcel, IArray *ao) const;
@@ -97,10 +110,12 @@ private:
bool ReadFromParcelArrayByte(Parcel &parcel, sptr<IArray> &ao);
bool ReadFromParcelArrayChar(Parcel &parcel, sptr<IArray> &ao);
bool ReadFromParcelArrayShort(Parcel &parcel, sptr<IArray> &ao);
bool ReadFromParcelArrayInt(Parcel &parcel, sptr<IArray> &ao);
bool ReadFromParcelArrayLong(Parcel &parcel, sptr<IArray> &ao);
bool ReadFromParcelArrayFloat(Parcel &parcel, sptr<IArray> &ao);
bool ReadFromParcelArrayDouble(Parcel &parcel, sptr<IArray> &ao);
bool ReadFromParcelWantParamWrapper(Parcel &parcel, const std::string &key);
bool WriteArrayToParcelString(Parcel &parcel, IArray *ao) const;
bool WriteArrayToParcelBool(Parcel &parcel, IArray *ao) const;
@@ -122,7 +137,12 @@ private:
bool WriteToParcelLong(Parcel &parcel, sptr<IInterface> &o) const;
bool WriteToParcelFloat(Parcel &parcel, sptr<IInterface> &o) const;
bool WriteToParcelDouble(Parcel &parcel, sptr<IInterface> &o) const;
bool WriteToParcelWantParams(Parcel &parcel, sptr<IInterface> &o) const;
friend class WantParamWrapper;
// inner use function
bool NewArrayData(IArray *source, sptr<IArray> &dest);
bool NewParams(const WantParams &source, WantParams &dest);
std::map<std::string, sptr<IInterface>> params_;
};
} // namespace AAFwk
+99
View File
@@ -0,0 +1,99 @@
/*
* 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 { AsyncCallback } from './.basic';
import { Context } from './app/context';
import { Want } from './ability/want';
import { StartAbilityParameter, StartAbilityForResultParameter } from './ability/startabilityparameter';
import { AbilityResult, StartAbilityResult } from './ability/abilityresult';
/**
* A Feature Ability represents an ability with a UI and is designed to interact with users.
* @name featureAbility
* @since 3
* @sysCap AAFwk
* @devices phone, tablet
* @permission N/A
*/
declare namespace featureAbility {
/**
* Checks whether the main window of this ability has window focus.
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
* @param -
* @return Returns true if this ability currently has window focus; returns false otherwise.
*/
function hasWindowFocus(): Promise<boolean>;
function hasWindowFocus(callback: AsyncCallback<boolean>): void;
/**
* Destroys the current ability.
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
* @param -
* @return -
*/
function terminateAbility(): Promise<void>;
function terminateAbility(callback: AsyncCallback<void>): void;
/**
* Obtain the want sended from the source ability.
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
* @param parameter Indicates the ability to start.
* @return -
*/
function getWant(callback: AsyncCallback<Want>): void;
function getWant(): Promise<Want>;
/**
* Starts a new ability.
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
* @param parameter Indicates the ability to start.
* @return -
*/
function startAbility(parameter: StartAbilityParameter, callback: AsyncCallback<number>): void;
function startAbility(parameter: StartAbilityParameter): Promise<number>;
/**
* Starts a new ability, onAbilityResult will be called after this new ability is terminated.
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
* @param parameter Indicates the ability to start.
* @return -
*/
function startAbilityForResult(parameter: StartAbilityForResultParameter,
resultCallback: AsyncCallback<StartAbilityResult>, callback: AsyncCallback<number>): void;
function startAbilityForResult(parameter: StartAbilityForResultParameter,
resultCallback: AsyncCallback<StartAbilityResult>): Promise<number>;
/**
* Sets the result code and data to be returned by this Feature ability to the caller.
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
* @param AbilityResult Indicates the result code returned after the ability is destroyed.
* You can define the result code to identify an error.
* @return -
*/
function finishWithResult(result: AbilityResult, callback: AsyncCallback<void>): void;
function finishWithResult(result: AbilityResult): Promise<void>;
}
export default featureAbility;
+263
View File
@@ -0,0 +1,263 @@
/*
* 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.
*/
/**
* the constant for action and entity in the want
* @name wantConstant
* @since 3
* @sysCap aafwk
* @devices phone, tablet
* @permission N/A
*/
declare namespace wantConstant {
/**
* the constant for action of the want
* @name Action
* @since 3
* @sysCap aafwk
* @devices phone, tablet
* @permission N/A
*/
export enum Action {
/**
* Indicates the action of backing home.
*
* @since 1
*/
ACTION_HOME = "action.system.home",
/**
* Indicates the action of playing a media item.
*
* @since 1
*/
ACTION_PLAY = "action.system.play",
/**
* Indicates the action of installing a bundle.
*
* @since 1
*/
ACTION_BUNDLE_ADD = "action.bundle.add",
/**
* Indicates the action of uninstalling a bundle.
*
* @since 1
*/
ACTION_BUNDLE_REMOVE = "action.bundle.remove",
/**
* Indicates the action of updating a bundle.
*
* @since 1
*/
ACTION_BUNDLE_UPDATE = "action.bundle.update",
/**
* Indicates the action of booking a taxi.
*
* @since 1
*/
ACTION_ORDER_TAXI = "ability.intent.ORDER_TAXI",
/**
* Indicates the action of querying driving bans.
*
* @since 1
*/
ACTION_QUERY_TRAFFIC_RESTRICTION = "ability.intent.QUERY_TRAFFIC_RESTRICTION",
/**
* Indicates the action of querying routes.
*
* @since 1
*/
ACTION_PLAN_ROUTE = "ability.intent.PLAN_ROUTE",
/**
* Indicates the action of booking a flight.
*
* @since 1
*/
ACTION_BOOK_FLIGHT = "ability.intent.BOOK_FLIGHT",
/**
* Indicates the action of booking a train ticket.
*
* @since 1
*/
ACTION_BOOK_TRAIN_TICKET = "ability.intent.BOOK_TRAIN_TICKET",
/**
* Indicates the action of booking a hotel.
*
* @since 1
*/
ACTION_BOOK_HOTEL = "ability.intent.BOOK_HOTEL",
/**
* Indicates the action of querying a travel guide.
*
* @since 1
*/
ACTION_QUERY_TRAVELLING_GUIDELINE = "ability.intent.QUERY_TRAVELLING_GUIDELINE",
/**
* Indicates the action of querying nearby places.
*
* @since 1
*/
ACTION_QUERY_POI_INFO = "ability.intent.QUERY_POI_INFO",
/**
* Indicates the action of querying horoscope.
*
* @since 1
*/
ACTION_QUERY_CONSTELLATION_FORTUNE = "ability.intent.QUERY_CONSTELLATION_FORTUNE",
/**
* Indicates the action of querying the Chinese Almanac calendar.
*
* @since 1
*/
ACTION_QUERY_ALMANC = "ability.intent.QUERY_ALMANC",
/**
* Indicates the action of querying weather.
*
* @since 1
*/
ACTION_QUERY_WEATHER = "ability.intent.QUERY_WEATHER",
/**
* Indicates the action of querying the encyclopedia.
*
* @since 1
*/
ACTION_QUERY_ENCYCLOPEDIA = "ability.intent.QUERY_ENCYCLOPEDIA",
/**
* Indicates the action of searching for a recipe.
*
* @since 1
*/
ACTION_QUERY_RECIPE = "ability.intent.QUERY_RECIPE",
/**
* Indicates the action of ordering take-out food.
*
* @since 1
*/
ACTION_BUY_TAKEOUT = "ability.intent.BUY_TAKEOUT",
/**
* Indicates the action of translating text.
*
* @since 1
*/
ACTION_TRANSLATE_TEXT = "ability.intent.TRANSLATE_TEXT",
/**
* Indicates the action of shopping.
*
* @since 1
*/
ACTION_BUY = "ability.intent.BUY",
/**
* Indicates the action of tracking shipment status.
*
* @since 1
*/
ACTION_QUERY_LOGISTICS_INFO = "ability.intent.QUERY_LOGISTICS_INFO",
/**
* Indicates the action of shipping a bundle.
*
* @since 1
*/
ACTION_SEND_LOGISTICS = "ability.intent.SEND_LOGISTICS",
/**
* Indicates the action of querying sports teams and game schedule.
*
* @since 1
*/
ACTION_QUERY_SPORTS_INFO = "ability.intent.QUERY_SPORTS_INFO",
/**
* Indicates the action of browsing news.
*
* @since 1
*/
ACTION_QUERY_NEWS = "ability.intent.QUERY_NEWS",
/**
* Indicates the action of reading jokes.
*
* @since 1
*/
ACTION_QUERY_JOKE = "ability.intent.QUERY_JOKE",
/**
* Indicates the action of watching video clips.
*
* @since 1
*/
ACTION_WATCH_VIDEO_CLIPS = "ability.intent.WATCH_VIDEO_CLIPS",
/**
* Indicates the action of querying stock market quotes.
*
* @since 1
*/
ACTION_QUERY_STOCK_INFO = "ability.intent.QUERY_STOCK_INFO",
/**
* Indicates that the locale has changed.
*
* @since 1
*/
ACTION_LOCALE_CHANGED = "ability.intent.LOCALE_CHANGED"
}
/**
* the constant for Entity of the want
* @name Action
* @since 3
* @sysCap aafwk
* @devices phone, tablet
* @permission N/A
*/
export enum Entity {
/**
* Indicates the home screen category.
*
* @since 1
*/
ENTITY_HOME = "entity.system.home",
/**
* Indicates the video category.
*
* @since 1
*/
ENTITY_VIDEO = "entity.system.video"
}
}
export default wantConstant;
+228
View File
@@ -0,0 +1,228 @@
/*
* 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 { AbilityMissionInfo } from './app/abilitymissioninfo';
import { RunningProcessInfo } from './app/runningprocessinfo';
import { AsyncCallback } from './.basic';
/**
* Obtains running process and memory information about an application.
* @name abilityManager
* @since 3
* @sysCap appexecfwk
* @devices phone, tablet
* @permission N/A
*/
declare namespace abilityManager {
export enum WeightReasonCode {
REASON_UNKNOWN = 0,
WEIGHT_FOREGROUND = 100,
WEIGHT_FOREGROUND_SERVICE = 125,
WEIGHT_VISIBLE = 200,
WEIGHT_PERCEPTIBLE = 230,
WEIGHT_SERVICE = 300,
WEIGHT_TOP_SLEEPING = 325,
WEIGHT_CANT_SAVE_STATE = 350,
WEIGHT_CACHED = 400,
WEIGHT_GONE = 1000,
}
/**
* Obtains information about application processes that are running on the device.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @returns Returns a list of running processes.
*/
function getAllRunningProcesses(): Promise<Array<RunningProcessInfo>>;
/**
* Obtains information about the application process running on the device through callback.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @param callback Specified callback method.
*/
function getAllRunningProcesses(callback: AsyncCallback<Array<RunningProcessInfo>>): void;
/**
* Queries information about the running Ability Mission.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @returns Returns the AbilityMissionInfos.
*/
function queryRunningAbilityMissionInfos(maxNum: number): Promise<Array<AbilityMissionInfo>>;
/**
* Queries information about the running Ability Mission through callback.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @param callback Specified callback method.
*/
function queryRunningAbilityMissionInfos(maxNum: number, callback: AsyncCallback<Array<AbilityMissionInfo>>): void;
/**
* Queries information about the recent Ability Mission.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @returns Returns the AbilityMissionInfos.
*/
function queryRecentAbilityMissionInfos(maxNum: number, flag: number): Promise<Array<AbilityMissionInfo>>;
/**
* Queries information about the recent Ability Mission.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @param callback Specified callback method.
*/
function queryRecentAbilityMissionInfos(maxNum: number, flag: number, callback: AsyncCallback<Array<AbilityMissionInfo>>): void;
/**
* Remove the mission associated with the given mission ID.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @param missionId Indicates the mission ID
* @returns Returns 0 for success, return non-0 for failure.
*/
function removeMission(missionId: number): Promise<number>;
/**
* Remove the mission associated with the given mission ID.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @param missionId Indicates the mission ID
* @param callback Specified callback method
*/
function removeMission(missionId: number, callback: AsyncCallback<number>): void;
/**
* Remove the missions associated with the given array of the mission ID.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @param missionIds Indicates the array of the mission ID
* @returns Returns 0 for success, return non-0 for failure.
*/
function removeMissions(missionIds: Array<number>): Promise<number>;
/**
* Remove the missions associated with the given array of the mission ID.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @param missionIds Indicates the array of the mission ID
* @param callback Specified callback method
*/
function removeMissions(missionIds: Array<number>, callback: AsyncCallback<number>): void;
/**
* Removes all the recent missions
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @returns Returns 0 for success, return non-0 for failure.
*/
function clearMissions(): Promise<number>;
/**
* Removes all the recent missions
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @param callback Specified callback method.
*/
function clearMissions(callback: AsyncCallback<number>): void;
/**
* Ask that the mission associated with a given mission ID be moved to the
* front of the stack.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @param missionId Indicates the mission ID
* @returns Returns 0 for success, return non-0 for failure.
*/
function moveMissionToTop(missionId: number): Promise<number>;
/**
* Ask that the mission associated with a given mission ID be moved to the
* front of the stack.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @param missionId Indicates the mission ID
* @param callback Specified callback method.
*/
function moveMissionToTop(missionId: number, callback: AsyncCallback<number>): void;
/**
* Kills all background processes associated with a specified bundle.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @param bundleName Indicates the bundle name
* @returns Returns 0 for success, return non-0 for failure.
*/
function killProcessesByBundleName(bundleName: string): Promise<number>;
/**
* Kills all background processes associated with a specified bundle through callback.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
* @param bundleName Indicates the bundle name
* @param callback Specified callback method
*/
function killProcessesByBundleName(bundleName: string, callback: AsyncCallback<number>): void;
}
export default abilityManager;
+345
View File
@@ -0,0 +1,345 @@
/*
* 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 { AsyncCallback } from './.basic';
import { ApplicationInfo } from './bundle/applicationinfo';
import { BundleInfo } from './bundle/bundleinfo';
import { AbilityInfo } from './bundle/abilityinfo';
import { Want } from './ability/want';
import { BundleInstaller } from './bundle/bundleinstaller';
import permission from './@ohos.security.permission';
/**
* @name BundleFlag
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export declare interface BundleFlag {
getBundleDefault: boolean;
getBundleWithAbilities: boolean;
getAbilityInfoWithPermission: boolean;
getAbilityInfoWithApplication: boolean;
getApplicationInfoWithPermission: boolean;
getBundleWithRequestedPermission: boolean;
getAllApplicationInfo: boolean;
}
export declare interface QueryParameter {
flags?: number;
userId?: string;
}
/**
* bundle.
* @name bundle
* @since 3
* @sysCap appexecfwk
* @devices phone, tablet
* @permission N/A
*/
declare namespace bundle {
export enum ModuleUpdateFlag {
FLAG_MODULE_UPGRADE_CHECK = 0,
FLAG_MODULE_UPGRADE_INSTALL = 1,
FLAG_MODULE_UPGRADE_INSTALL_WITH_CONFIG_WINDOWS = 2,
}
export enum FormType {
JAVA = 0,
JS = 1,
}
export enum ColorMode {
AUTO_MODE = -1,
DARK_MODE = 0,
LIGHT_MODE = 1,
}
export enum GrantStatus {
PERMISSION_DENIED = -1,
PERMISSION_GRANTED = 0,
}
export enum ModuleRemoveFlag {
FLAG_MODULE_NOT_USED_BY_FORM = 0,
FLAG_MODULE_USED_BY_FORM = 1,
FLAG_MODULE_NOT_USED_BY_SHORTCUT = 2,
FLAG_MODULE_USED_BY_SHORTCUT = 3,
}
export enum SignatureCompareResult {
SIGNATURE_MATCHED = 0,
SIGNATURE_NOT_MATCHED = 1,
SIGNATURE_UNKNOWN_BUNDLE = 2,
}
export enum ShortcutExistence {
SHORTCUT_EXISTENCE_EXISTS = 0,
SHORTCUT_EXISTENCE_NOT_EXISTS = 1,
SHORTCUT_EXISTENCE_UNKNOW = 2,
}
export enum QueryShortCutFlag {
QUERY_SHORTCUT_HOME = 0,
}
/**
* @name AbilityType
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export enum AbilityType {
UNKNOWN,
PAGE,
SERVICE,
DATA,
}
/**
* @name AbilitySubType
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export enum AbilitySubType {
UNSPECIFIED = 0,
CA = 1,
}
/**
* @name DisplayOrientation
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export enum DisplayOrientation {
UNSPECIFIED,
LANDSCAPE,
PORTRAIT,
FOLLOWRECENT,
}
/**
* @name LaunchMode
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export enum LaunchMode {
SINGLETON = 0,
STANDARD = 1,
}
export enum InstallErrorCode{
SUCCESS = 0,
STATUS_INSTALL_FAILURE = 1,
STATUS_INSTALL_FAILURE_ABORTED = 2,
STATUS_INSTALL_FAILURE_INVALID = 3,
STATUS_INSTALL_FAILURE_CONFLICT = 4,
STATUS_INSTALL_FAILURE_STORAGE = 5,
STATUS_INSTALL_FAILURE_INCOMPATIBLE = 6,
STATUS_UNINSTALL_FAILURE = 7,
STATUS_UNINSTALL_FAILURE_BLOCKED = 8,
STATUS_UNINSTALL_FAILURE_ABORTED = 9,
STATUS_UNINSTALL_FAILURE_CONFLICT = 10,
STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT = 0x0B,
STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED = 0x0C,
STATUS_ABILITY_NOT_FOUND = 0x40,
STATUS_BMS_SERVICE_ERROR = 0x41
}
/**
* Obtains BundleInfo based on a given bundle name.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param bundleName Indicates the bundle name.
* @param callback Specified callback method.
*/
function getBundleInfo(bundleName: string, flags: number, callback: AsyncCallback<BundleInfo>) : void;
/**
* Obtains BundleInfo based on a given bundle name.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param bundleName Indicates the bundle name.
* @return BundleInfo.
*/
function getBundleInfo(bundleName: string, flags: number) : Promise<BundleInfo>;
/**
* Obtains Bundle installer to install or uninstall hap.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @return BundleInstaller.
*/
function getBundleInstaller(callback: AsyncCallback<BundleInstaller>): void;
/**
* Obtains Bundle installer to install or uninstall hap.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @return BundleInstaller.
*/
function getBundleInstaller(): Promise<BundleInstaller>;
/**
* Obtains the ApplicationInfo based on a given application name.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param bundleName Indicates the application name.
* @param callback Specified callback method.
*/
function getApplicationInfo(bundleName: string, flags: number, userId: number, callback: AsyncCallback<ApplicationInfo>) : void;
/**
* Obtains the ApplicationInfo based on a given application name.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param bundleName Indicates the application name.
* @return ApplicationInfo.
*/
function getApplicationInfo(bundleName: string, flags: number, userId: number) : Promise<ApplicationInfo>;
/**
* Query the AbilityInfo by the given Want.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param want Indicates the Want for the ability to be queried.
* @param callback Specified callback method.
*/
function queryAbilityByWant(want: Want, params: QueryParameter, callback: AsyncCallback<Array<AbilityInfo>>): void;
/**
* Query the AbilityInfo by the given Want.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param want Indicates the Want for the ability to be queried.
* @return AbilityInfo.
*/
function queryAbilityByWant(want: Want, params: QueryParameter): Promise<AbilityInfo>;
/**
* Obtains BundleInfo of all bundles available in the system.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param callback Specified callback method.
*/
function getBundleInfos(flags: BundleFlag, callback: AsyncCallback<Array<BundleInfo>>) : void;
/**
* Obtains BundleInfo of all bundles available in the system.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @return Array of BundleInfo.
*/
function getBundleInfos(flags: BundleFlag) : Promise<Array<BundleInfo>>;
/**
* Obtains information about all installed applications.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param callback Specified callback method.
*/
function getApplicationInfos(flags: number, userId: number, callback: AsyncCallback<Array<ApplicationInfo>>) : void;
/**
* Obtains information about all installed applications.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param NA
* @return Array of ApplicationInfo.
*/
function getApplicationInfos(flags: number, userId: number) : Promise<Array<ApplicationInfo>>;
/**
* Obtains information about a bundle contained in a HAP.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param hapFilePath Indicates the path of the HAP.
* @param callback Specified callback method.
*/
function getBundleArchiveInfo(hapFilePath: string, flags: number, callback: AsyncCallback<BundleInfo>) : void;
/**
* Obtains information about a bundle contained in a HAP.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param hapFilePath Indicates the path of the HAP.
* @return BundleInfo.
*/
function getBundleArchiveInfo(hapFilePath: string, flags: number) : Promise<BundleInfo>;
/**
* Obtains detailed information about a specified permission.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param permissionName Indicates the name of the permission.
* @param callback Specified callback method.
*/
function getPermissionDef(permissionName: string, callback: AsyncCallback<permission.PermissionDef>) : void;
/**
* Obtains detailed information about a specified permission.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param permissionName Indicates the name of the permission.
* @return PermissionDef.
*/
function getPermissionDef(permissionName: string) : Promise<permission.PermissionDef>;
}
export default bundle;
+49
View File
@@ -0,0 +1,49 @@
/*
* 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 { Want } from './want';
export interface AbilityResult {
/**
* Indicates result code for startAbilityResult.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap aafwk
*/
resultCode: number;
/**
* Indicates the data returned after the ability is started. You can define the data returned.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap aafwk
*/
want?: Want;
}
export interface StartAbilityResult extends AbilityResult {
/**
* Indicates the Want containing information about the target ability to start.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap aafwk
*/
requestCode: number;
}
+49
View File
@@ -0,0 +1,49 @@
/*
* 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 { Want } from './want';
export interface StartAbilityParameter {
/**
* Indicates the Want containing information about the target ability to start.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap aafwk
*/
want: Want;
/**
* Indicates the special start setting used in starting ability.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap aafwk
*/
abilityStartSetting?: {[key: string]: any};
}
export interface StartAbilityForResultParameter extends StartAbilityParameter {
/**
* Indicates the Want containing information about the target ability to start.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap aafwk
*/
requestCode: number;
}
+155
View File
@@ -0,0 +1,155 @@
/*
* 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.
*/
/**
* @name WantOptions
* @since 3
* @SysCap AAFwk
* @import
* @permission N/A
* @devices phone, tablet
*/
export declare interface WantOptions {
// indicates the grant to perform read operations on the URI
authReadUriPermission: boolean;
// indicates the grant to perform write operations on the URI
authWriteUriPermission: boolean;
// support forward intent result to origin ability
abilityForwardResult: boolean;
// used for marking the ability start-up is triggered by continuation
abilityContinuation: boolean;
// specifies whether a component does not belong to ohos
notOhosComponent: boolean;
// specifies whether an ability is started
abilityFormEnabled: boolean;
// indicates the grant for possible persisting on the URI.
authPersistableUriPermission: boolean;
// indicates the grant for possible persisting on the URI.
authPrefixUriPermission: boolean;
// support distributed scheduling system start up multiple devices
abilitySliceMultiDevice: boolean;
// indicates that an ability using the service template is started regardless of whether the
// host application has been started.
startForegroundAbility: boolean;
// install the specified ability if it's not installed.
installOnDemand: boolean;
// return result to origin ability slice
abilitySliceForwardResult: boolean;
// install the specified ability with background mode if it's not installed.
installWithBackgroundMode: boolean;
}
/**
* Want is the basic communication component of the system.
* @name Want
* @since 3
* @sysCap AAFwk
* @devices phone, tablet
* @permission N/A
*/
export declare interface Want {
/**
* device id
* @default -
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
*/
deviceId?: string;
/**
* bundle name
* @default -
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
*/
bundleName?: string;
/**
* ability name
* @default -
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
*/
abilityName?: string;
/**
* The description of a URI in a Want.
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
* @default -
*/
uri?: string;
/**
* The description of the type in this Want.
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
* @default -
*/
type?: string;
/**
* The options of the flags in this Want.
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
* @default -
*/
options?: WantOptions;
/**
* The description of an action in an want.
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
* @default -
*/
action?: string;
/**
* The description of the WantParams object in an Want
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
* @default -
*/
parameters?: {[key: string]: any};
/**
* The description of a entities in a Want.
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
* @default -
*/
entities?: Array<string>;
}
+97
View File
@@ -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.
*/
import { ElementName } from '../bundle/elementname';
/**
* @name Task stack information corresponding to ability
* @since 3
* @SysCap appexecfwk
* @import import AbilityMissionInfo from '@ohos.AbilityMissionInfo'
* @permission N/A
* @devices phone, tablet
*/
export interface AbilityMissionInfo {
/**
* Unique identification of task stack information corresponding to ability
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
id: number;
/**
* The component launched as the first ability in the task stack
* This can be considered the "application" of this task stack
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
baseAbility: ElementName;
/**
* The ability component at the top of the history stack of the task
* This is what the user is currently doing
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
topAbility: ElementName;
/**
* The corresponding ability description information in the task stack
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
missionDescription: MissionDescriptionInfo;
}
/**
* @name Task stack description information
* @since 3
* @SysCap appexecfwk
* @import import app from '@system.app'
* @permission N/A
* @devices phone, tablet
*/
export interface MissionDescriptionInfo {
/**
* The label of the specified ability in the task stack
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
label: string;
/**
* The path to the icon that specifies the ability in the task stack
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
iconPath: string;
}
+44
View File
@@ -0,0 +1,44 @@
/*
* 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.
*/
/**
* @name This class saves process information about an application
* @since 3
* @SysCap appexecfwk
* @import import app from '@system.app'
* @permission N/A
* @devices phone, tablet
*/
export interface ProcessInfo {
/**
* The id of the current process
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
pid: number;
/**
* The name of the current process
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
processName: string;
}
+95
View File
@@ -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.
*/
import abilityManager from './../@ohos.app.abilitymanager';
/**
* @name This class saves process information about an application
* @since 3
* @SysCap appexecfwk
* @import import app from '@system.app'
* @permission N/A
* @devices phone, tablet
*/
export interface RunningProcessInfo {
/**
* The id of the current process
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
pid: number;
/**
* The name of the current process
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
processName: string;
/**
* The list of packaget in the current process
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
pkgList: Array<string>;
/**
* The uid of the current process
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
uid: number;
/**
* the memory level of the current process
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
lastMemoryLevel: number;
/**
* the weight of the current process
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
weight: number;
/**
* the ReasonCode of weight for the current process
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap appexecfwk
*/
weightReasonCode: abilityManager.WeightReasonCode;
}
+57
View File
@@ -0,0 +1,57 @@
/*
* 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 { ApplicationInfo } from './applicationinfo';
import bundle from './../@ohos.bundle';
/**
* @name AbilityInfo
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export interface AbilityInfo {
readonly bundleName: string;
readonly name: string;
readonly label: string;
readonly description: string;
readonly icon: string;
readonly labelId: number;
readonly descriptionId: number;
readonly iconId: number;
readonly moduleName: string;
readonly process: string;
readonly targetAbility: string;
readonly backgroundModes: number;
readonly isVisible: boolean;
readonly formEnabled: boolean;
readonly type: bundle.AbilityType;
readonly subType: bundle.AbilitySubType;
readonly orientation: bundle.DisplayOrientation;
readonly launchMode: bundle.LaunchMode;
readonly permissions: Array<String>;
readonly deviceTypes: Array<String>;
readonly deviceCapabilities: Array<string>;
readonly readPermission: string;
readonly writePermission: string;
readonly applicationInfo: ApplicationInfo;
readonly formEntity: number;
readonly minFormHeight: number;
readonly defaultFormHeight: number;
readonly minFormWidth: number;
readonly defaultFormWidth: number;
readonly uri: string;
}
+42
View File
@@ -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.
*/
import { ModuleInfo } from './moduleinfo';
/**
* @name ApplicationInfo
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export interface ApplicationInfo {
readonly name: string;
readonly description: string;
readonly descriptionId: number;
readonly systemApp: boolean;
readonly enabled: boolean;
readonly label: string;
readonly labelId: string;
readonly icon: string;
readonly iconId: string;
readonly process: string;
readonly supportedModes: number;
readonly moduleSourceDirs: Array<string>;
readonly permissions: Array<string>;
readonly moduleInfos: Array<ModuleInfo>;
flags: number;
readonly entryDir: string;
}
+77
View File
@@ -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.
*/
import { AbilityInfo } from './abilityinfo';
import { ApplicationInfo } from './applicationinfo';
import { HapModuleInfo } from './hapmoduleinfo';
/**
* @name UsedScene
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export interface UsedScene {
abilities: Array<string>;
when: string;
}
/**
* @name ReqPermissionDetail
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export interface ReqPermissionDetail {
name: string;
reason: string;
usedScene: UsedScene;
}
/**
* @name BundleInfo
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export interface BundleInfo {
readonly name: string;
readonly type: string;
readonly appId: string;
readonly uid: number;
readonly installTime: number;
readonly updateTime: number;
readonly appInfo: ApplicationInfo;
readonly abilityInfos: Array<AbilityInfo>;
readonly reqPermissions: Array<string>;
readonly reqPermissionDetails: Array<ReqPermissionDetail>;
readonly vendor: string;
readonly versionCode: number;
readonly versionName: string;
readonly compatibleVersion: number;
readonly targetVersion: number;
readonly isCompressNativeLibs: boolean;
readonly hapModuleInfos: Array<HapModuleInfo>;
readonly entryModuleName: string;
readonly cpuAbi: string;
readonly isSilentInstallation: string;
readonly minCompatibleVersionCode: number;
readonly entryInstallationFree: boolean;
}
+86
View File
@@ -0,0 +1,86 @@
/*
* 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 { AsyncCallback } from './../.basic';
import bundle from './../@ohos.bundle';
/**
* @name InstallParam
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export interface InstallParam {
userId: number;
installFlag: number;
isKeepData: boolean;
}
/**
* @name InstallStatus
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export interface InstallStatus {
status: bundle.InstallErrorCode;
/**
* The install result string message.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap BMS
*/
statusMessage: string;
}
/**
* @name BundleInstaller
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export interface BundleInstaller {
/**
* Install an application in a HAP.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param bundleFilePaths Indicates the paths of the HAP.
* @param InstallParam Indicates the userId and whether keep data.
* @return InstallStatus
*/
install(bundleFilePaths: Array<string>, param: InstallParam, callback: AsyncCallback<InstallStatus>): void;
/**
* Uninstall an application.
*
* @devices phone, tablet
* @since 3
* @SysCap BMS
* @param bundleName Indicates the bundle name.
* @param InstallParam Indicates the userId and whether keep data.
* @return InstallStatus
*/
uninstall(bundleName: string, param: InstallParam, callback: AsyncCallback<InstallStatus>): void;
}
+71
View File
@@ -0,0 +1,71 @@
/*
* 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.
*/
/**
* Contains basic Ability information, which uniquely identifies an ability.
* You can use this class to obtain values of the fields set in an element,
* such as the device ID, bundle name, and ability name.
* @name ElementName
* @since 3
* @sysCap AAFwk
* @devices phone, tablet
* @permission N/A
*/
export interface ElementName {
/**
* device id
* @default -
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
*/
deviceId?: string;
/**
* bundle name
* @default -
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
*/
bundleName: string;
/**
* ability name
* @default -
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
*/
abilityName: string;
/**
* shortName name
* @default -
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
*/
uri?: string;
/**
* shortName name
* @default -
* @devices phone, tablet
* @since 3
* @sysCap AAFwk
*/
shortName?: string;
}
+41
View File
@@ -0,0 +1,41 @@
/*
* 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 {AbilityInfo} from "./abilityinfo";
/**
* @name HapModuleInfo
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export interface HapModuleInfo {
readonly name: string;
readonly description: string;
readonly descriptionId: number;
readonly icon: string;
readonly label: string;
readonly labelId: number;
readonly iconId: number;
readonly backgroundImg: string;
readonly supportedModes: number;
readonly reqCapabilities: Array<string>;
readonly deviceTypes: Array<string>;
readonly abilityInfos: Array<AbilityInfo>;
readonly moduleName: string;
readonly mainAbilityName: string;
readonly installationFree: boolean;
}
+44
View File
@@ -0,0 +1,44 @@
/*
* 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.
*/
/**
* @name ModuleInfo
* @since 3
* @SysCap BMS
* @import NA
* @permission NA
* @devices phone, tablet
*/
export interface ModuleInfo {
/**
* The module name.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap BMS
*/
readonly moduleName: string;
/**
* The module source path.
*
* @default -
* @devices phone, tablet
* @since 3
* @SysCap BMS
*/
readonly moduleSourceDir: string;
}
+4 -3
View File
@@ -15,8 +15,9 @@ import("//build/ohos.gni")
group("napi_packages") {
deps = [
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/abilityManager:napi_ability_manager",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/context:context",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility:feature_ability",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/abilityManager:abilitymanager",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataUriUtils:datauriutils",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility:featureability",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/wantConstant:wantconstant",
]
}
@@ -13,7 +13,7 @@
import("//build/ohos.gni")
ohos_shared_library("napi_ability_manager") {
ohos_shared_library("abilitymanager") {
include_dirs = [
"//foundation/ace/napi/interfaces/kits",
"//third_party/node/src",
@@ -23,7 +23,7 @@ ohos_shared_library("napi_ability_manager") {
]
sources = [
"ability_manager.cpp",
"napi_ability_manager.cpp",
"native_module.cpp",
]
@@ -50,7 +50,7 @@ ohos_shared_library("napi_ability_manager") {
"ipc:ipc_core",
]
relative_install_dir = "module"
relative_install_dir = "module/app"
subsystem_name = "aafwk"
part_name = "aafwk_standard"
@@ -1,810 +0,0 @@
/*
* 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_manager.h"
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include "hilog_wrapper.h"
#include "ipc_skeleton.h"
#include "system_ability_definition.h"
#include "if_system_ability_manager.h"
#include "iservice_registry.h"
#include "app_mgr_interface.h"
#include "ability_manager_interface.h"
static OHOS::sptr<OHOS::AAFwk::IAbilityManager> GetAbilityManagerInstance()
{
OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
OHOS::sptr<OHOS::IRemoteObject> abilityObject =
systemAbilityManager->GetSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID);
return OHOS::iface_cast<OHOS::AAFwk::IAbilityManager>(abilityObject);
}
static OHOS::sptr<OHOS::AppExecFwk::IAppMgr> GetAppManagerInstance()
{
OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
OHOS::sptr<OHOS::IRemoteObject> appObject = systemAbilityManager->GetSystemAbility(OHOS::APP_MGR_SERVICE_ID);
return OHOS::iface_cast<OHOS::AppExecFwk::IAppMgr>(appObject);
}
static void GetRecentMissionsForResult(
napi_env env, const std::vector<RecentMissionInfo> recentMissionInfos, napi_value result)
{
int32_t index = 0;
std::vector<RecentMissionInfo> entities = recentMissionInfos;
for (const auto &item : entities) {
napi_value objRecentMissionInfo;
NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objRecentMissionInfo));
napi_value id;
NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.id, &id));
HILOG_INFO("id = [%{public}d]", item.id);
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRecentMissionInfo, "id", id));
napi_value runingState;
NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.runingState, &runingState));
HILOG_INFO("runingState = [%{public}d]", item.runingState);
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRecentMissionInfo, "runingState", runingState));
napi_value want;
NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &want));
napi_value uri;
NAPI_CALL_RETURN_VOID(
env, napi_create_string_utf8(env, item.baseWant.GetUriString().c_str(), NAPI_AUTO_LENGTH, &uri));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, want, "uri", uri));
napi_value type;
NAPI_CALL_RETURN_VOID(
env, napi_create_string_utf8(env, item.baseWant.GetType().c_str(), NAPI_AUTO_LENGTH, &type));
HILOG_INFO("type = [%{public}s]", item.baseWant.GetType().c_str());
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, want, "type", type));
napi_value flags;
NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.baseWant.GetFlags(), &flags));
HILOG_INFO("flags = [%{public}d]", item.baseWant.GetFlags());
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, want, "flags", flags));
napi_value action;
NAPI_CALL_RETURN_VOID(
env, napi_create_string_utf8(env, item.baseWant.GetAction().c_str(), NAPI_AUTO_LENGTH, &action));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, want, "action", action));
napi_value nWantEntities;
NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nWantEntities));
if (item.baseWant.GetEntities().size() > 0) {
size_t idx = 0;
std::vector<std::string> wantEntities = item.baseWant.GetEntities();
for (const auto &entity : wantEntities) {
napi_value value;
NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, entity.c_str(), NAPI_AUTO_LENGTH, &value));
NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nWantEntities, idx, value));
idx++;
}
}
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, want, "entities", nWantEntities));
napi_value elementName;
NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &elementName));
napi_value deviceId;
NAPI_CALL_RETURN_VOID(env,
napi_create_string_utf8(
env, item.baseWant.GetElement().GetDeviceID().c_str(), NAPI_AUTO_LENGTH, &deviceId));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, elementName, "deviceId", deviceId));
napi_value bundleName;
NAPI_CALL_RETURN_VOID(env,
napi_create_string_utf8(
env, item.baseWant.GetElement().GetBundleName().c_str(), NAPI_AUTO_LENGTH, &bundleName));
HILOG_INFO("bundleName = [%{public}s]", item.baseWant.GetElement().GetBundleName().c_str());
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, elementName, "bundleName", bundleName));
napi_value abilityName;
NAPI_CALL_RETURN_VOID(env,
napi_create_string_utf8(
env, item.baseWant.GetElement().GetAbilityName().c_str(), NAPI_AUTO_LENGTH, &abilityName));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, elementName, "abilityName", abilityName));
HILOG_INFO("abilityName = [%{public}s]", item.baseWant.GetElement().GetAbilityName().c_str());
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, want, "elementName", elementName));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRecentMissionInfo, "baseWant", want));
napi_value baseAbility;
NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &baseAbility));
napi_value deviceId1;
NAPI_CALL_RETURN_VOID(
env, napi_create_string_utf8(env, item.baseAbility.GetDeviceID().c_str(), NAPI_AUTO_LENGTH, &deviceId1));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, baseAbility, "deviceId", deviceId1));
napi_value bundleName1;
NAPI_CALL_RETURN_VOID(env,
napi_create_string_utf8(env, item.baseAbility.GetBundleName().c_str(), NAPI_AUTO_LENGTH, &bundleName1));
HILOG_INFO("bundleName1 = [%{public}s]", item.baseAbility.GetBundleName().c_str());
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, baseAbility, "bundleName", bundleName1));
napi_value abilityName1;
NAPI_CALL_RETURN_VOID(env,
napi_create_string_utf8(env, item.baseAbility.GetAbilityName().c_str(), NAPI_AUTO_LENGTH, &abilityName1));
HILOG_INFO("abilityName1 = [%{public}s]", item.baseAbility.GetAbilityName().c_str());
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, baseAbility, "abilityName", abilityName1));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRecentMissionInfo, "baseAbility", baseAbility));
napi_value topAbility;
NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &topAbility));
napi_value deviceId2;
NAPI_CALL_RETURN_VOID(
env, napi_create_string_utf8(env, item.topAbility.GetDeviceID().c_str(), NAPI_AUTO_LENGTH, &deviceId2));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, topAbility, "deviceId", deviceId2));
napi_value bundleName2;
NAPI_CALL_RETURN_VOID(
env, napi_create_string_utf8(env, item.topAbility.GetBundleName().c_str(), NAPI_AUTO_LENGTH, &bundleName2));
HILOG_INFO("bundleName2 = [%{public}s]", item.topAbility.GetBundleName().c_str());
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, topAbility, "bundleName", bundleName2));
napi_value abilityName2;
NAPI_CALL_RETURN_VOID(env,
napi_create_string_utf8(env, item.topAbility.GetAbilityName().c_str(), NAPI_AUTO_LENGTH, &abilityName2));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, topAbility, "abilityName", abilityName2));
HILOG_INFO("abilityName2 = [%{public}s]", item.topAbility.GetAbilityName().c_str());
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRecentMissionInfo, "topAbility", topAbility));
napi_value size;
NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.size, &size));
HILOG_INFO("size = [%{public}d]", item.size);
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRecentMissionInfo, "size", size));
napi_value missionDescription;
NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &missionDescription));
napi_value label;
NAPI_CALL_RETURN_VOID(
env, napi_create_string_utf8(env, item.missionDescription.label.c_str(), NAPI_AUTO_LENGTH, &label));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, missionDescription, "label", label));
napi_value iconPath;
NAPI_CALL_RETURN_VOID(
env, napi_create_string_utf8(env, item.missionDescription.iconPath.c_str(), NAPI_AUTO_LENGTH, &iconPath));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, missionDescription, "iconPath", iconPath));
NAPI_CALL_RETURN_VOID(
env, napi_set_named_property(env, objRecentMissionInfo, "missionDescription", missionDescription));
NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, objRecentMissionInfo));
index++;
}
}
static void GetAllRunningProcessesForResult(
napi_env env, const RunningProcessInfo &runningProcessInfo, napi_value result)
{
int32_t index = 0;
for (const auto &item : runningProcessInfo.appProcessInfos) {
napi_value objAppProcessInfo;
NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objAppProcessInfo));
napi_value nPid;
NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.pid_, &nPid));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppProcessInfo, "pid", nPid));
napi_value nProcessName;
NAPI_CALL_RETURN_VOID(
env, napi_create_string_utf8(env, item.processName_.c_str(), NAPI_AUTO_LENGTH, &nProcessName));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppProcessInfo, "processName", nProcessName));
napi_value nstate;
NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast<int32_t>(item.state_), &nstate));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppProcessInfo, "state", nstate));
NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, objAppProcessInfo));
index++;
}
}
napi_value NAPI_QueryRecentAbilityMissionInfos(napi_env env, napi_callback_info info)
{
HILOG_INFO("NAPI_QueryRecentAbilityMissionInfos called...");
size_t argc = 1;
napi_value argv[argc];
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL));
HILOG_INFO("argc = [%{public}d]", argc);
AsyncMissionInfosCallbackInfo *async_callback_info =
new AsyncMissionInfosCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr};
async_callback_info->maxMissionNum = MAX_MISSION_NUM;
async_callback_info->queryType = QUERY_RECENT_MISSION_INFO_TYPE;
if (argc >= 1) {
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype));
NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected.");
napi_create_reference(env, argv[0], 1, &async_callback_info->callback[0]);
napi_value resourceName;
napi_create_string_latin1(env, "NAPI_QueryRecentAbilityMissionInfosCallBack", NAPI_AUTO_LENGTH, &resourceName);
napi_create_async_work(env,
nullptr,
resourceName,
[](napi_env env, void *data) {
HILOG_INFO("queryRecentAbilityMissionInfos called(CallBack Mode)...");
AsyncMissionInfosCallbackInfo *async_callback_info = (AsyncMissionInfosCallbackInfo *)data;
HILOG_INFO("maxMissionNum = [%{public}d]", async_callback_info->maxMissionNum);
HILOG_INFO("queryType = [%{public}d]", async_callback_info->queryType);
GetAbilityManagerInstance()->GetRecentMissions(async_callback_info->maxMissionNum,
async_callback_info->queryType,
async_callback_info->recentMissionInfo);
},
[](napi_env env, napi_status status, void *data) {
HILOG_INFO("queryRecentAbilityMissionInfos compeleted(CallBack Mode)...");
AsyncMissionInfosCallbackInfo *async_callback_info = (AsyncMissionInfosCallbackInfo *)data;
napi_value result;
napi_value callback;
napi_value undefined;
napi_create_array(env, &result);
GetRecentMissionsForResult(env, async_callback_info->recentMissionInfo, result);
napi_get_undefined(env, &undefined);
napi_get_reference_value(env, async_callback_info->callback[0], &callback);
napi_call_function(env, undefined, callback, 1, &result, nullptr);
if (async_callback_info->callback[0] != nullptr) {
napi_delete_reference(env, async_callback_info->callback[0]);
}
napi_delete_async_work(env, async_callback_info->asyncWork);
delete async_callback_info;
},
(void *)async_callback_info,
&async_callback_info->asyncWork);
NAPI_CALL(env, napi_queue_async_work(env, async_callback_info->asyncWork));
return NULL;
} else {
napi_value resourceName;
napi_create_string_latin1(env, "NAPI_QueryRecentAbilityMissionInfosPromise", NAPI_AUTO_LENGTH, &resourceName);
napi_deferred deferred;
napi_value promise;
NAPI_CALL(env, napi_create_promise(env, &deferred, &promise));
async_callback_info->deferred = deferred;
napi_create_async_work(env,
nullptr,
resourceName,
[](napi_env env, void *data) {
HILOG_INFO("queryRecentAbilityMissionInfos called(Promise Mode)...");
AsyncMissionInfosCallbackInfo *async_callback_info = (AsyncMissionInfosCallbackInfo *)data;
HILOG_INFO("maxMissionNum = [%{public}d]", async_callback_info->maxMissionNum);
HILOG_INFO("queryType = [%{public}d]", async_callback_info->queryType);
GetAbilityManagerInstance()->GetRecentMissions(async_callback_info->maxMissionNum,
async_callback_info->queryType,
async_callback_info->recentMissionInfo);
HILOG_INFO("size = [%{public}d]", async_callback_info->recentMissionInfo.size());
},
[](napi_env env, napi_status status, void *data) {
HILOG_INFO("queryRecentAbilityMissionInfos compeleted(Promise Mode)...");
AsyncMissionInfosCallbackInfo *async_callback_info = (AsyncMissionInfosCallbackInfo *)data;
napi_value result;
napi_create_array(env, &result);
GetRecentMissionsForResult(env, async_callback_info->recentMissionInfo, result);
napi_resolve_deferred(async_callback_info->env, async_callback_info->deferred, result);
napi_delete_async_work(env, async_callback_info->asyncWork);
delete async_callback_info;
},
(void *)async_callback_info,
&async_callback_info->asyncWork);
napi_queue_async_work(env, async_callback_info->asyncWork);
return promise;
}
}
napi_value NAPI_QueryRunningAbilityMissionInfos(napi_env env, napi_callback_info info)
{
HILOG_INFO("NAPI_QueryRunningAbilityMissionInfos called...");
size_t argc = 1;
napi_value argv[argc];
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL));
HILOG_INFO("argc = [%{public}d]", argc);
AsyncMissionInfosCallbackInfo *async_callback_info =
new AsyncMissionInfosCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr};
async_callback_info->maxMissionNum = MAX_MISSION_NUM;
async_callback_info->queryType = QUERY_RECENT_RUNNING_MISSION_INFO_TYPE;
if (argc >= 1) {
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype));
NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected.");
napi_create_reference(env, argv[0], 1, &async_callback_info->callback[0]);
napi_value resourceName;
napi_create_string_latin1(env, "NAPI_QueryRunningAbilityMissionInfosCallBack", NAPI_AUTO_LENGTH, &resourceName);
napi_create_async_work(env,
nullptr,
resourceName,
[](napi_env env, void *data) {
HILOG_INFO("queryRunningAbilityMissionInfos called(CallBack Mode)...");
AsyncMissionInfosCallbackInfo *async_callback_info = (AsyncMissionInfosCallbackInfo *)data;
HILOG_INFO("maxMissionNum = [%{public}d]", async_callback_info->maxMissionNum);
HILOG_INFO("queryType = [%{public}d]", async_callback_info->queryType);
GetAbilityManagerInstance()->GetRecentMissions(async_callback_info->maxMissionNum,
async_callback_info->queryType,
async_callback_info->recentMissionInfo);
HILOG_INFO("size = [%{public}d]", async_callback_info->recentMissionInfo.size());
},
[](napi_env env, napi_status status, void *data) {
HILOG_INFO("queryRunningAbilityMissionInfos compeleted(CallBack Mode)...");
AsyncMissionInfosCallbackInfo *async_callback_info = (AsyncMissionInfosCallbackInfo *)data;
napi_value result;
napi_value callback;
napi_value undefined;
napi_create_array(env, &result);
GetRecentMissionsForResult(env, async_callback_info->recentMissionInfo, result);
napi_get_undefined(env, &undefined);
napi_get_reference_value(env, async_callback_info->callback[0], &callback);
napi_call_function(env, undefined, callback, 1, &result, nullptr);
if (async_callback_info->callback[0] != nullptr) {
napi_delete_reference(env, async_callback_info->callback[0]);
}
napi_delete_async_work(env, async_callback_info->asyncWork);
delete async_callback_info;
},
(void *)async_callback_info,
&async_callback_info->asyncWork);
NAPI_CALL(env, napi_queue_async_work(env, async_callback_info->asyncWork));
return NULL;
} else {
napi_value resourceName;
napi_create_string_latin1(env, "NAPI_QueryRunningAbilityMissionInfosPromise", NAPI_AUTO_LENGTH, &resourceName);
napi_deferred deferred;
napi_value promise;
NAPI_CALL(env, napi_create_promise(env, &deferred, &promise));
async_callback_info->deferred = deferred;
napi_create_async_work(env,
nullptr,
resourceName,
[](napi_env env, void *data) {
HILOG_INFO("queryRunningAbilityMissionInfos called(Promise Mode)...");
AsyncMissionInfosCallbackInfo *async_callback_info = (AsyncMissionInfosCallbackInfo *)data;
HILOG_INFO("maxMissionNum = [%{public}d]", async_callback_info->maxMissionNum);
HILOG_INFO("queryType = [%{public}d]", async_callback_info->queryType);
GetAbilityManagerInstance()->GetRecentMissions(async_callback_info->maxMissionNum,
async_callback_info->queryType,
async_callback_info->recentMissionInfo);
HILOG_INFO("size = [%{public}d]", async_callback_info->recentMissionInfo.size());
},
[](napi_env env, napi_status status, void *data) {
HILOG_INFO("queryRunningAbilityMissionInfos compeleted(Promise Mode)...");
AsyncMissionInfosCallbackInfo *async_callback_info = (AsyncMissionInfosCallbackInfo *)data;
napi_value result;
napi_create_array(env, &result);
GetRecentMissionsForResult(env, async_callback_info->recentMissionInfo, result);
napi_resolve_deferred(async_callback_info->env, async_callback_info->deferred, result);
napi_delete_async_work(env, async_callback_info->asyncWork);
delete async_callback_info;
},
(void *)async_callback_info,
&async_callback_info->asyncWork);
napi_queue_async_work(env, async_callback_info->asyncWork);
return promise;
}
}
napi_value NAPI_GetAllRunningProcesses(napi_env env, napi_callback_info info)
{
HILOG_INFO("NAPI_GetAllRunningProcesses called...");
size_t argc = 1;
napi_value argv[argc];
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL));
HILOG_INFO("argc = [%{public}d]", argc);
AsyncCallbackInfo *async_callback_info =
new AsyncCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr};
if (argc >= 1) {
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype));
NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected.");
napi_create_reference(env, argv[0], 1, &async_callback_info->callback[0]);
napi_value resourceName;
napi_create_string_latin1(env, "NAPI_GetAllRunningProcessesCallBack", NAPI_AUTO_LENGTH, &resourceName);
napi_create_async_work(env,
nullptr,
resourceName,
[](napi_env env, void *data) {
HILOG_INFO("getAllRunningProcesses called(CallBack Mode)...");
AsyncCallbackInfo *async_callback_info = (AsyncCallbackInfo *)data;
std::shared_ptr<OHOS::AppExecFwk::RunningProcessInfo> runningProcessInfo =
std::make_shared<OHOS::AppExecFwk::RunningProcessInfo>();
GetAppManagerInstance()->GetAllRunningProcesses(runningProcessInfo);
for (size_t idx = 0; idx < runningProcessInfo->appProcessInfos.size(); idx++) {
OHOS::AppExecFwk::AppProcessInfo appProcessInfoTmp;
appProcessInfoTmp.pid_ = runningProcessInfo->appProcessInfos[idx].pid_;
appProcessInfoTmp.processName_ = runningProcessInfo->appProcessInfos[idx].processName_;
appProcessInfoTmp.state_ = runningProcessInfo->appProcessInfos[idx].state_;
async_callback_info->runningProcessInfo.appProcessInfos.push_back(appProcessInfoTmp);
}
},
[](napi_env env, napi_status status, void *data) {
HILOG_INFO("getAllRunningProcesses compeleted(CallBack Mode)...");
AsyncCallbackInfo *async_callback_info = (AsyncCallbackInfo *)data;
napi_value result;
napi_value callback;
napi_value undefined;
napi_create_array(env, &result);
GetAllRunningProcessesForResult(env, async_callback_info->runningProcessInfo, result);
napi_get_undefined(env, &undefined);
napi_get_reference_value(env, async_callback_info->callback[0], &callback);
napi_call_function(env, undefined, callback, 1, &result, nullptr);
if (async_callback_info->callback[0] != nullptr) {
napi_delete_reference(env, async_callback_info->callback[0]);
}
napi_delete_async_work(env, async_callback_info->asyncWork);
delete async_callback_info;
},
(void *)async_callback_info,
&async_callback_info->asyncWork);
NAPI_CALL(env, napi_queue_async_work(env, async_callback_info->asyncWork));
return NULL;
} else {
napi_value resourceName;
napi_create_string_latin1(env, "NAPI_GetAllRunningProcessesPromise", NAPI_AUTO_LENGTH, &resourceName);
napi_deferred deferred;
napi_value promise;
NAPI_CALL(env, napi_create_promise(env, &deferred, &promise));
async_callback_info->deferred = deferred;
napi_create_async_work(env,
nullptr,
resourceName,
[](napi_env env, void *data) {
HILOG_INFO("getAllRunningProcesses called(Promise Mode)...");
AsyncCallbackInfo *async_callback_info = (AsyncCallbackInfo *)data;
std::shared_ptr<OHOS::AppExecFwk::RunningProcessInfo> runningProcessInfo =
std::make_shared<OHOS::AppExecFwk::RunningProcessInfo>();
GetAppManagerInstance()->GetAllRunningProcesses(runningProcessInfo);
for (size_t idx = 0; idx < runningProcessInfo->appProcessInfos.size(); idx++) {
OHOS::AppExecFwk::AppProcessInfo appProcessInfoTmp;
appProcessInfoTmp.pid_ = runningProcessInfo->appProcessInfos[idx].pid_;
appProcessInfoTmp.processName_ = runningProcessInfo->appProcessInfos[idx].processName_;
appProcessInfoTmp.state_ = runningProcessInfo->appProcessInfos[idx].state_;
async_callback_info->runningProcessInfo.appProcessInfos.push_back(appProcessInfoTmp);
}
},
[](napi_env env, napi_status status, void *data) {
HILOG_INFO("getAllRunningProcesses compeleted(Promise Mode)...");
AsyncCallbackInfo *async_callback_info = (AsyncCallbackInfo *)data;
napi_value result;
napi_create_array(env, &result);
GetAllRunningProcessesForResult(env, async_callback_info->runningProcessInfo, result);
napi_resolve_deferred(async_callback_info->env, async_callback_info->deferred, result);
napi_delete_async_work(env, async_callback_info->asyncWork);
delete async_callback_info;
},
(void *)async_callback_info,
&async_callback_info->asyncWork);
napi_queue_async_work(env, async_callback_info->asyncWork);
return promise;
}
}
napi_value NAPI_RemoveMission(napi_env env, napi_callback_info info)
{
HILOG_INFO("NAPI_RemoveMission called...");
size_t argc = 2;
napi_value argv[argc];
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL));
HILOG_INFO("argc = [%{public}d]", argc);
AsyncRemoveMissionCallbackInfo *async_callback_info =
new AsyncRemoveMissionCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr};
napi_valuetype valuetype0;
NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype0));
NAPI_ASSERT(env, valuetype0 == napi_number, "Wrong argument type. Numbers expected.");
int32_t value0;
NAPI_CALL(env, napi_get_value_int32(env, argv[0], &value0));
async_callback_info->index = value0;
if (argc >= 2) {
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype));
NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected.");
napi_create_reference(env, argv[1], 1, &async_callback_info->callback[0]);
napi_value resourceName;
napi_create_string_latin1(env, "NAPI_RemoveMissionCallBack", NAPI_AUTO_LENGTH, &resourceName);
napi_create_async_work(env,
nullptr,
resourceName,
[](napi_env env, void *data) {
HILOG_INFO("removeMission called(CallBack Mode)...");
AsyncRemoveMissionCallbackInfo *async_callback_info = (AsyncRemoveMissionCallbackInfo *)data;
async_callback_info->result = GetAbilityManagerInstance()->RemoveMission(async_callback_info->index);
},
[](napi_env env, napi_status status, void *data) {
HILOG_INFO("removeMission compeleted(CallBack Mode)...");
AsyncRemoveMissionCallbackInfo *async_callback_info = (AsyncRemoveMissionCallbackInfo *)data;
napi_value result;
napi_value callback;
napi_value undefined;
napi_create_int32(async_callback_info->env, async_callback_info->result, &result);
napi_get_undefined(env, &undefined);
napi_get_reference_value(env, async_callback_info->callback[0], &callback);
napi_call_function(env, undefined, callback, 1, &result, nullptr);
if (async_callback_info->callback[0] != nullptr) {
napi_delete_reference(env, async_callback_info->callback[0]);
}
napi_delete_async_work(env, async_callback_info->asyncWork);
delete async_callback_info;
},
(void *)async_callback_info,
&async_callback_info->asyncWork);
NAPI_CALL(env, napi_queue_async_work(env, async_callback_info->asyncWork));
return NULL;
} else {
napi_value resourceName;
napi_create_string_latin1(env, "NAPI_RemoveMissionPromise", NAPI_AUTO_LENGTH, &resourceName);
napi_deferred deferred;
napi_value promise;
NAPI_CALL(env, napi_create_promise(env, &deferred, &promise));
async_callback_info->deferred = deferred;
napi_create_async_work(env,
nullptr,
resourceName,
[](napi_env env, void *data) {
HILOG_INFO("removeMission called(Promise Mode)...");
AsyncRemoveMissionCallbackInfo *async_callback_info = (AsyncRemoveMissionCallbackInfo *)data;
async_callback_info->result = GetAbilityManagerInstance()->RemoveMission(async_callback_info->index);
},
[](napi_env env, napi_status status, void *data) {
HILOG_INFO("removeMission compeleted(Promise Mode)...");
AsyncRemoveMissionCallbackInfo *async_callback_info = (AsyncRemoveMissionCallbackInfo *)data;
napi_value result;
napi_create_int32(async_callback_info->env, async_callback_info->result, &result);
napi_resolve_deferred(async_callback_info->env, async_callback_info->deferred, result);
napi_delete_async_work(env, async_callback_info->asyncWork);
delete async_callback_info;
},
(void *)async_callback_info,
&async_callback_info->asyncWork);
napi_queue_async_work(env, async_callback_info->asyncWork);
return promise;
}
}
napi_value NAPI_RemoveStack(napi_env env, napi_callback_info info)
{
HILOG_INFO("NAPI_RemoveStack called...");
size_t argc = 2;
napi_value argv[argc];
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL));
HILOG_INFO("argc = [%{public}d]", argc);
AsyncRemoveStackCallbackInfo *async_callback_info =
new AsyncRemoveStackCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr};
napi_valuetype valuetype0;
NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype0));
NAPI_ASSERT(env, valuetype0 == napi_number, "Wrong argument type. Numbers expected.");
int32_t value0;
NAPI_CALL(env, napi_get_value_int32(env, argv[0], &value0));
async_callback_info->index = value0;
if (argc >= 2) {
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype));
NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected.");
napi_create_reference(env, argv[1], 1, &async_callback_info->callback[0]);
napi_value resourceName;
napi_create_string_latin1(env, "NAPI_RemoveStackCallBack", NAPI_AUTO_LENGTH, &resourceName);
napi_create_async_work(env,
nullptr,
resourceName,
[](napi_env env, void *data) {
HILOG_INFO("removeStack called(CallBack Mode)...");
AsyncRemoveStackCallbackInfo *async_callback_info = (AsyncRemoveStackCallbackInfo *)data;
async_callback_info->result = GetAbilityManagerInstance()->RemoveStack(async_callback_info->index);
},
[](napi_env env, napi_status status, void *data) {
HILOG_INFO("removeStack compeleted(CallBack Mode)...");
AsyncRemoveStackCallbackInfo *async_callback_info = (AsyncRemoveStackCallbackInfo *)data;
napi_value result;
napi_value callback;
napi_value undefined;
napi_create_int32(async_callback_info->env, async_callback_info->result, &result);
napi_get_undefined(env, &undefined);
napi_get_reference_value(env, async_callback_info->callback[0], &callback);
napi_call_function(env, undefined, callback, 1, &result, nullptr);
if (async_callback_info->callback[0] != nullptr) {
napi_delete_reference(env, async_callback_info->callback[0]);
}
napi_delete_async_work(env, async_callback_info->asyncWork);
delete async_callback_info;
},
(void *)async_callback_info,
&async_callback_info->asyncWork);
NAPI_CALL(env, napi_queue_async_work(env, async_callback_info->asyncWork));
return NULL;
} else {
napi_value resourceName;
napi_create_string_latin1(env, "NAPI_RemoveStackPromise", NAPI_AUTO_LENGTH, &resourceName);
napi_deferred deferred;
napi_value promise;
NAPI_CALL(env, napi_create_promise(env, &deferred, &promise));
async_callback_info->deferred = deferred;
napi_create_async_work(env,
nullptr,
resourceName,
[](napi_env env, void *data) {
HILOG_INFO("removeStack called(Promise Mode)...");
AsyncRemoveStackCallbackInfo *async_callback_info = (AsyncRemoveStackCallbackInfo *)data;
async_callback_info->result = GetAbilityManagerInstance()->RemoveStack(async_callback_info->index);
},
[](napi_env env, napi_status status, void *data) {
HILOG_INFO("removeStack compeleted(Promise Mode)...");
AsyncRemoveStackCallbackInfo *async_callback_info = (AsyncRemoveStackCallbackInfo *)data;
napi_value result;
napi_create_int32(async_callback_info->env, async_callback_info->result, &result);
napi_resolve_deferred(async_callback_info->env, async_callback_info->deferred, result);
napi_delete_async_work(env, async_callback_info->asyncWork);
delete async_callback_info;
},
(void *)async_callback_info,
&async_callback_info->asyncWork);
napi_queue_async_work(env, async_callback_info->asyncWork);
return promise;
}
}
napi_value NAPI_MoveMissionToTop(napi_env env, napi_callback_info info)
{
HILOG_INFO("NAPI_MoveMissionToTop called...");
size_t argc = 2;
napi_value argv[argc];
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL));
HILOG_INFO("argc = [%{public}d]", argc);
AsyncMoveMissionToTopCallbackInfo *async_callback_info =
new AsyncMoveMissionToTopCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr};
napi_valuetype valuetype0;
NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype0));
NAPI_ASSERT(env, valuetype0 == napi_number, "Wrong argument type. Numbers expected.");
int32_t value0;
NAPI_CALL(env, napi_get_value_int32(env, argv[0], &value0));
async_callback_info->index = value0;
if (argc >= 2) {
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype));
NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected.");
napi_create_reference(env, argv[1], 1, &async_callback_info->callback[0]);
napi_value resourceName;
napi_create_string_latin1(env, "NAPI_MoveMissionToTopCallBack", NAPI_AUTO_LENGTH, &resourceName);
napi_create_async_work(env,
nullptr,
resourceName,
[](napi_env env, void *data) {
HILOG_INFO("moveMissionToTop called(CallBack Mode)...");
AsyncMoveMissionToTopCallbackInfo *async_callback_info = (AsyncMoveMissionToTopCallbackInfo *)data;
async_callback_info->result = GetAbilityManagerInstance()->MoveMissionToTop(async_callback_info->index);
},
[](napi_env env, napi_status status, void *data) {
HILOG_INFO("moveMissionToTop compeleted(CallBack Mode)...");
AsyncMoveMissionToTopCallbackInfo *async_callback_info = (AsyncMoveMissionToTopCallbackInfo *)data;
napi_value result;
napi_value callback;
napi_value undefined;
napi_create_int32(async_callback_info->env, async_callback_info->result, &result);
napi_get_undefined(env, &undefined);
napi_get_reference_value(env, async_callback_info->callback[0], &callback);
napi_call_function(env, undefined, callback, 1, &result, nullptr);
if (async_callback_info->callback[0] != nullptr) {
napi_delete_reference(env, async_callback_info->callback[0]);
}
napi_delete_async_work(env, async_callback_info->asyncWork);
delete async_callback_info;
},
(void *)async_callback_info,
&async_callback_info->asyncWork);
NAPI_CALL(env, napi_queue_async_work(env, async_callback_info->asyncWork));
return NULL;
} else {
napi_value resourceName;
napi_create_string_latin1(env, "NAPI_MoveMissionToTopPromise", NAPI_AUTO_LENGTH, &resourceName);
napi_deferred deferred;
napi_value promise;
NAPI_CALL(env, napi_create_promise(env, &deferred, &promise));
async_callback_info->deferred = deferred;
napi_create_async_work(env,
nullptr,
resourceName,
[](napi_env env, void *data) {
HILOG_INFO("moveMissionToTop called(Promise Mode)...");
AsyncMoveMissionToTopCallbackInfo *async_callback_info = (AsyncMoveMissionToTopCallbackInfo *)data;
async_callback_info->result = GetAbilityManagerInstance()->MoveMissionToTop(async_callback_info->index);
},
[](napi_env env, napi_status status, void *data) {
HILOG_INFO("moveMissionToTop compeleted(Promise Mode)...");
AsyncMoveMissionToTopCallbackInfo *async_callback_info = (AsyncMoveMissionToTopCallbackInfo *)data;
napi_value result;
napi_create_int32(async_callback_info->env, async_callback_info->result, &result);
napi_resolve_deferred(async_callback_info->env, async_callback_info->deferred, result);
napi_delete_async_work(env, async_callback_info->asyncWork);
delete async_callback_info;
},
(void *)async_callback_info,
&async_callback_info->asyncWork);
napi_queue_async_work(env, async_callback_info->asyncWork);
return promise;
}
}
File diff suppressed because it is too large Load Diff
@@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef ABILITY_MANAGER_H
#define ABILITY_MANAGER_H
#ifndef NAPI_ABILITY_MANAGER_H
#define NAPI_ABILITY_MANAGER_H
#include <vector>
@@ -22,23 +22,30 @@
#include "napi/native_node_api.h"
#include "running_process_info.h"
#include "app_process_info.h"
#include "recent_mission_info.h"
#include "ability_mission_info.h"
using RunningProcessInfo = OHOS::AppExecFwk::RunningProcessInfo;
using AppProcessInfo = OHOS::AppExecFwk::AppProcessInfo;
using RecentMissionInfo = OHOS::AAFwk::RecentMissionInfo;
using AbilityMissionInfo = OHOS::AAFwk::AbilityMissionInfo;
#define BUFFER_LENGTH_MAX (128)
#define DEFAULT_STACK_ID (1)
#define DEFAULT_LAST_MEMORY_LEVEL (-1)
#define DEFAULT_WEIGHT (-1)
#define MAX_MISSION_NUM (65535)
#define QUERY_RECENT_MISSION_INFO_TYPE (1)
#define QUERY_RECENT_RUNNING_MISSION_INFO_TYPE (2)
#define BUSINESS_ERROR_CODE_OK 0
namespace OHOS {
namespace AppExecFwk {
struct AsyncCallbackInfo {
napi_env env;
napi_async_work asyncWork;
napi_deferred deferred;
napi_ref callback[2] = {0};
RunningProcessInfo runningProcessInfo;
std::vector<RunningProcessInfo> info;
};
struct AsyncMissionInfosCallbackInfo {
@@ -48,7 +55,7 @@ struct AsyncMissionInfosCallbackInfo {
napi_ref callback[2] = {0};
int32_t maxMissionNum = 0;
int32_t queryType = 0;
std::vector<RecentMissionInfo> recentMissionInfo;
std::vector<AbilityMissionInfo> recentMissionInfo;
};
struct AsyncRemoveMissionCallbackInfo {
@@ -60,12 +67,20 @@ struct AsyncRemoveMissionCallbackInfo {
int32_t result = -1;
};
struct AsyncRemoveStackCallbackInfo {
struct AsyncRemoveMissionsCallbackInfo {
napi_env env;
napi_async_work asyncWork;
napi_deferred deferred;
napi_ref callback[2] = {0};
std::vector<std::int32_t> missionIds;
int32_t result = -1;
};
struct AsyncClearMissionsCallbackInfo {
napi_env env;
napi_async_work asyncWork;
napi_deferred deferred;
napi_ref callback[2] = {0};
int32_t index = -1;
int32_t result = -1;
};
@@ -78,11 +93,36 @@ struct AsyncMoveMissionToTopCallbackInfo {
int32_t result = -1;
};
struct AsyncKillProcessCallbackInfo {
napi_env env;
napi_async_work asyncWork;
napi_deferred deferred;
napi_ref callback[2] = {0};
std::string bundleName;
int32_t result;
};
struct AsyncClearUpApplicationDataCallbackInfo {
napi_env env;
napi_async_work asyncWork;
napi_deferred deferred;
napi_ref callback[2] = {0};
std::string bundleName;
int32_t result;
};
napi_value NAPI_GetAllRunningProcesses(napi_env env, napi_callback_info info);
napi_value NAPI_QueryRunningAbilityMissionInfos(napi_env env, napi_callback_info info);
napi_value NAPI_QueryRecentAbilityMissionInfos(napi_env env, napi_callback_info info);
napi_value NAPI_RemoveMission(napi_env env, napi_callback_info info);
napi_value NAPI_RemoveStack(napi_env env, napi_callback_info info);
napi_value NAPI_RemoveMissions(napi_env env, napi_callback_info info);
napi_value NAPI_ClearMissions(napi_env env, napi_callback_info info);
napi_value NAPI_MoveMissionToTop(napi_env env, napi_callback_info info);
napi_value NAPI_KillProcessesByBundleName(napi_env env, napi_callback_info info);
napi_value NAPI_ClearUpApplicationData(napi_env env, napi_callback_info info);
void CreateWeightReasonCodeObject(napi_env env, napi_value value);
napi_value GetCallbackErrorValue(napi_env env, int errCode);
#endif // ABILITY_MANAGER_H
} // namespace AppExecFwk
} // namespace OHOS
#endif // NAPI_ABILITY_MANAGER_H
@@ -18,12 +18,15 @@
#include <string.h>
#include <unistd.h>
#include "ability_manager.h"
#include "napi_ability_manager.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "hilog_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
EXTERN_C_START
/*
* function for module exports
@@ -31,12 +34,21 @@ EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
HILOG_INFO("napi_moudule Init start...");
napi_value nWeightReasonCode = nullptr;
NAPI_CALL(env, napi_create_object(env, &nWeightReasonCode));
CreateWeightReasonCodeObject(env, nWeightReasonCode);
napi_property_descriptor desc[] = {DECLARE_NAPI_FUNCTION("getAllRunningProcesses", NAPI_GetAllRunningProcesses),
DECLARE_NAPI_FUNCTION("queryRunningAbilityMissionInfos", NAPI_QueryRunningAbilityMissionInfos),
DECLARE_NAPI_FUNCTION("queryRecentAbilityMissionInfos", NAPI_QueryRecentAbilityMissionInfos),
DECLARE_NAPI_FUNCTION("removeMission", NAPI_RemoveMission),
DECLARE_NAPI_FUNCTION("removeStack", NAPI_RemoveStack),
DECLARE_NAPI_FUNCTION("moveMissionToTop", NAPI_MoveMissionToTop)};
DECLARE_NAPI_FUNCTION("removeMissions", NAPI_RemoveMissions),
DECLARE_NAPI_FUNCTION("clearMissions", NAPI_ClearMissions),
DECLARE_NAPI_FUNCTION("moveMissionToTop", NAPI_MoveMissionToTop),
DECLARE_NAPI_FUNCTION("killProcessesByBundleName", NAPI_KillProcessesByBundleName),
DECLARE_NAPI_FUNCTION("clearUpApplicationData", NAPI_ClearUpApplicationData),
DECLARE_NAPI_PROPERTY("WeightReasonCode", nWeightReasonCode)};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
HILOG_INFO("napi_moudule Init end...");
@@ -51,13 +63,17 @@ static napi_module _module = {.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "napi_ability_manager",
.nm_modname = "app.abilitymanager",
.nm_priv = ((void *)0),
.reserved = {0}};
/*
* Module register function
*/
extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&_module);
}
}
} // namespace AppExecFwk
} // namespace OHOS
+2 -2
View File
@@ -11,8 +11,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# import("//build/config/ohos/rules.gni")
import("//build/ohos.gni")
ohos_shared_library("context") {
include_dirs = [
"//foundation/ace/napi/interfaces/kits",
@@ -40,8 +40,8 @@ ohos_shared_library("context") {
"appexecfwk_standard:appexecfwk_base",
"appexecfwk_standard:appexecfwk_core",
"appexecfwk_standard:libeventhandler",
"communication_L2:ipc_core",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
relative_install_dir = "module"
@@ -0,0 +1,53 @@
# 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/config/ohos/rules.gni")
import("//build/ohos.gni")
ohos_shared_library("datauriutils") {
include_dirs = [
"//foundation/ace/napi/interfaces/kits",
"//foundation/aafwk/standard/frameworks/kits/ability/native/include",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataUriUtils",
"//foundation/aafwk/standard/interfaces/kits/napi/aafwk/featureAbility",
"//third_party/node/src",
]
sources = [
"napi_data_uri_utils.cpp",
"native_module.cpp",
]
deps = [
"//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native",
"//foundation/aafwk/standard/interfaces/innerkits/base:base",
"//foundation/ace/napi:ace_napi",
"//foundation/appexecfwk/standard/kits:appkit_native",
"//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri",
"//utils/native/base:utils",
]
external_deps = [
"aafwk_standard:ability_manager",
"aafwk_standard:want",
"appexecfwk_standard:appexecfwk_base",
"appexecfwk_standard:appexecfwk_core",
"appexecfwk_standard:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
relative_install_dir = "module/dataUriUtils"
subsystem_name = "aafwk"
part_name = "aafwk_standard"
}
@@ -0,0 +1,183 @@
/*
* 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 "napi_data_uri_utils.h"
#include "data_uri_utils.h"
#include "feature_ability_common.h"
#include "uri.h"
#include <cstring>
#include <vector>
#include "securec.h"
#include "hilog_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
/**
* @brief DataUriUtilsInit NAPI module registration.
*
* @param env The environment that the Node-API call is invoked under.
* @param exports An empty object via the exports parameter as a convenience.
*
* @return The return value from Init is treated as the exports object for the module.
*/
napi_value DataUriUtilsInit(napi_env env, napi_value exports)
{
HILOG_INFO("%{public}s,called", __func__);
napi_property_descriptor properties[] = {
DECLARE_NAPI_FUNCTION("getIdSync", NAPI_GetIdSync),
DECLARE_NAPI_FUNCTION("attachIdSync", NAPI_AttachIdSync),
DECLARE_NAPI_FUNCTION("deleteIdSync", NAPI_DeleteIdSync),
DECLARE_NAPI_FUNCTION("updateIdSync", NAPI_UpdateIdSync),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties));
return exports;
}
/**
* @brief DataUriUtils NAPI method : getIdSync.
*
* @param env The environment that the Node-API call is invoked under.
* @param info The callback info passed into the callback function.
*
* @return The return value from NAPI C++ to JS for the module.
*/
napi_value NAPI_GetIdSync(napi_env env, napi_callback_info info)
{
size_t requireArgc = 1;
size_t argc = 1;
napi_value args[1] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
if (argc > requireArgc) {
HILOG_ERROR("%{public}s, Wrong argument count.", __func__);
return nullptr;
}
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, args[0], &valuetype));
NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. Numbers expected.");
Uri uri(NapiValueToStringUtf8(env, args[0]));
napi_value id = nullptr;
NAPI_CALL(env, napi_create_int64(env, DataUriUtils::GetId(uri), &id));
return id;
}
/**
* @brief DataUriUtils NAPI method : attachIdSync.
*
* @param env The environment that the Node-API call is invoked under.
* @param info The callback info passed into the callback function.
*
* @return The return value from NAPI C++ to JS for the module.
*/
napi_value NAPI_AttachIdSync(napi_env env, napi_callback_info info)
{
size_t requireArgc = 2;
size_t argc = 2;
napi_value args[2] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
if (argc > requireArgc) {
HILOG_ERROR("%{public}s, Wrong argument count.", __func__);
return nullptr;
}
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, args[0], &valuetype));
NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. Numbers expected.");
Uri uri(NapiValueToStringUtf8(env, args[0]));
int64_t id;
NAPI_CALL(env, napi_get_value_int64(env, args[1], &id));
napi_value uriAttached = nullptr;
NAPI_CALL(env,
napi_create_string_utf8(
env, DataUriUtils::AttachId(uri, id).ToString().c_str(), NAPI_AUTO_LENGTH, &uriAttached));
return uriAttached;
}
/**
* @brief DataUriUtils NAPI method : deleteIdSync.
*
* @param env The environment that the Node-API call is invoked under.
* @param info The callback info passed into the callback function.
*
* @return The return value from NAPI C++ to JS for the module.
*/
napi_value NAPI_DeleteIdSync(napi_env env, napi_callback_info info)
{
size_t requireArgc = 1;
size_t argc = 1;
napi_value args[1] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
if (argc > requireArgc) {
HILOG_ERROR("%{public}s, Wrong argument count.", __func__);
return nullptr;
}
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, args[0], &valuetype));
NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. Numbers expected.");
Uri uri(NapiValueToStringUtf8(env, args[0]));
napi_value uriDeleted = nullptr;
NAPI_CALL(env,
napi_create_string_utf8(env, DataUriUtils::DeleteId(uri).ToString().c_str(), NAPI_AUTO_LENGTH, &uriDeleted));
return uriDeleted;
}
/**
* @brief DataUriUtils NAPI method : updateIdSync.
*
* @param env The environment that the Node-API call is invoked under.
* @param info The callback info passed into the callback function.
*
* @return The return value from NAPI C++ to JS for the module.
*/
napi_value NAPI_UpdateIdSync(napi_env env, napi_callback_info info)
{
size_t requireArgc = 2;
size_t argc = 2;
napi_value args[2] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
if (argc > requireArgc) {
HILOG_ERROR("%{public}s, Wrong argument count.", __func__);
return nullptr;
}
napi_valuetype valuetype;
NAPI_CALL(env, napi_typeof(env, args[0], &valuetype));
NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. Numbers expected.");
Uri uri(NapiValueToStringUtf8(env, args[0]));
int64_t id;
NAPI_CALL(env, napi_get_value_int64(env, args[1], &id));
napi_value uriUpdated = nullptr;
NAPI_CALL(env,
napi_create_string_utf8(
env, DataUriUtils::UpdateId(uri, id).ToString().c_str(), NAPI_AUTO_LENGTH, &uriUpdated));
return uriUpdated;
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,74 @@
/*
* 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_APPEXECFWK_NAPI_DATA_URI_UTILS_H
#define OHOS_APPEXECFWK_NAPI_DATA_URI_UTILS_H
#include "napi/native_common.h"
#include "napi/native_node_api.h"
namespace OHOS {
namespace AppExecFwk {
/**
* @brief DataUriUtilsInit NAPI module registration.
*
* @param env The environment that the Node-API call is invoked under.
* @param exports An empty object via the exports parameter as a convenience.
*
* @return The return value from Init is treated as the exports object for the module.
*/
napi_value DataUriUtilsInit(napi_env env, napi_value exports);
/**
* @brief DataUriUtils NAPI method : getIdSync.
*
* @param env The environment that the Node-API call is invoked under.
* @param info The callback info passed into the callback function.
*
* @return The return value from NAPI C++ to JS for the module.
*/
napi_value NAPI_GetIdSync(napi_env env, napi_callback_info info);
/**
* @brief DataUriUtils NAPI method : attachIdSync.
*
* @param env The environment that the Node-API call is invoked under.
* @param info The callback info passed into the callback function.
*
* @return The return value from NAPI C++ to JS for the module.
*/
napi_value NAPI_AttachIdSync(napi_env env, napi_callback_info info);
/**
* @brief DataUriUtils NAPI method : deleteIdSync.
*
* @param env The environment that the Node-API call is invoked under.
* @param info The callback info passed into the callback function.
*
* @return The return value from NAPI C++ to JS for the module.
*/
napi_value NAPI_DeleteIdSync(napi_env env, napi_callback_info info);
/**
* @brief DataUriUtils NAPI method : updateIdSync.
*
* @param env The environment that the Node-API call is invoked under.
* @param info The callback info passed into the callback function.
*
* @return The return value from NAPI C++ to JS for the module.
*/
napi_value NAPI_UpdateIdSync(napi_env env, napi_callback_info info);
} // namespace AppExecFwk
} // namespace OHOS
#endif /* OHOS_APPEXECFWK_NAPI_DATA_URI_UTILS */

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