From 3cf0f124eeebbe5a2602e5cc3b531dabe5f843b1 Mon Sep 17 00:00:00 2001 From: yangxuguang-huawei Date: Thu, 17 Oct 2024 09:48:02 +0800 Subject: [PATCH] feat: keep alive for 3rd-party apps Signed-off-by: yangxuguang-huawei --- .../app/js_app_manager/js_app_manager.cpp | 152 ++++++++++++++- .../js_app_manager/js_app_manager_utils.cpp | 67 +++++++ .../app/js_app_manager/js_app_manager_utils.h | 5 + .../ability_business_error.cpp | 9 + interfaces/inner_api/ability_manager/BUILD.gn | 1 + .../include/ability_manager_errors.h | 15 ++ .../include/ability_manager_interface.h | 50 +++++ .../ability_manager_ipc_interface_code.h | 12 ++ .../ability_manager/include/keep_alive_info.h | 4 +- .../ability_manager/include/process_options.h | 1 + .../include/appmgr/ams_mgr_interface.h | 9 + .../include/appmgr/ams_mgr_proxy.h | 8 + .../app_manager/include/appmgr/ams_mgr_stub.h | 1 + .../include/appmgr/app_mgr_client.h | 19 ++ .../include/appmgr/app_state_callback_host.h | 11 +- .../include/appmgr/app_state_callback_proxy.h | 6 + .../include/appmgr/iapp_state_callback.h | 9 +- .../app_manager/src/appmgr/ams_mgr_proxy.cpp | 25 +++ .../app_manager/src/appmgr/ams_mgr_stub.cpp | 12 ++ .../app_manager/src/appmgr/app_mgr_client.cpp | 18 ++ .../src/appmgr/app_state_callback_host.cpp | 27 +++ .../src/appmgr/app_state_callback_proxy.cpp | 29 +++ .../ability_business_error.h | 9 + services/abilitymgr/BUILD.gn | 1 + services/abilitymgr/abilitymgr.gni | 6 + .../ability_auto_startup_data_manager.h | 3 - .../include/ability_manager_proxy.h | 38 ++++ .../include/ability_manager_service.h | 45 +++++ .../abilitymgr/include/ability_manager_stub.h | 6 + services/abilitymgr/include/app_scheduler.h | 8 + .../ability_keep_alive_data_manager.h | 4 +- .../keep_alive/ability_keep_alive_service.h | 45 ++--- .../keep_alive/keep_alive_process_manager.h | 20 +- .../resident_process_manager.h | 7 +- .../scene_board/status_bar_delegate_manager.h | 1 + .../ui_ability_lifecycle_manager.h | 3 + .../include/utils/keep_alive_utils.h | 61 ++++++ .../include/utils/main_element_utils.h | 36 +++- services/abilitymgr/libabilityms.map | 5 + .../src/ability_auto_startup_data_manager.cpp | 37 +--- .../abilitymgr/src/ability_manager_proxy.cpp | 142 ++++++++++++++ .../src/ability_manager_service.cpp | 166 +++++++++++++---- .../abilitymgr/src/ability_manager_stub.cpp | 88 ++++++++- services/abilitymgr/src/ability_record.cpp | 34 ++-- services/abilitymgr/src/app_scheduler.cpp | 7 + .../ability_keep_alive_data_manager.cpp | 29 +-- .../keep_alive/ability_keep_alive_service.cpp | 158 +++------------- .../keep_alive/keep_alive_process_manager.cpp | 174 ++++++++++-------- services/abilitymgr/src/process_options.cpp | 5 + .../resident_process_manager.cpp | 102 +++++----- .../status_bar_delegate_manager.cpp | 15 ++ .../ui_ability_lifecycle_manager.cpp | 15 +- .../abilitymgr/src/utils/keep_alive_utils.cpp | 59 ++++++ .../src/utils/main_element_utils.cpp | 71 +++++-- services/appmgr/include/ams_mgr_scheduler.h | 8 + .../appmgr/include/app_mgr_service_inner.h | 18 ++ services/appmgr/include/app_running_record.h | 14 ++ services/appmgr/src/ams_mgr_scheduler.cpp | 9 + services/appmgr/src/app_mgr_service_inner.cpp | 111 +++++++++++ services/appmgr/src/app_running_record.cpp | 10 + services/common/include/hilog_tag_wrapper.h | 3 +- services/common/include/json_utils.h | 45 +++++ .../common/include/permission_constants.h | 2 + services/common/src/json_utils.cpp | 23 +++ .../abilityautostartupdatamanager_fuzzer.cpp | 2 - .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../abilityautostartupdatamanagerb_fuzzer.cpp | 8 - .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../include/appmgr/app_state_callback_host.h | 7 + .../src/appmgr/app_state_callback_host.cpp | 11 ++ .../src/appmgr/app_state_callback_proxy.cpp | 3 + .../src/appmgr/mock_app_scheduler.cpp | 5 + .../include/mock_iapp_state_callback.h | 1 + .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../ability_manager_service_first_test.cpp | 13 ++ .../BUILD.gn | 1 + .../BUILD.gn | 1 + .../ams_app_state_callback_test.cpp | 16 ++ .../app_scheduler_test/app_scheduler_test.cpp | 16 ++ .../app_state_call_back_mock.h | 1 + .../extension_permissions_util_test/BUILD.gn | 2 - .../BUILD.gn | 4 - .../main_element_utils_test.cpp | 36 ++-- test/unittest/multi_app_utils_test/BUILD.gn | 2 - test/unittest/want_utils_test/BUILD.gn | 2 - .../window_options_utils_test/BUILD.gn | 5 +- utils/server/startup/include/param.h | 1 + utils/server/startup/src/param.cpp | 4 + 92 files changed, 1810 insertions(+), 471 deletions(-) create mode 100644 services/abilitymgr/include/utils/keep_alive_utils.h create mode 100644 services/abilitymgr/src/utils/keep_alive_utils.cpp diff --git a/frameworks/js/napi/app/js_app_manager/js_app_manager.cpp b/frameworks/js/napi/app/js_app_manager/js_app_manager.cpp index 3f6ac64edf..b15a5ef79c 100644 --- a/frameworks/js/napi/app/js_app_manager/js_app_manager.cpp +++ b/frameworks/js/napi/app/js_app_manager/js_app_manager.cpp @@ -184,6 +184,16 @@ public: { GET_CB_INFO_AND_CALL(env, info, JsAppManager, OnGetSupportedProcessCachePids); } + + static napi_value SetKeepAliveForBundle(napi_env env, napi_callback_info info) + { + GET_CB_INFO_AND_CALL(env, info, JsAppManager, OnSetKeepAliveForBundle); + } + + static napi_value GetKeepAliveBundles(napi_env env, napi_callback_info info) + { + GET_CB_INFO_AND_CALL(env, info, JsAppManager, OnGetKeepAliveBundles); + } #ifdef SUPPORT_SCREEN static bool CheckCallerIsSystemApp() { @@ -1457,6 +1467,138 @@ private: return result; } + napi_value OnSetKeepAliveForBundleInner(napi_env env, const std::string &bundleName, + int32_t userId, bool flag) + { + auto innerErrCode = std::make_shared(ERR_OK); + NapiAsyncTask::ExecuteCallback execute = [bundleName, userId, flag, + abilityManager = abilityManager_, innerErrCode]() { + if (innerErrCode == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "inner code null"); + return; + } + if (abilityManager == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "abilityManager nullptr"); + *innerErrCode = static_cast(AbilityErrorCode::ERROR_CODE_INNER); + return; + } + *innerErrCode = abilityManager->SetApplicationKeepAlive(bundleName, userId, flag); + }; + + NapiAsyncTask::CompleteCallback complete = [innerErrCode](napi_env env, NapiAsyncTask& task, int32_t status) { + if (innerErrCode == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "inner code null"); + task.Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER))); + return; + } + if (*innerErrCode == ERR_OK) { + TAG_LOGI(AAFwkTag::APPMGR, "SetApplicationKeepAlive succeeded."); + task.ResolveWithNoError(env, CreateJsUndefined(env)); + return; + } + TAG_LOGE(AAFwkTag::APPMGR, "SetApplicationKeepAlive failed:%{public}d", *innerErrCode); + task.Reject(env, CreateJsErrorByNativeErr(env, *innerErrCode)); + }; + + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("OnSetKeepAliveForBundle", env, + CreateAsyncTaskWithLastParam(env, nullptr, std::move(execute), std::move(complete), &result)); + return result; + } + + napi_value OnSetKeepAliveForBundle(napi_env env, size_t argc, napi_value *argv) + { + if (argc < ARGC_THREE) { + TAG_LOGE(AAFwkTag::APPMGR, "Params not enough."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + std::string bundleName; + if (!ConvertFromJsValue(env, argv[INDEX_ZERO], bundleName)) { + TAG_LOGE(AAFwkTag::APPMGR, "get bundleName wrong."); + ThrowInvalidParamError(env, "Parse param bundleName failed, must be a string."); + return CreateJsUndefined(env); + } + int32_t userId = -1; + if (!ConvertFromJsValue(env, argv[INDEX_ONE], userId)) { + TAG_LOGE(AAFwkTag::APPMGR, "get userId wrong."); + ThrowInvalidParamError(env, "Parse param userId failed, must be a number."); + return CreateJsUndefined(env); + } + bool flag = false; + if (!ConvertFromJsValue(env, argv[INDEX_TWO], flag)) { + TAG_LOGE(AAFwkTag::APPMGR, "get flag wrong."); + ThrowInvalidParamError(env, "Parse param flag failed, must be a boolean."); + return CreateJsUndefined(env); + } + return OnSetKeepAliveForBundleInner(env, bundleName, userId, flag); + } + + napi_value OnGetKeepAliveBundlesInner(napi_env env, int32_t appType, int32_t userId) + { + auto innerErrCode = std::make_shared(ERR_OK); + auto infoList = std::make_shared>(); + NapiAsyncTask::ExecuteCallback execute = [appType, userId, abilityManager = abilityManager_, + infoList, innerErrCode]() { + if (infoList == nullptr || innerErrCode == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "infoList or inner code null"); + return; + } + if (abilityManager == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "abilityManager nullptr"); + *innerErrCode = static_cast(AbilityErrorCode::ERROR_CODE_INNER); + return; + } + *innerErrCode = abilityManager->QueryKeepAliveApplications(appType, userId, *infoList); + }; + + NapiAsyncTask::CompleteCallback complete = [infoList, innerErrCode]( + napi_env env, NapiAsyncTask& task, int32_t status) { + if (infoList == nullptr || innerErrCode == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "infoList or inner code null"); + task.Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER))); + return; + } + if (*innerErrCode == ERR_OK) { + TAG_LOGI(AAFwkTag::APPMGR, "QueryKeepAliveApplications succeeded."); + task.ResolveWithNoError(env, CreateJsKeepAliveBundleInfoArray(env, *infoList)); + return; + } + TAG_LOGE(AAFwkTag::APPMGR, "QueryKeepAliveApplications failed:%{public}d", *innerErrCode); + task.Reject(env, CreateJsErrorByNativeErr(env, *innerErrCode)); + }; + + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("OnSetKeepAliveForBundle", env, + CreateAsyncTaskWithLastParam(env, nullptr, std::move(execute), std::move(complete), &result)); + return result; + } + + napi_value OnGetKeepAliveBundles(napi_env env, size_t argc, napi_value *argv) + { + TAG_LOGD(AAFwkTag::APPMGR, "called"); + if (argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::APPMGR, "Params not enough."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + int32_t appType = 0; + if (!ConvertFromJsValue(env, argv[INDEX_ZERO], appType)) { + TAG_LOGE(AAFwkTag::APPMGR, "get appType wrong."); + ThrowInvalidParamError(env, "Parse param appType failed, must be a number."); + return CreateJsUndefined(env); + } + int32_t userId = -1; + if (argc > ARGC_ONE && !ConvertFromJsValue(env, argv[INDEX_ONE], userId)) { + TAG_LOGE(AAFwkTag::APPMGR, "get userId wrong."); + ThrowInvalidParamError(env, "Parse param userId failed, must be a number."); + return CreateJsUndefined(env); + } + return OnGetKeepAliveBundlesInner(env, appType, userId); + } + bool CheckOnOffType(napi_env env, size_t argc, napi_value* argv) { if (argc < ARGC_ONE) { @@ -1524,6 +1666,8 @@ napi_value JsAppManagerInit(napi_env env, napi_value exportObj) napi_set_named_property(env, exportObj, "ApplicationState", ApplicationStateInit(env)); napi_set_named_property(env, exportObj, "ProcessState", ProcessStateInit(env)); napi_set_named_property(env, exportObj, "PreloadMode", PreloadModeInit(env)); + napi_set_named_property(env, exportObj, "KeepAliveAppType", KeepAliveAppTypeInit(env)); + napi_set_named_property(env, exportObj, "KeepAliveSetter", KeepAliveSetterInit(env)); const char *moduleName = "AppManager"; BindNativeFunction(env, exportObj, "on", moduleName, JsAppManager::On); @@ -1534,8 +1678,7 @@ napi_value JsAppManagerInit(napi_env env, napi_value exportObj) JsAppManager::GetRunningProcessInformation); BindNativeFunction(env, exportObj, "getRunningProcessInformation", moduleName, JsAppManager::GetRunningProcessInformation); - BindNativeFunction(env, exportObj, "isRunningInStabilityTest", moduleName, - JsAppManager::IsRunningInStabilityTest); + BindNativeFunction(env, exportObj, "isRunningInStabilityTest", moduleName, JsAppManager::IsRunningInStabilityTest); BindNativeFunction(env, exportObj, "killProcessWithAccount", moduleName, JsAppManager::KillProcessWithAccount); BindNativeFunction(env, exportObj, "killProcessesByBundleName", moduleName, JsAppManager::KillProcessesByBundleName); @@ -1550,13 +1693,14 @@ napi_value JsAppManagerInit(napi_env env, napi_value exportObj) JsAppManager::GetRunningProcessInfoByBundleName); BindNativeFunction(env, exportObj, "getRunningMultiAppInfo", moduleName, JsAppManager::GetRunningMultiAppInfo); BindNativeFunction(env, exportObj, "isApplicationRunning", moduleName, JsAppManager::IsApplicationRunning); - BindNativeFunction(env, exportObj, "isAppRunning", moduleName, - JsAppManager::IsAppRunning); + BindNativeFunction(env, exportObj, "isAppRunning", moduleName, JsAppManager::IsAppRunning); BindNativeFunction(env, exportObj, "preloadApplication", moduleName, JsAppManager::PreloadApplication); BindNativeFunction(env, exportObj, "getRunningProcessInformationByBundleType", moduleName, JsAppManager::GetRunningProcessInformationByBundleType); BindNativeFunction(env, exportObj, "getSupportedProcessCachePids", moduleName, JsAppManager::GetSupportedProcessCachePids); + BindNativeFunction(env, exportObj, "setKeepAliveForBundle", moduleName, JsAppManager::SetKeepAliveForBundle); + BindNativeFunction(env, exportObj, "getKeepAliveBundles", moduleName, JsAppManager::GetKeepAliveBundles); TAG_LOGD(AAFwkTag::APPMGR, "end"); return CreateJsUndefined(env); } diff --git a/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.cpp b/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.cpp index edf277d5c2..5769332274 100644 --- a/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.cpp +++ b/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.cpp @@ -299,6 +299,48 @@ napi_value PreloadModeInit(napi_env env) return objValue; } +napi_value KeepAliveAppTypeInit(napi_env env) +{ + if (env == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "null env"); + return nullptr; + } + + napi_value object = nullptr; + napi_create_object(env, &object); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "null obj"); + return nullptr; + } + napi_set_named_property(env, object, "ALL", CreateJsValue(env, + static_cast(KeepAliveAppType::UNSPECIFIED))); + napi_set_named_property(env, object, "THIRD_PARTY", + CreateJsValue(env, static_cast(KeepAliveAppType::THIRD_PARTY))); + napi_set_named_property(env, object, "SYSTEM", + CreateJsValue(env, static_cast(KeepAliveAppType::SYSTEM))); + return object; +} + +napi_value KeepAliveSetterInit(napi_env env) +{ + if (env == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "null env"); + return nullptr; + } + + napi_value object = nullptr; + napi_create_object(env, &object); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "null obj"); + return nullptr; + } + napi_set_named_property(env, object, "SYSTEM", + CreateJsValue(env, static_cast(KeepAliveSetter::SYSTEM))); + napi_set_named_property(env, object, "USER", + CreateJsValue(env, static_cast(KeepAliveSetter::USER))); + return object; +} + bool ConvertPreloadApplicationParam(napi_env env, size_t argc, napi_value *argv, PreloadApplicationParam ¶m, std::string &errorMsg) { @@ -352,5 +394,30 @@ JsAppProcessState ConvertToJsAppProcessState( } return processState; } + +napi_value CreateJsKeepAliveBundleInfo(napi_env env, const KeepAliveInfo &info) +{ + napi_value object = nullptr; + napi_create_object(env, &object); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "null obj"); + return nullptr; + } + napi_set_named_property(env, object, "bundleName", CreateJsValue(env, info.bundleName)); + napi_set_named_property(env, object, "type", CreateJsValue(env, static_cast(info.appType))); + napi_set_named_property(env, object, "setter", CreateJsValue(env, static_cast(info.setter))); + return object; +} + +napi_value CreateJsKeepAliveBundleInfoArray(napi_env env, const std::vector& data) +{ + napi_value arrayValue = nullptr; + napi_create_array_with_length(env, data.size(), &arrayValue); + uint32_t index = 0; + for (const auto &item : data) { + napi_set_element(env, arrayValue, index++, CreateJsKeepAliveBundleInfo(env, item)); + } + return arrayValue; +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.h b/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.h index 9cfa189192..12aa474663 100644 --- a/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.h +++ b/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.h @@ -17,6 +17,7 @@ #define OHOS_ABILITY_RUNTIME_JS_APP_MANAGER_UTILS_H #include "application_state_observer_stub.h" +#include "keep_alive_info.h" #include "native_engine/native_engine.h" #include "running_process_info.h" #include "running_multi_info.h" @@ -63,6 +64,8 @@ napi_value CreateJsRunningProcessInfo(napi_env env, const RunningProcessInfo &in napi_value ApplicationStateInit(napi_env env); napi_value ProcessStateInit(napi_env env); napi_value PreloadModeInit(napi_env env); +napi_value KeepAliveAppTypeInit(napi_env env); +napi_value KeepAliveSetterInit(napi_env env); bool ConvertPreloadApplicationParam(napi_env env, size_t argc, napi_value *argv, PreloadApplicationParam ¶m, std::string &errorMsg); JsAppProcessState ConvertToJsAppProcessState( @@ -72,6 +75,8 @@ napi_value CreateJsRunningAppCloneArray(napi_env env, const std::vector& data); napi_value CreateJsRunningMultiInstanceInfo(napi_env env, const RunningMultiInstanceInfo &info); +napi_value CreateJsKeepAliveBundleInfo(napi_env env, const KeepAliveInfo &info); +napi_value CreateJsKeepAliveBundleInfoArray(napi_env env, const std::vector& data); } // namespace AbilityRuntime } // namespace OHOS #endif // OHOS_ABILITY_RUNTIME_JS_APP_MANAGER_UTILS_H diff --git a/frameworks/native/ability/native/ability_business_error/ability_business_error.cpp b/frameworks/native/ability/native/ability_business_error/ability_business_error.cpp index a432dbb883..a0994856ec 100644 --- a/frameworks/native/ability/native/ability_business_error/ability_business_error.cpp +++ b/frameworks/native/ability/native/ability_business_error/ability_business_error.cpp @@ -77,6 +77,9 @@ constexpr const char* ERROR_MSG_NOT_SUPPORT_CROSS_APP_START = "Redirection to a third-party application is not allowed in API version 11 or later."; constexpr const char* ERROR_MSG_CANNOT_MATCH_ANY_COMPONENT = "No matching ability is found."; constexpr const char* ERROR_MSG_TARGET_BUNDLE_NOT_EXIST = "The bundle does not exist or no patch has been applied."; +constexpr const char* ERROR_MSG_NO_MAIN_ABILITY = "The target bundle has no main ability."; +constexpr const char* ERROR_MSG_NO_STATUS_BAR_ABILITY = "The target app has no status-bar ability."; +constexpr const char* ERROR_MSG_NOT_ATTACHED_TO_STATUS_BAR = "The target app is not attached to a status bar."; constexpr const char* ERROR_MSG_NO_RESIDENT_PERMISSION = "The caller application can only set the resident status of the configured process."; constexpr const char* ERROR_MSG_MULTI_APP_NOT_SUPPORTED = "App clone or multi-instance is not supported."; @@ -148,6 +151,9 @@ static std::unordered_map ERR_CODE_MAP = { { AbilityErrorCode::ERROR_CODE_NOT_SUPPORT_CROSS_APP_START, ERROR_MSG_NOT_SUPPORT_CROSS_APP_START }, { AbilityErrorCode::ERROR_CODE_CANNOT_MATCH_ANY_COMPONENT, ERROR_MSG_CANNOT_MATCH_ANY_COMPONENT }, { AbilityErrorCode::ERROR_CODE_TARGET_BUNDLE_NOT_EXIST, ERROR_MSG_TARGET_BUNDLE_NOT_EXIST }, + { AbilityErrorCode::ERROR_CODE_NO_MAIN_ABILITY, ERROR_MSG_NO_MAIN_ABILITY }, + { AbilityErrorCode::ERROR_CODE_NO_STATUS_BAR_ABILITY, ERROR_MSG_NO_STATUS_BAR_ABILITY }, + { AbilityErrorCode::ERROR_CODE_NOT_ATTACHED_TO_STATUS_BAR, ERROR_MSG_NOT_ATTACHED_TO_STATUS_BAR }, { AbilityErrorCode::ERROR_CODE_NO_RESIDENT_PERMISSION, ERROR_MSG_NO_RESIDENT_PERMISSION }, { AbilityErrorCode::ERROR_CODE_MULTI_APP_NOT_SUPPORTED, ERROR_MSG_MULTI_APP_NOT_SUPPORTED }, { AbilityErrorCode::ERROR_NOT_APP_CLONE, ERROR_MSG_NOT_APP_CLONE }, @@ -219,6 +225,9 @@ static std::unordered_map INNER_TO_JS_ERROR_CODE_MAP {ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST, AbilityErrorCode::ERROR_CODE_INVALID_ID}, {ERR_START_OTHER_APP_FAILED, AbilityErrorCode::ERROR_CODE_NOT_SUPPORT_CROSS_APP_START}, {ERR_TARGET_BUNDLE_NOT_EXIST, AbilityErrorCode::ERROR_CODE_TARGET_BUNDLE_NOT_EXIST}, + {ERR_NO_MAIN_ABILITY, AbilityErrorCode::ERROR_CODE_NO_MAIN_ABILITY}, + {ERR_NO_STATUS_BAR_ABILITY, AbilityErrorCode::ERROR_CODE_NO_STATUS_BAR_ABILITY}, + {ERR_NOT_ATTACHED_TO_STATUS_BAR, AbilityErrorCode::ERROR_CODE_NOT_ATTACHED_TO_STATUS_BAR}, {ERR_NO_RESIDENT_PERMISSION, AbilityErrorCode::ERROR_CODE_NO_RESIDENT_PERMISSION}, {ERR_MULTI_APP_NOT_SUPPORTED, AbilityErrorCode::ERROR_CODE_MULTI_APP_NOT_SUPPORTED}, {ERR_APP_CLONE_INDEX_INVALID, AbilityErrorCode::ERROR_APP_CLONE_INDEX_INVALID}, diff --git a/interfaces/inner_api/ability_manager/BUILD.gn b/interfaces/inner_api/ability_manager/BUILD.gn index 1a529afb18..f12f172c3b 100644 --- a/interfaces/inner_api/ability_manager/BUILD.gn +++ b/interfaces/inner_api/ability_manager/BUILD.gn @@ -85,6 +85,7 @@ ohos_shared_library("ability_manager") { "${ability_runtime_services_path}/abilitymgr/src/insight_intent_execute_callback_stub.cpp", "${ability_runtime_services_path}/abilitymgr/src/insight_intent_execute_param.cpp", "${ability_runtime_services_path}/abilitymgr/src/insight_intent_execute_result.cpp", + "${ability_runtime_services_path}/abilitymgr/src/keep_alive/keep_alive_info.cpp", "${ability_runtime_services_path}/abilitymgr/src/launch_param.cpp", "${ability_runtime_services_path}/abilitymgr/src/lifecycle_state_info.cpp", "${ability_runtime_services_path}/abilitymgr/src/mission/mission_listener_stub.cpp", diff --git a/interfaces/inner_api/ability_manager/include/ability_manager_errors.h b/interfaces/inner_api/ability_manager/include/ability_manager_errors.h index 27724a4bfe..b7de902fb5 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_errors.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_errors.h @@ -807,6 +807,21 @@ enum NativeFreeInstallError { */ INVALID_REMOTE_PARAMETERS_ERR = 29360131, + /** + * Native error(29360135) for target bundle has no main ability. + */ + ERR_NO_MAIN_ABILITY = 29360135, + + /** + * Native error(29360136) for target app has no status-bar ability. + */ + ERR_NO_STATUS_BAR_ABILITY = 29360136, + + /** + * Native error(29360137) for target app is not attached to a status bar. + */ + ERR_NOT_ATTACHED_TO_STATUS_BAR = 29360137, + /* * Result(29360205) for continue freeinstall failed. */ diff --git a/interfaces/inner_api/ability_manager/include/ability_manager_interface.h b/interfaces/inner_api/ability_manager/include/ability_manager_interface.h index f5dd76aaa3..7eae3f8171 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_interface.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_interface.h @@ -40,6 +40,7 @@ #include "insight_intent_execute_param.h" #include "insight_intent_execute_result.h" #include "iprepare_terminate_callback_interface.h" +#include "keep_alive_info.h" #include "mission_info.h" #include "mission_listener_interface.h" #include "mission_snapshot.h" @@ -73,6 +74,7 @@ class IStatusBarDelegate; } namespace AAFwk { +using KeepAliveInfo = AbilityRuntime::KeepAliveInfo; using AutoStartupInfo = AbilityRuntime::AutoStartupInfo; using InsightIntentExecuteParam = AppExecFwk::InsightIntentExecuteParam; using InsightIntentExecuteResult = AppExecFwk::InsightIntentExecuteResult; @@ -1895,6 +1897,54 @@ public: { return 0; } + + /** + * Set keep-alive flag for application under a specific user. + * @param bundleName Bundle name. + * @param userId User Id. + * @param flag Keep-alive flag. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t SetApplicationKeepAlive(const std::string &bundleName, int32_t userId, bool flag) + { + return 0; + } + + /** + * Get keep-alive applications. + * @param appType Application type. + * @param userId User Id. + * @param list List of Keep-alive information. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t QueryKeepAliveApplications(int32_t appType, int32_t userId, std::vector &list) + { + return 0; + } + + /** + * Set keep-alive flag for application under a specific user by EDM. + * @param bundleName Bundle name. + * @param userId User Id. + * @param flag Keep-alive flag. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t SetApplicationKeepAliveByEDM(const std::string &bundleName, int32_t userId, bool flag) + { + return 0; + } + + /** + * Get keep-alive applications by EDM. + * @param appType Application type. + * @param userId User Id. + * @param list List of Keep-alive information. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t QueryKeepAliveApplicationsByEDM(int32_t appType, int32_t userId, std::vector &list) + { + return 0; + } }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/ability_manager/include/ability_manager_ipc_interface_code.h b/interfaces/inner_api/ability_manager/include/ability_manager_ipc_interface_code.h index 9a13e7599c..e709c1cc44 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_ipc_interface_code.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_ipc_interface_code.h @@ -561,6 +561,18 @@ enum class AbilityManagerInterfaceCode { // update associate config list UPDATE_ASSOCIATE_CONFIG_LIST = 6120, + + // set application keep alive + SET_APPLICATION_KEEP_ALLIVE = 6121, + + // get keep-alive applications + GET_APPLICATIONS_KEEP_ALIVE = 6122, + + // set application keep alive by EDM + SET_APPLICATION_KEEP_ALLIVE_BY_EDM = 6123, + + // get keep-alive applications by EDM + GET_APPLICATIONS_KEEP_ALIVE_BY_EDM = 6124, }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/ability_manager/include/keep_alive_info.h b/interfaces/inner_api/ability_manager/include/keep_alive_info.h index 7f8a6d9d85..0fc0dacff9 100644 --- a/interfaces/inner_api/ability_manager/include/keep_alive_info.h +++ b/interfaces/inner_api/ability_manager/include/keep_alive_info.h @@ -38,7 +38,7 @@ enum class KeepAliveSetter : int32_t { */ enum class KeepAliveAppType : int32_t { UNSPECIFIED = 0, - APP = 1, + THIRD_PARTY = 1, SYSTEM = 2, }; @@ -60,7 +60,7 @@ public: struct KeepAliveStatus { int32_t code; - bool isKeepAlive; + KeepAliveSetter setter; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/interfaces/inner_api/ability_manager/include/process_options.h b/interfaces/inner_api/ability_manager/include/process_options.h index 988ae5d4c7..73af531813 100644 --- a/interfaces/inner_api/ability_manager/include/process_options.h +++ b/interfaces/inner_api/ability_manager/include/process_options.h @@ -56,6 +56,7 @@ public: ProcessMode processMode = ProcessMode::UNSPECIFIED; StartupVisibility startupVisibility = StartupVisibility::UNSPECIFIED; std::string processName; + bool isRestartKeepAlive = false; }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_interface.h b/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_interface.h index fe6b5045aa..c23ed0ee81 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_interface.h +++ b/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_interface.h @@ -375,6 +375,14 @@ public: */ virtual void SetKeepAliveEnableState(const std::string &bundleName, bool enable, int32_t uid) {}; + /** + * @brief Set non-resident keep-alive process status. + * @param bundleName The application bundle name. + * @param enable The current updated enable status. + * @param uid indicates user, 0 for all users + */ + virtual void SetKeepAliveDkv(const std::string &bundleName, bool enable, int32_t uid) {}; + /** * To clear the process by ability token. * @@ -502,6 +510,7 @@ public: IS_APP_KILLING, ENABLE_START_PROCESS_FLAG_BY_USER_ID, SET_APP_EXCEPTION_CALLBACK, + SET_KEEP_ALIVE_DKV, // Add enumeration values above END }; diff --git a/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_proxy.h b/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_proxy.h index 82e688c5db..85c72fabd1 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_proxy.h +++ b/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_proxy.h @@ -338,6 +338,14 @@ public: */ void SetKeepAliveEnableState(const std::string &bundleName, bool enable, int32_t uid) override; + /** + * @brief Set non-resident keep-alive process status. + * @param bundleName The application bundle name. + * @param enable The current updated enable status. + * @param uid indicates user, 0 for all users + */ + void SetKeepAliveDkv(const std::string &bundleName, bool enable, int32_t uid) override; + /** * To clear the process by ability token. * diff --git a/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_stub.h b/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_stub.h index 6f6db7594b..f609278cd9 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_stub.h @@ -85,6 +85,7 @@ private: int32_t HandleClearProcessByToken(MessageParcel &data, MessageParcel &reply); int32_t HandleIsMemorySizeSufficent(MessageParcel &data, MessageParcel &reply); int32_t HandleSetKeepAliveEnableState(MessageParcel &data, MessageParcel &reply); + int32_t HandleSetKeepAliveDkv(MessageParcel &data, MessageParcel &reply); int32_t HandleAttachedToStatusBar(MessageParcel &data, MessageParcel &reply); int32_t OnRemoteRequestInner(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_client.h b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_client.h index 7999284a36..48725af913 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_client.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_client.h @@ -675,6 +675,14 @@ public: */ void SetKeepAliveEnableState(const std::string &bundleName, bool enable, int32_t uid); + /** + * @brief Set non-resident keep-alive process status. + * @param bundleName The application bundle name. + * @param enable The current updated enable status. + * @param uid indicates user, 0 for all users + */ + void SetKeepAliveDkv(const std::string &bundleName, bool enable, int32_t uid); + /** * Register application or process state observer. * @param observer, ability token. @@ -893,6 +901,17 @@ public: bool IsAppKilling(sptr token) const; + /** + * Check whether the bundle is running. + * + * @param bundleName Indicates the bundle name of the bundle. + * @param appCloneIndex the appindex of the bundle. + * @param isRunning Obtain the running status of the application, the result is true if running, false otherwise. + * @return Return ERR_OK if success, others fail. + */ + virtual AppMgrResultCode IsAppRunning(const std::string &bundleName, int32_t appCloneIndex, + bool &isRunning); + private: void SetServiceManager(std::unique_ptr serviceMgr); /** diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_host.h b/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_host.h index 65f6fbd506..561b5f3b60 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_host.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_host.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -62,7 +62,13 @@ public: * @param bundleInfos resident process bundle infos. */ virtual void NotifyStartResidentProcess(std::vector &bundleInfos) override; - + + /** + * @brief Notify abilityms start keep-alive process. + * @param bundleInfos resident process bundle infos. + */ + virtual void NotifyStartKeepAliveProcess(std::vector &bundleInfos) override; + /** * @brief Notify abilityms app process OnRemoteDied * @param abilityTokens abilities in died process. @@ -81,6 +87,7 @@ private: int32_t HandleOnAbilityRequestDone(MessageParcel &data, MessageParcel &reply); int32_t HandleNotifyConfigurationChange(MessageParcel &data, MessageParcel &reply); int32_t HandleNotifyStartResidentProcess(MessageParcel &data, MessageParcel &reply); + int32_t HandleNotifyStartKeepAliveProcess(MessageParcel &data, MessageParcel &reply); int32_t HandleOnAppRemoteDied(MessageParcel &data, MessageParcel &reply); int32_t HandleNotifyAppPreCache(MessageParcel &data, MessageParcel &reply); diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_proxy.h b/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_proxy.h index d0402dc24a..51bc105d5b 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_proxy.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_proxy.h @@ -57,6 +57,12 @@ public: */ virtual void NotifyStartResidentProcess(std::vector &bundleInfos) override; + /** + * @brief Notify abilityms start keep-alive process. + * @param bundleInfos resident process bundle infos. + */ + virtual void NotifyStartKeepAliveProcess(std::vector &bundleInfos) override; + /** * @brief Notify abilityms app process OnRemoteDied * @param abilityTokens abilities in died process. diff --git a/interfaces/inner_api/app_manager/include/appmgr/iapp_state_callback.h b/interfaces/inner_api/app_manager/include/appmgr/iapp_state_callback.h index e48cbff652..bf7951a591 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/iapp_state_callback.h +++ b/interfaces/inner_api/app_manager/include/appmgr/iapp_state_callback.h @@ -63,6 +63,12 @@ public: */ virtual void NotifyStartResidentProcess(std::vector &bundleInfos) {} + /** + * @brief Notify abilityms start keep-alive process. + * @param bundleInfos resident process bundle infos. + */ + virtual void NotifyStartKeepAliveProcess(std::vector &bundleInfos) {} + /** * @brief Notify abilityms app process OnRemoteDied * @param abilityTokens abilities in died process. @@ -82,7 +88,8 @@ public: TRANSACT_ON_NOTIFY_CONFIG_CHANGE, TRANSACT_ON_NOTIFY_START_RESIDENT_PROCESS, TRANSACT_ON_APP_REMOTE_DIED, - TRANSACT_ON_APP_PRE_CACHE + TRANSACT_ON_APP_PRE_CACHE, + TRANSACT_ON_NOTIFY_START_KEEP_ALIVE_PROCESS }; }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_proxy.cpp index 5c60a78d30..bea80ee23c 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_proxy.cpp @@ -972,6 +972,31 @@ void AmsMgrProxy::SetKeepAliveEnableState(const std::string &bundleName, bool en } } +void AmsMgrProxy::SetKeepAliveDkv(const std::string &bundleName, bool enable, int32_t uid) +{ + TAG_LOGD(AAFwkTag::APPMGR, "called"); + MessageParcel data; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write token failed"); + return; + } + if (bundleName.empty() || !data.WriteString(bundleName)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write bundleName fail"); + return; + } + if (!data.WriteBool(enable) || !data.WriteInt32(uid)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write flag or uid fail"); + return; + } + MessageParcel reply; + MessageOption option; + auto ret = SendTransactCmd(static_cast(IAmsMgr::Message::SET_KEEP_ALIVE_DKV), + data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGE(AAFwkTag::APPMGR, "Send request err: %{public}d", ret); + } +} + int32_t AmsMgrProxy::SetAppWaitingDebug(const std::string &bundleName, bool isPersist) { TAG_LOGD(AAFwkTag::APPMGR, "called"); diff --git a/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_stub.cpp index 1346b7ffb2..219f663855 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_stub.cpp @@ -215,6 +215,8 @@ int32_t AmsMgrStub::OnRemoteRequestInnerFourth(uint32_t code, MessageParcel &dat return HandleIsProcessAttached(data, reply); case static_cast(IAmsMgr::Message::IS_APP_KILLING): return HandleIsAppKilling(data, reply); + case static_cast(IAmsMgr::Message::SET_KEEP_ALIVE_DKV): + return HandleSetKeepAliveDkv(data, reply); } return AAFwk::ERR_CODE_NOT_EXIST; } @@ -714,6 +716,16 @@ int32_t AmsMgrStub::HandleSetKeepAliveEnableState(MessageParcel &data, MessagePa return NO_ERROR; } +int32_t AmsMgrStub::HandleSetKeepAliveDkv(MessageParcel &data, MessageParcel &reply) +{ + TAG_LOGD(AAFwkTag::APPMGR, "called"); + auto bundleName = data.ReadString(); + auto enable = data.ReadBool(); + auto uid = data.ReadInt32(); + SetKeepAliveDkv(bundleName, enable, uid); + return NO_ERROR; +} + int32_t AmsMgrStub::HandleClearNonPersistWaitingDebugFlag(MessageParcel &data, MessageParcel &reply) { TAG_LOGD(AAFwkTag::APPMGR, "called"); diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_mgr_client.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_mgr_client.cpp index 332539f869..ee743fa96e 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_mgr_client.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_mgr_client.cpp @@ -688,6 +688,14 @@ void AppMgrClient::SetKeepAliveEnableState(const std::string &bundleName, bool e amsService_->SetKeepAliveEnableState(bundleName, enable, uid); } +void AppMgrClient::SetKeepAliveDkv(const std::string &bundleName, bool enable, int32_t uid) +{ + if (!IsAmsServiceReady()) { + return; + } + amsService_->SetKeepAliveDkv(bundleName, enable, uid); +} + void AppMgrClient::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, int32_t requestId) { @@ -1403,5 +1411,15 @@ bool AppMgrClient::IsAppKilling(sptr token) const } return amsService->IsAppKilling(token); } + +AppMgrResultCode AppMgrClient::IsAppRunning(const std::string &bundleName, int32_t appCloneIndex, + bool &isRunning) +{ + sptr service = iface_cast(mgrHolder_->GetRemoteObject()); + if (service != nullptr) { + return AppMgrResultCode(service->IsAppRunning(bundleName, appCloneIndex, isRunning)); + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_host.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_host.cpp index 5b190fbf50..37936e1b4d 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_host.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_host.cpp @@ -56,6 +56,8 @@ int AppStateCallbackHost::OnRemoteRequest( return HandleOnAppRemoteDied(data, reply); case static_cast(IAppStateCallback::Message::TRANSACT_ON_APP_PRE_CACHE): return HandleNotifyAppPreCache(data, reply); + case static_cast(IAppStateCallback::Message::TRANSACT_ON_NOTIFY_START_KEEP_ALIVE_PROCESS): + return HandleNotifyStartKeepAliveProcess(data, reply); } TAG_LOGD(AAFwkTag::APPMGR, "AppStateCallbackHost::OnRemoteRequest end"); @@ -86,6 +88,11 @@ void AppStateCallbackHost::NotifyStartResidentProcess(std::vector &bundleInfos) +{ + TAG_LOGD(AAFwkTag::APPMGR, "called"); +} + void AppStateCallbackHost::OnAppRemoteDied(const std::vector> &abilityTokens) { TAG_LOGD(AAFwkTag::APPMGR, "called"); @@ -148,6 +155,26 @@ int32_t AppStateCallbackHost::HandleNotifyStartResidentProcess(MessageParcel &da return NO_ERROR; } +int32_t AppStateCallbackHost::HandleNotifyStartKeepAliveProcess(MessageParcel &data, MessageParcel &reply) +{ + std::vector bundleInfos; + int32_t infoSize = data.ReadInt32(); + if (infoSize > CYCLE_LIMIT) { + TAG_LOGE(AAFwkTag::APPMGR, "infoSize is too large"); + return ERR_INVALID_VALUE; + } + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr bundleInfo(data.ReadParcelable()); + if (!bundleInfo) { + TAG_LOGE(AAFwkTag::APPMGR, "Read Parcelable infos failed."); + return ERR_INVALID_VALUE; + } + bundleInfos.emplace_back(*bundleInfo); + } + NotifyStartKeepAliveProcess(bundleInfos); + return NO_ERROR; +} + int32_t AppStateCallbackHost::HandleOnAppRemoteDied(MessageParcel &data, MessageParcel &reply) { std::vector> abilityTokens; diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_proxy.cpp index c6e700e920..597e00026a 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_proxy.cpp @@ -137,6 +137,35 @@ void AppStateCallbackProxy::NotifyStartResidentProcess(std::vector &bundleInfos) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "WriteInterfaceToken failed"); + return; + } + + if (!data.WriteInt32(bundleInfos.size())) { + TAG_LOGE(AAFwkTag::APPMGR, "write bundle info size failed."); + return; + } + + for (auto &bundleInfo : bundleInfos) { + if (!data.WriteParcelable(&bundleInfo)) { + TAG_LOGE(AAFwkTag::APPMGR, "write bundle info failed"); + return; + } + } + auto ret = SendTransactCmd( + static_cast(IAppStateCallback::Message::TRANSACT_ON_NOTIFY_START_KEEP_ALIVE_PROCESS), + data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); + } +} + void AppStateCallbackProxy::OnAppRemoteDied(const std::vector> &abilityTokens) { MessageParcel data; diff --git a/interfaces/kits/native/ability/native/ability_business_error/ability_business_error.h b/interfaces/kits/native/ability/native/ability_business_error/ability_business_error.h index 6284e4403c..56723ea1f2 100644 --- a/interfaces/kits/native/ability/native/ability_business_error/ability_business_error.h +++ b/interfaces/kits/native/ability/native/ability_business_error/ability_business_error.h @@ -204,6 +204,15 @@ enum class AbilityErrorCode { // target free install task does not exist. ERROR_CODE_FREE_INSTALL_TASK_NOT_EXIST = 16300007, + // target bundle has no main ability. + ERROR_CODE_NO_MAIN_ABILITY = 16300008, + + // target application has no status-bar ability. + ERROR_CODE_NO_STATUS_BAR_ABILITY = 16300009, + + // target application is not attached to a status bar. + ERROR_CODE_NOT_ATTACHED_TO_STATUS_BAR = 16300010, + ERROR_CODE_BUNDLE_NAME_INVALID = 18500001, }; diff --git a/services/abilitymgr/BUILD.gn b/services/abilitymgr/BUILD.gn index 77c22d1b96..4233c90dee 100644 --- a/services/abilitymgr/BUILD.gn +++ b/services/abilitymgr/BUILD.gn @@ -36,6 +36,7 @@ config("abilityms_config") { "include/mission/", "include/rdb/", "include/resident_process/", + "include/keep_alive/", "include/screen_lock/", "include/utils/", "${ability_runtime_innerkits_path}/ability_manager/include", diff --git a/services/abilitymgr/abilitymgr.gni b/services/abilitymgr/abilitymgr.gni index c0f9f45dca..6e59ee6148 100644 --- a/services/abilitymgr/abilitymgr.gni +++ b/services/abilitymgr/abilitymgr.gni @@ -126,6 +126,11 @@ abilityms_files = [ "src/insight_intent_execute_manager.cpp", "src/insight_intent_execute_result.cpp", + # keep alive + "src/keep_alive/ability_keep_alive_data_manager.cpp", + "src/keep_alive/ability_keep_alive_service.cpp", + "src/keep_alive/keep_alive_process_manager.cpp", + "src/ability_manager_event_subscriber.cpp", #utils @@ -135,6 +140,7 @@ abilityms_files = [ "src/utils/dump_utils.cpp", "src/utils/extension_permissions_util.cpp", "src/utils/insight_intent_utils.cpp", + "src/utils/keep_alive_utils.cpp", "src/utils/main_element_utils.cpp", "src/utils/modal_system_dialog_util.cpp", "src/utils/multi_app_utils.cpp", diff --git a/services/abilitymgr/include/ability_auto_startup_data_manager.h b/services/abilitymgr/include/ability_auto_startup_data_manager.h index 72d883fcc8..1eca706bfe 100644 --- a/services/abilitymgr/include/ability_auto_startup_data_manager.h +++ b/services/abilitymgr/include/ability_auto_startup_data_manager.h @@ -56,9 +56,6 @@ private: DistributedKv::Key ConvertAutoStartupDataToKey(const AutoStartupInfo &info); AutoStartupInfo ConvertAutoStartupInfoFromKeyAndValue( const DistributedKv::Key &key, const DistributedKv::Value &value); - bool IsEqual(nlohmann::json &jsonObject, const std::string &key, - const std::string &value, bool checkEmpty = false); - bool IsEqual(nlohmann::json &jsonObject, const std::string &key, int32_t value); bool IsEqual(const DistributedKv::Key &key, const AutoStartupInfo &info); bool IsEqual(const DistributedKv::Key &key, const std::string &accessTokenId); bool IsEqual(const DistributedKv::Key &key, int32_t userId); diff --git a/services/abilitymgr/include/ability_manager_proxy.h b/services/abilitymgr/include/ability_manager_proxy.h index c619a94afb..4c5b148ad2 100644 --- a/services/abilitymgr/include/ability_manager_proxy.h +++ b/services/abilitymgr/include/ability_manager_proxy.h @@ -1499,6 +1499,44 @@ public: virtual int32_t UpdateAssociateConfigList(const std::map>& configs, const std::list& exportConfigs, int32_t flag) override; + /** + * Set keep-alive flag for application under a specific user. + * @param bundleName Bundle name. + * @param userId User Id. + * @param flag Keep-alive flag. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t SetApplicationKeepAlive(const std::string &bundleName, int32_t userId, bool flag) override; + + /** + * Get keep-alive applications. + * @param appType Application type. + * @param userId User Id. + * @param list List of Keep-alive information. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t QueryKeepAliveApplications(int32_t appType, int32_t userId, + std::vector &list) override; + + /** + * Set keep-alive flag for application under a specific user by EDM. + * @param bundleName Bundle name. + * @param userId User Id. + * @param flag Keep-alive flag. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t SetApplicationKeepAliveByEDM(const std::string &bundleName, int32_t userId, bool flag) override; + + /** + * Get keep-alive applications by EDM. + * @param appType Application type. + * @param userId User Id. + * @param list List of Keep-alive information. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t QueryKeepAliveApplicationsByEDM(int32_t appType, int32_t userId, + std::vector &list) override; + private: template int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); diff --git a/services/abilitymgr/include/ability_manager_service.h b/services/abilitymgr/include/ability_manager_service.h index f7c64d64ca..ece6ae4b94 100644 --- a/services/abilitymgr/include/ability_manager_service.h +++ b/services/abilitymgr/include/ability_manager_service.h @@ -34,6 +34,7 @@ #include "ability_info.h" #include "ability_manager_event_subscriber.h" #include "ability_manager_stub.h" +#include "ability_keep_alive_service.h" #include "ams_configuration_parameter.h" #include "app_debug_listener_interface.h" #include "app_exit_reason_helper.h" @@ -1819,6 +1820,46 @@ public: int32_t UpdateKeepAliveEnableState(const std::string &bundleName, const std::string &moduleName, const std::string &mainElement, bool updateEnable, int32_t userId); + bool IsInStatusBar(uint32_t accessTokenId); + + /** + * Set keep-alive flag for application under a specific user. + * @param bundleName Bundle name. + * @param userId User Id. + * @param flag Keep-alive flag. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t SetApplicationKeepAlive(const std::string &bundleName, int32_t userId, bool flag) override; + + /** + * Get keep-alive applications by EDM. + * @param appType Application type. + * @param userId User Id. + * @param list List of Keep-alive information. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t QueryKeepAliveApplications(int32_t appType, int32_t userId, + std::vector &list) override; + + /** + * Set keep-alive flag for application under a specific user by EDM. + * @param bundleName Bundle name. + * @param userId User Id. + * @param flag Keep-alive flag. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t SetApplicationKeepAliveByEDM(const std::string &bundleName, int32_t userId, bool flag) override; + + /** + * Get keep-alive applications by EDM. + * @param appType Application type. + * @param userId User Id. + * @param list List of Keep-alive information. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t QueryKeepAliveApplicationsByEDM(int32_t appType, int32_t userId, + std::vector &list) override; + // MSG 0 - 20 represents timeout message static constexpr uint32_t LOAD_TIMEOUT_MSG = 0; static constexpr uint32_t ACTIVE_TIMEOUT_MSG = 1; @@ -1852,6 +1893,8 @@ protected: void NotifyStartResidentProcess(std::vector &bundleInfos) override; + void NotifyStartKeepAliveProcess(std::vector &bundleInfos) override; + /** * @brief Notify abilityms app process pre cache * @param pid process pid. @@ -2027,6 +2070,8 @@ private: void StartResidentApps(int32_t userId); + void StartKeepAliveApps(int32_t userId); + void StartAutoStartupApps(); void RetryStartAutoStartupApps(const std::vector &infoList, int32_t retryCount); void SubscribeScreenUnlockedEvent(); diff --git a/services/abilitymgr/include/ability_manager_stub.h b/services/abilitymgr/include/ability_manager_stub.h index d29110c3d8..cd3af6b0ce 100644 --- a/services/abilitymgr/include/ability_manager_stub.h +++ b/services/abilitymgr/include/ability_manager_stub.h @@ -303,6 +303,10 @@ private: int32_t NotifyFrozenProcessByRSSInner(MessageParcel &data, MessageParcel &reply); int32_t CleanUIAbilityBySCBInner(MessageParcel &data, MessageParcel &reply); int32_t PreStartMissionInner(MessageParcel &data, MessageParcel &reply); + int32_t SetApplicationKeepAliveInner(MessageParcel &data, MessageParcel &reply); + int32_t QueryKeepAliveApplicationsInner(MessageParcel &data, MessageParcel &reply); + int32_t SetApplicationKeepAliveByEDMInner(MessageParcel &data, MessageParcel &reply); + int32_t QueryKeepAliveApplicationsByEDMInner(MessageParcel &data, MessageParcel &reply); int OnRemoteRequestInnerFirst(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); int OnRemoteRequestInnerSecond(uint32_t code, MessageParcel &data, @@ -343,6 +347,8 @@ private: MessageParcel &reply, MessageOption &option); int OnRemoteRequestInnerNineteenth(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + int OnRemoteRequestInnerTwentieth(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); int HandleOnRemoteRequestInnerFirst(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); int HandleOnRemoteRequestInnerSecond(uint32_t code, MessageParcel &data, diff --git a/services/abilitymgr/include/app_scheduler.h b/services/abilitymgr/include/app_scheduler.h index dff369aae9..4b25198c28 100644 --- a/services/abilitymgr/include/app_scheduler.h +++ b/services/abilitymgr/include/app_scheduler.h @@ -100,6 +100,8 @@ public: virtual void NotifyStartResidentProcess(std::vector &bundleInfos) {} + virtual void NotifyStartKeepAliveProcess(std::vector &bundleInfos) {} + /** * @brief Notify abilityms app process pre cache * @param pid process pid. @@ -597,6 +599,12 @@ protected: */ virtual void NotifyStartResidentProcess(std::vector &bundleInfos) override; + /** + * @brief Notify abilityms start keep-alive process. + * @param bundleInfos resident process bundle infos. + */ + virtual void NotifyStartKeepAliveProcess(std::vector &bundleInfos) override; + /** * @brief Notify abilityms app process OnRemoteDied * @param abilityTokens abilities in died process. diff --git a/services/abilitymgr/include/keep_alive/ability_keep_alive_data_manager.h b/services/abilitymgr/include/keep_alive/ability_keep_alive_data_manager.h index c120ee3534..7e046c3dba 100644 --- a/services/abilitymgr/include/keep_alive/ability_keep_alive_data_manager.h +++ b/services/abilitymgr/include/keep_alive/ability_keep_alive_data_manager.h @@ -43,8 +43,8 @@ private: ~AbilityKeepAliveDataManager(); DistributedKv::Status GetKvStore(); bool CheckKvStore(); - DistributedKv::Value ConvertKeepAliveStatusToValue(bool isKeepAlive); - void ConvertKeepAliveStatusFromValue(const DistributedKv::Value &value, bool &isKeepAlive); + DistributedKv::Value ConvertKeepAliveStatusToValue(KeepAliveSetter setter); + void ConvertKeepAliveStatusFromValue(const DistributedKv::Value &value, KeepAliveSetter &setter); DistributedKv::Key ConvertKeepAliveDataToKey(const KeepAliveInfo &info); KeepAliveInfo ConvertKeepAliveInfoFromKey(const DistributedKv::Key &key); bool IsEqual(const DistributedKv::Key &key, const KeepAliveInfo &info); diff --git a/services/abilitymgr/include/keep_alive/ability_keep_alive_service.h b/services/abilitymgr/include/keep_alive/ability_keep_alive_service.h index c84497c5c9..d0121a0c09 100644 --- a/services/abilitymgr/include/keep_alive/ability_keep_alive_service.h +++ b/services/abilitymgr/include/keep_alive/ability_keep_alive_service.h @@ -26,12 +26,9 @@ namespace OHOS { namespace AbilityRuntime { -class AbilityKeepAliveService : public std::enable_shared_from_this { +class AbilityKeepAliveService { public: - explicit AbilityKeepAliveService(); - - virtual ~AbilityKeepAliveService(); - + static AbilityKeepAliveService &GetInstance(); /** * @brief Set every application keep alive state. * @param info The keep-alive info,include bundle name, module name, ability name. @@ -49,31 +46,13 @@ public: */ int32_t QueryKeepAliveApplications(int32_t userId, int32_t appType, std::vector &infoList); - /** - * @brief Set application keep alive state by EDM. - * @param info The keep-alive info, include bundle name, module name, ability name. - * @param flag Indicates whether to keep alive for application. - * @return Returns ERR_OK on success, others on failure. - */ - int32_t SetApplicationKeepAliveByEDM(KeepAliveInfo &info, bool flag); - - /** - * @brief Query keep-alive applications by EDM. - * @param userId User id. - * @param appType App type. - * @param infoList Output parameters, return keep-alive info list. - * @return Returns ERR_OK on success, others on failure. - */ - int32_t QueryKeepAliveApplicationsByEDM(int32_t userId, int32_t appType, std::vector &infoList); - /** * @brief Query if bundle is keep-alive. * @param bundleName The bundle name. * @param userId User id. - * @param isKeepAlive The return flag indicates whether the bundle is keep-alive. - * @return Returns ERR_OK on success, others on failure. + * @return Returns true on app keep alive, false otherwise. */ - int32_t GetKeepAliveProcessEnable(const std::string &bundleName, int32_t userId, bool &isKeepAlive); + bool IsKeepAliveApp(const std::string &bundleName, int32_t userId); /** * @brief Get keep-alive applications without permissions. @@ -83,12 +62,24 @@ public: */ int32_t GetKeepAliveApplications(int32_t userId, std::vector &infoList); + /** + * @brief Query if bundle is keep-alive. + * @param bundleName The bundle name. + * @param userId User id. + * @param isByEDM The flag indicates whether it's user or system who sets the flag. + * @param isKeepAlive The return flag indicates whether the bundle is keep-alive. + * @return Returns ERR_OK on success, others on failure. + */ + bool CanSetKeepAlive(const std::string &bundleName, int32_t userId, bool isByEDM, bool &isKeepAlive); + private: - int32_t CheckPermission(); - int32_t CheckPermissionForEDM(); + AbilityKeepAliveService(); + ~AbilityKeepAliveService(); + void GetValidUserId(int32_t &userId); int32_t SetKeepAliveTrue(const KeepAliveInfo &info); int32_t CancelKeepAlive(const KeepAliveInfo &info); + DISALLOW_COPY_AND_MOVE(AbilityKeepAliveService); }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/services/abilitymgr/include/keep_alive/keep_alive_process_manager.h b/services/abilitymgr/include/keep_alive/keep_alive_process_manager.h index 11c590da7d..c972d55c6f 100644 --- a/services/abilitymgr/include/keep_alive/keep_alive_process_manager.h +++ b/services/abilitymgr/include/keep_alive/keep_alive_process_manager.h @@ -40,9 +40,15 @@ struct KeepAliveAbilityInfo { * @class KeepAliveProcessManager * KeepAliveProcessManager */ -class KeepAliveProcessManager : public std::enable_shared_from_this { - DECLARE_DELAYED_SINGLETON(KeepAliveProcessManager) +class KeepAliveProcessManager { public: + /** + * Get the instance of KeepAliveProcessManager. + * + * @return Returns the instance of KeepAliveProcessManager. + */ + static KeepAliveProcessManager &GetInstance(); + /** * Set the enable flag for keep-alive processes. * @@ -102,8 +108,11 @@ public: void StartFailedKeepAliveAbilities(); private: - void UpdateKeepAliveProcessesStatus(const AppExecFwk::BundleInfo &bundleInfo, int32_t userId, - bool localEnable, bool updateEnable); + KeepAliveProcessManager(); + ~KeepAliveProcessManager(); + + int32_t CheckPermission(); + int32_t CheckPermissionForEDM(); void AddFailedKeepAliveAbility(const std::string &bundleName, const std::string &moduleName, const std::string &abilityName, int32_t userId); void StartKeepAliveProcessWithMainElementPerBundle(const AppExecFwk::BundleInfo &bundleInfo, @@ -115,11 +124,10 @@ private: bool IsRunningAppInStatusBar(std::shared_ptr abilityMgr, const AppExecFwk::BundleInfo &bundleInfo); - std::shared_ptr abilityKeepAliveService_; - std::mutex failedKeepAliveAbilityInfoMutex_; std::list failedKeepAliveAbilityInfos_; std::atomic_bool unlockedAfterBoot_ = false; + DISALLOW_COPY_AND_MOVE(KeepAliveProcessManager); }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/resident_process/resident_process_manager.h b/services/abilitymgr/include/resident_process/resident_process_manager.h index c2f446cc69..dbdf02788b 100644 --- a/services/abilitymgr/include/resident_process/resident_process_manager.h +++ b/services/abilitymgr/include/resident_process/resident_process_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -98,7 +98,10 @@ public: private: void UpdateResidentProcessesStatus(const std::string &bundleName, bool localEnable, bool updateEnable); void AddFailedResidentAbility(const std::string &bundleName, const std::string &abilityName, int32_t userId); - void NotifyDisableResidentProcess(const std::vector &bundleInfos, int32_t userId); + void StartResidentProcessWithMainElementPerBundle(const AppExecFwk::BundleInfo &bundleInfo, + size_t index, std::set &needEraseIndexSet, int32_t userId); + void StartResidentProcessWithMainElementPerBundleHap(const AppExecFwk::HapModuleInfo &hapModuleInfo, + const std::string &processName, size_t index, std::set &needEraseIndexSet, int32_t userId); std::mutex residentAbilityInfoMutex_; std::list residentAbilityInfos_; diff --git a/services/abilitymgr/include/scene_board/status_bar_delegate_manager.h b/services/abilitymgr/include/scene_board/status_bar_delegate_manager.h index 7caee23e04..4e16e7cc04 100644 --- a/services/abilitymgr/include/scene_board/status_bar_delegate_manager.h +++ b/services/abilitymgr/include/scene_board/status_bar_delegate_manager.h @@ -30,6 +30,7 @@ public: int32_t RegisterStatusBarDelegate(sptr delegate); bool IsCallerInStatusBar(); + bool IsInStatusBar(uint32_t accessTokenId); int32_t DoProcessAttachment(std::shared_ptr abilityRecord); int32_t DoCallerProcessAttachment(std::shared_ptr abilityRecord); diff --git a/services/abilitymgr/include/scene_board/ui_ability_lifecycle_manager.h b/services/abilitymgr/include/scene_board/ui_ability_lifecycle_manager.h index af933622b2..c6307f8ca4 100644 --- a/services/abilitymgr/include/scene_board/ui_ability_lifecycle_manager.h +++ b/services/abilitymgr/include/scene_board/ui_ability_lifecycle_manager.h @@ -345,8 +345,11 @@ public: int32_t UpdateSessionInfoBySCB(std::list &sessionInfos, std::vector &sessionIds); int32_t RegisterStatusBarDelegate(sptr delegate); + bool IsCallerInStatusBar(); + bool IsInStatusBar(uint32_t accessTokenId); + int32_t TryPrepareTerminateByPids(const std::vector& pids); int ChangeAbilityVisibility(sptr token, bool isShow); diff --git a/services/abilitymgr/include/utils/keep_alive_utils.h b/services/abilitymgr/include/utils/keep_alive_utils.h new file mode 100644 index 0000000000..be9f99ce4f --- /dev/null +++ b/services/abilitymgr/include/utils/keep_alive_utils.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_ABILITY_RUNTIME_KEEP_ALIVE_UTILS_H +#define OHOS_ABILITY_RUNTIME_KEEP_ALIVE_UTILS_H + +#include "bundle_info.h" + +namespace OHOS { +namespace AAFwk { +/** + * @class KeepAliveType + * defines what type of keep-alive. + */ +enum class KeepAliveType : int32_t { + UNSPECIFIED = -1, + RESIDENT_PROCESS = 0, + THIRD_PARTY = 1, +}; + +/** + * @class KeepAliveUtils + * provides keep-alive utilities. + */ +class KeepAliveUtils final { +public: + /** + * CheckMainElement, check main element. + * + * @param bundleInfos The list of bundle info. + * @param userId User id. + * @return Whether or not the hap module has the main element. + */ + static void NotifyDisableKeepAliveProcesses(const std::vector &bundleInfos, + int32_t userId); + + /** + * IsKeepAliveBundle, check if bundle is keep-alive. + * + * @param bundleInfo The bundle info. + * @param userId User id. + * @param type The returned type of keep-alive. + * @return Whether or not the bundle is keep-alive. + */ + static bool IsKeepAliveBundle(const AppExecFwk::BundleInfo &bundleInfo, int32_t userId, KeepAliveType &type); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_KEEP_ALIVE_UTILS_H diff --git a/services/abilitymgr/include/utils/main_element_utils.h b/services/abilitymgr/include/utils/main_element_utils.h index 33f956e91c..3de656d971 100644 --- a/services/abilitymgr/include/utils/main_element_utils.h +++ b/services/abilitymgr/include/utils/main_element_utils.h @@ -32,13 +32,14 @@ public: * @param hapModuleInfo The hap module info. * @param processName The process name. * @param mainElement The returned main element. - * @param needEraseIndexSet The returned set of indices that need to be erased. - * @param bundleInfoIndex The index of the bundle info. + * @param isDataAbility The returned flag indicates whether the module contains data ability. + * @param uri Returned URI of the data ability. * @param userId User id. * @return Whether or not the hap module has the main element. */ - static bool CheckMainElement(const AppExecFwk::HapModuleInfo &hapModuleInfo, const std::string &processName, - std::string &mainElement, std::set &needEraseIndexSet, size_t bundleInfoIndex, int32_t userId = 0); + static bool CheckMainElement(const AppExecFwk::HapModuleInfo &hapModuleInfo, + const std::string &processName, std::string &mainElement, bool &isDataAbility, + std::string &uriStr, int32_t userId = 0); /** * UpdateMainElement, update main element. @@ -51,6 +52,33 @@ public: */ static void UpdateMainElement(const std::string &bundleName, const std::string &moduleName, const std::string &mainElement, bool updateEnable, int32_t userId); + + /** + * CheckMainUIAbility, check if bundle has main UIAbility. + * + * @param bundleInfo The bundle info. + * @param mainElementName The returned main element name. + * @return Whether or not the bundle has the main element. + */ + static bool CheckMainUIAbility(const AppExecFwk::BundleInfo &bundleInfo, std::string& mainElementName); + + /** + * CheckStatusBarAbility, check if bundle has status bar ability. + * + * @param bundleInfo The bundle info. + * @return Whether or not the bundle has a status bar ability. + */ + static bool CheckStatusBarAbility(const AppExecFwk::BundleInfo &bundleInfo); + + /** + * GetMainUIAbilityAccessTokenId, get the access token id of the main uiability. + * + * @param bundleInfo The bundle info. + * @param mainElementName The main element name. + * @param accessTokenId The returned access token id. + */ + static void GetMainUIAbilityAccessTokenId(const AppExecFwk::BundleInfo &bundleInfo, + const std::string &mainElementName, uint32_t &accessTokenId); }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/libabilityms.map b/services/abilitymgr/libabilityms.map index a4d90394f4..f00a26747c 100644 --- a/services/abilitymgr/libabilityms.map +++ b/services/abilitymgr/libabilityms.map @@ -61,6 +61,11 @@ *ImplicitStartProcessor*; *InnerMissionInfo*; *InsightIntentUtils*; + *JsonUtils*; + *KeepAliveAppType*; + *KeepAliveInfo*; + *KeepAliveSetter*; + *KeepAliveUtils*; *LaunchParam*; *LifeCycleStateInfo*; *Mission*; diff --git a/services/abilitymgr/src/ability_auto_startup_data_manager.cpp b/services/abilitymgr/src/ability_auto_startup_data_manager.cpp index bae7e5525d..878d046a7e 100644 --- a/services/abilitymgr/src/ability_auto_startup_data_manager.cpp +++ b/services/abilitymgr/src/ability_auto_startup_data_manager.cpp @@ -19,6 +19,7 @@ #include "accesstoken_kit.h" #include "hilog_tag_wrapper.h" +#include "json_utils.h" #include "os_account_manager_wrapper.h" namespace OHOS { @@ -435,30 +436,6 @@ AutoStartupInfo AbilityAutoStartupDataManager::ConvertAutoStartupInfoFromKeyAndV return info; } -bool AbilityAutoStartupDataManager::IsEqual( - nlohmann::json &jsonObject, const std::string &key, const std::string &value, bool checkEmpty) -{ - if (jsonObject.contains(key) && jsonObject[key].is_string()) { - std::string jsonValue = jsonObject.at(key).get(); - if (checkEmpty && !jsonValue.empty() && jsonValue != value) { - return false; - } else if (value != jsonValue) { - return false; - } - } - return true; -} - -bool AbilityAutoStartupDataManager::IsEqual(nlohmann::json &jsonObject, const std::string &key, int32_t value) -{ - if (jsonObject.contains(key) && jsonObject[key].is_number()) { - if (value != jsonObject.at(key).get()) { - return false; - } - } - return true; -} - bool AbilityAutoStartupDataManager::IsEqual(const DistributedKv::Key &key, const AutoStartupInfo &info) { nlohmann::json jsonObject = nlohmann::json::parse(key.ToString(), nullptr, false); @@ -467,12 +444,12 @@ bool AbilityAutoStartupDataManager::IsEqual(const DistributedKv::Key &key, const return false; } - if (!IsEqual(jsonObject, JSON_KEY_BUNDLE_NAME, info.bundleName) - || !IsEqual(jsonObject, JSON_KEY_ABILITY_NAME, info.abilityName) - || !IsEqual(jsonObject, JSON_KEY_MODULE_NAME, info.moduleName, true) - || !IsEqual(jsonObject, JSON_KEY_APP_CLONE_INDEX, info.appCloneIndex) - || !IsEqual(jsonObject, JSON_KEY_ACCESS_TOKENID, info.accessTokenId) - || !IsEqual(jsonObject, JSON_KEY_USERID, info.userId)) { + if (!AAFwk::JsonUtils::GetInstance().IsEqual(jsonObject, JSON_KEY_BUNDLE_NAME, info.bundleName) + || !AAFwk::JsonUtils::GetInstance().IsEqual(jsonObject, JSON_KEY_ABILITY_NAME, info.abilityName) + || !AAFwk::JsonUtils::GetInstance().IsEqual(jsonObject, JSON_KEY_MODULE_NAME, info.moduleName, true) + || !AAFwk::JsonUtils::GetInstance().IsEqual(jsonObject, JSON_KEY_APP_CLONE_INDEX, info.appCloneIndex) + || !AAFwk::JsonUtils::GetInstance().IsEqual(jsonObject, JSON_KEY_ACCESS_TOKENID, info.accessTokenId) + || !AAFwk::JsonUtils::GetInstance().IsEqual(jsonObject, JSON_KEY_USERID, info.userId)) { return false; } return true; diff --git a/services/abilitymgr/src/ability_manager_proxy.cpp b/services/abilitymgr/src/ability_manager_proxy.cpp index dd6b3f91c4..d29745fde7 100644 --- a/services/abilitymgr/src/ability_manager_proxy.cpp +++ b/services/abilitymgr/src/ability_manager_proxy.cpp @@ -5711,5 +5711,147 @@ bool AbilityManagerProxy::UpdateAssociateConfigInner(const std::map &list) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "writeInterfaceToken fail"); + return INNER_ERR; + } + + if (!data.WriteInt32(appType)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "faled to write appType"); + return ERR_INVALID_VALUE; + } + + if (!data.WriteInt32(userId)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "faled to write userID"); + return ERR_INVALID_VALUE; + } + + MessageParcel reply; + MessageOption option; + auto ret = SendRequest(AbilityManagerInterfaceCode::GET_APPLICATIONS_KEEP_ALIVE, + data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "request error: %{public}d", ret); + return ret; + } + + ret = GetParcelableInfos(reply, list); + if (ret != NO_ERROR) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "GetParcelableInfos error: %{public}d", ret); + return ret; + } + + return reply.ReadInt32(); +} + +int32_t AbilityManagerProxy::SetApplicationKeepAliveByEDM(const std::string &bundleName, int32_t userId, bool flag) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "writeInterfaceToken fail"); + return INNER_ERR; + } + + if (!data.WriteString(bundleName)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "faled to write bundleName"); + return ERR_INVALID_VALUE; + } + + if (!data.WriteInt32(userId)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "faled to write userID"); + return ERR_INVALID_VALUE; + } + + if (!data.WriteBool(flag)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "faled to write flag"); + return ERR_INVALID_VALUE; + } + + MessageParcel reply; + MessageOption option; + auto ret = SendRequest(AbilityManagerInterfaceCode::SET_APPLICATION_KEEP_ALLIVE_BY_EDM, + data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "request error: %{public}d", ret); + return ret; + } + return reply.ReadInt32(); +} + +int32_t AbilityManagerProxy::QueryKeepAliveApplicationsByEDM(int32_t appType, int32_t userId, + std::vector &list) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "writeInterfaceToken fail"); + return INNER_ERR; + } + + if (!data.WriteInt32(appType)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "faled to write appType"); + return ERR_INVALID_VALUE; + } + + if (!data.WriteInt32(userId)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "faled to write userID"); + return ERR_INVALID_VALUE; + } + + MessageParcel reply; + MessageOption option; + auto ret = SendRequest(AbilityManagerInterfaceCode::GET_APPLICATIONS_KEEP_ALIVE_BY_EDM, + data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "request error: %{public}d", ret); + return ret; + } + + ret = GetParcelableInfos(reply, list); + if (ret != NO_ERROR) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "GetParcelableInfos error: %{public}d", ret); + return ret; + } + + return reply.ReadInt32(); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_service.cpp b/services/abilitymgr/src/ability_manager_service.cpp index b0410f45ad..46b07c9268 100644 --- a/services/abilitymgr/src/ability_manager_service.cpp +++ b/services/abilitymgr/src/ability_manager_service.cpp @@ -18,7 +18,6 @@ #include "ability_background_connection.h" #include "ability_connect_manager.h" #include "ability_manager_radar.h" -#include "ability_resident_process_rdb.h" #include "accesstoken_kit.h" #include "ability_manager_xcollie.h" #include "app_exception_handler.h" @@ -51,6 +50,8 @@ #include "int_wrapper.h" #include "ipc_skeleton.h" #include "iservice_registry.h" +#include "keep_alive_process_manager.h" +#include "keep_alive_utils.h" #include "mock_session_manager_service.h" #include "modal_system_dialog/modal_system_dialog_ui_extension.h" #include "modal_system_ui_extension.h" @@ -185,6 +186,8 @@ constexpr const char* ABILITYMS_ENABLE_UISERVICE = "const.abilityms.enable_uiser constexpr const char* DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag"; +constexpr char PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED[] = "const.product.enterprisefeature.setting.enabled"; + constexpr int32_t RESOURCE_SCHEDULE_UID = 1096; constexpr int32_t UPDATE_CONFIG_FLAG_COVER = 1; constexpr int32_t UPDATE_CONFIG_FLAG_APPEND = 2; @@ -2372,18 +2375,22 @@ void AbilityManagerService::AppUpgradeCompleted(const std::string &bundleName, i return; } - bool keepAliveEnable = bundleInfo.isKeepAlive; - AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleInfo.name, keepAliveEnable); - if (!keepAliveEnable) { - TAG_LOGW(AAFwkTag::ABILITYMGR, "not resident application"); + KeepAliveType type = KeepAliveType::UNSPECIFIED; + if (!KeepAliveUtils::IsKeepAliveBundle(bundleInfo, userId, type)) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "not keep-alive application"); return; } std::vector bundleInfos = { bundleInfo }; - DelayedSingleton::GetInstance()->StartResidentProcessWithMainElement(bundleInfos, userId); - - if (!bundleInfos.empty()) { - DelayedSingleton::GetInstance()->StartResidentProcess(bundleInfos); + if (type == KeepAliveType::THIRD_PARTY) { + KeepAliveProcessManager::GetInstance().StartKeepAliveProcessWithMainElement(bundleInfos, userId); + } else if (type == KeepAliveType::RESIDENT_PROCESS) { + auto residentProcessManager = DelayedSingleton::GetInstance(); + CHECK_POINTER(residentProcessManager); + residentProcessManager->StartResidentProcessWithMainElement(bundleInfos, userId); + if (!bundleInfos.empty()) { + residentProcessManager->StartResidentProcess(bundleInfos); + } } } @@ -6178,6 +6185,10 @@ void AbilityManagerService::OnAppStateChanged(const AppInfo &info) auto residentProcessMgr = DelayedSingleton::GetInstance(); CHECK_POINTER(residentProcessMgr); residentProcessMgr->OnAppStateChanged(info); + + if (system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) { + KeepAliveProcessManager::GetInstance().OnAppStateChanged(info); + } } std::shared_ptr AbilityManagerService::GetEventHandler() @@ -6534,9 +6545,9 @@ int AbilityManagerService::KillProcess(const std::string &bundleName, bool clear return GET_BUNDLE_INFO_FAILED; } - bool keepAliveEnable = bundleInfo.isKeepAlive; - AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleName, keepAliveEnable); - if (keepAliveEnable && DelayedSingleton::GetInstance()->IsMemorySizeSufficent()) { + KeepAliveType type; + if (KeepAliveUtils::IsKeepAliveBundle(bundleInfo, userId, type) + && DelayedSingleton::GetInstance()->IsMemorySizeSufficent()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "no kill alive process"); return KILL_PROCESS_KEEP_ALIVE; } @@ -6588,6 +6599,8 @@ int32_t AbilityManagerService::UninstallAppInner(const std::string &bundleName, IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton:: GetInstance()->SetKeepAliveEnableState(bundleName, false, uid)); auto userId = uid / BASE_USER_RANGE; + IN_PROCESS_CALL_WITHOUT_RET( + KeepAliveProcessManager::GetInstance().SetApplicationKeepAlive(bundleName, userId, false, true)); auto connectManager = GetConnectManagerByUserId(userId); if (connectManager) { connectManager->UninstallApp(bundleName); @@ -6993,25 +7006,45 @@ void AbilityManagerService::StartResidentApps(int32_t userId) { TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps %{public}d", userId); ConnectServices(); + auto residentProcessManager = DelayedSingleton::GetInstance(); + CHECK_POINTER(residentProcessManager); std::vector bundleInfos; - if (!DelayedSingleton::GetInstance()->GetResidentBundleInfosForUser(bundleInfos, userId)) { + if (!residentProcessManager->GetResidentBundleInfosForUser(bundleInfos, userId)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "get resident bundleinfos failed"); return; } - DelayedSingleton::GetInstance()->Init(); + residentProcessManager->Init(); TAG_LOGI(AAFwkTag::ABILITYMGR, "startResidentApps getBundleInfos size:%{public}zu", bundleInfos.size()); - DelayedSingleton::GetInstance()->StartResidentProcessWithMainElement(bundleInfos, userId); + residentProcessManager->StartResidentProcessWithMainElement(bundleInfos, userId); if (!bundleInfos.empty()) { #ifdef SUPPORT_GRAPHICS if (userId == U0_USER_ID) { WaitBootAnimationStart(); } #endif - DelayedSingleton::GetInstance()->StartResidentProcess(bundleInfos); + residentProcessManager->StartResidentProcess(bundleInfos); } } +void AbilityManagerService::StartKeepAliveApps(int32_t userId) +{ + if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) { + return; + } + TAG_LOGI(AAFwkTag::ABILITYMGR, "StartKeepAliveApps %{public}d", userId); + ConnectServices(); + std::vector bundleInfos; + if (!KeepAliveProcessManager::GetInstance().GetKeepAliveBundleInfosForUser( + bundleInfos, userId)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "get keep-alive bundle info failed"); + return; + } + TAG_LOGI(AAFwkTag::ABILITYMGR, "StartKeepAliveApps getBundleInfos size:%{public}zu", bundleInfos.size()); + + KeepAliveProcessManager::GetInstance().StartKeepAliveProcessWithMainElement(bundleInfos, userId); +} + void AbilityManagerService::StartAutoStartupApps() { TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); @@ -7510,6 +7543,18 @@ int AbilityManagerService::StopUser(int userId, const sptr &callb if (callback) { callback->OnStopUserDone(userId, ret); } + if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) { + return 0; + } + std::vector bundleInfos; + if (!KeepAliveProcessManager::GetInstance().GetKeepAliveBundleInfosForUser(bundleInfos, userId)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "get keep-alive bundle info failed"); + return 0; + } + for (const auto &bundleInfo : bundleInfos) { + IN_PROCESS_CALL_WITHOUT_RET(KeepAliveProcessManager::GetInstance().SetApplicationKeepAlive( + bundleInfo.name, userId, false, true)); + } return 0; } @@ -8110,7 +8155,13 @@ void AbilityManagerService::SwitchToUser(int32_t oldUserId, int32_t userId, sptr taskHandler_->SubmitTask([abilityMs = shared_from_this(), userId]() { TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps userId:%{public}d", userId); abilityMs->StartResidentApps(userId); + }); + if (system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) { + taskHandler_->SubmitTask([abilityMs = shared_from_this(), userId]() { + TAG_LOGI(AAFwkTag::ABILITYMGR, "StartKeepAliveApps userId:%{public}d", userId); + abilityMs->StartKeepAliveApps(userId); }); + } } if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && AmsConfigurationParameter::GetInstance().MultiUserType() != 0) { @@ -10436,15 +10487,17 @@ int32_t AbilityManagerService::CheckProcessOptions(const Want &want, const Start TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability with process options"); bool isEnable = AppUtils::GetInstance().IsStartOptionsWithProcessOptions(); - if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "not support process options"); - return ERR_CAPABILITY_NOT_SUPPORT; - } + CHECK_TRUE_RETURN_RET(!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable, + ERR_CAPABILITY_NOT_SUPPORT, "not support process options"); auto element = want.GetElement(); - if (element.GetAbilityName().empty() || want.GetAction().compare(ACTION_CHOOSE) == 0) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "not allow implicit start"); - return ERR_NOT_ALLOW_IMPLICIT_START; + CHECK_TRUE_RETURN_RET(element.GetAbilityName().empty() || want.GetAction().compare(ACTION_CHOOSE) == 0, + ERR_NOT_ALLOW_IMPLICIT_START, "not allow implicit start"); + + if (PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS_NAME) + && startOptions.processOptions->isRestartKeepAlive) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "restart keep-alive app."); + return ERR_OK; } int32_t appIndex = 0; @@ -10854,19 +10907,39 @@ void AbilityManagerService::NotifyStartResidentProcess(std::vector::GetInstance()->StartResidentProcessWithMainElement( + auto residentProcessMgr = DelayedSingleton::GetInstance(); + CHECK_POINTER(residentProcessMgr); + + residentProcessMgr->StartResidentProcessWithMainElement( bundleInfosForU0, U0_USER_ID); if (!bundleInfosForU0.empty()) { - DelayedSingleton::GetInstance()->StartResidentProcess(bundleInfosForU0); + residentProcessMgr->StartResidentProcess(bundleInfosForU0); } - DelayedSingleton::GetInstance()->StartResidentProcessWithMainElement( + residentProcessMgr->StartResidentProcessWithMainElement( bundleInfosForCurrentUser, currentUser); if (!bundleInfosForCurrentUser.empty()) { - DelayedSingleton::GetInstance()->StartResidentProcess(bundleInfosForCurrentUser); + residentProcessMgr->StartResidentProcess(bundleInfosForCurrentUser); } } +void AbilityManagerService::NotifyStartKeepAliveProcess(std::vector &bundleInfos) +{ + if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) { + return; + } + + auto userId = GetUserId(); + std::vector bundleInfosForCurrentUser; + for (const auto &item: bundleInfos) { + if (item.uid / BASE_USER_RANGE == userId) { + bundleInfosForCurrentUser.push_back(item); + } + } + + KeepAliveProcessManager::GetInstance().StartKeepAliveProcessWithMainElement(bundleInfosForCurrentUser, userId); +} + void AbilityManagerService::NotifyAppPreCache(int32_t pid, int32_t userId) { ForceTerminateServiceExtensionByPid(pid, userId); @@ -11034,10 +11107,7 @@ int32_t AbilityManagerService::SetResidentProcessEnabled(const std::string &bund } auto residentProcessManager = DelayedSingleton::GetInstance(); - if (residentProcessManager == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "get resident proces mgr null"); - return INNER_ERR; - } + CHECK_POINTER_AND_RETURN(residentProcessManager, INNER_ERR); std::string callerName; int32_t uid = 0; @@ -12357,5 +12427,39 @@ int32_t AbilityManagerService::UpdateKeepAliveEnableState(const std::string &bun } return ret; } + +bool AbilityManagerService::IsInStatusBar(uint32_t accessTokenId) +{ + auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid()); + CHECK_POINTER_AND_RETURN(uiAbilityManager, false); + + return uiAbilityManager->IsInStatusBar(accessTokenId); +} + +int32_t AbilityManagerService::SetApplicationKeepAlive(const std::string &bundleName, int32_t userId, bool flag) +{ + return KeepAliveProcessManager::GetInstance().SetApplicationKeepAlive( + bundleName, userId, flag); +} + +int32_t AbilityManagerService::QueryKeepAliveApplications(int32_t appType, int32_t userId, + std::vector &list) +{ + return KeepAliveProcessManager::GetInstance().QueryKeepAliveApplications( + appType, userId, list); +} + +int32_t AbilityManagerService::SetApplicationKeepAliveByEDM(const std::string &bundleName, int32_t userId, bool flag) +{ + return KeepAliveProcessManager::GetInstance().SetApplicationKeepAlive( + bundleName, userId, flag, true); +} + +int32_t AbilityManagerService::QueryKeepAliveApplicationsByEDM(int32_t appType, int32_t userId, + std::vector &list) +{ + return KeepAliveProcessManager::GetInstance().QueryKeepAliveApplications( + appType, userId, list, true); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp index 2a6fc369e7..a9e0893886 100644 --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -715,7 +715,6 @@ int AbilityManagerStub::OnRemoteRequestInnerEighteenth(uint32_t code, MessagePar return ERR_CODE_NOT_EXIST; } - int AbilityManagerStub::OnRemoteRequestInnerNineteenth(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { @@ -765,6 +764,25 @@ int AbilityManagerStub::OnRemoteRequestInnerNineteenth(uint32_t code, MessagePar return ERR_CODE_NOT_EXIST; } +int AbilityManagerStub::OnRemoteRequestInnerTwentieth(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + AbilityManagerInterfaceCode interfaceCode = static_cast(code); + if (interfaceCode == AbilityManagerInterfaceCode::SET_APPLICATION_KEEP_ALLIVE) { + return SetApplicationKeepAliveInner(data, reply); + } + if (interfaceCode == AbilityManagerInterfaceCode::GET_APPLICATIONS_KEEP_ALIVE) { + return QueryKeepAliveApplicationsInner(data, reply); + } + if (interfaceCode == AbilityManagerInterfaceCode::SET_APPLICATION_KEEP_ALLIVE_BY_EDM) { + return SetApplicationKeepAliveByEDMInner(data, reply); + } + if (interfaceCode == AbilityManagerInterfaceCode::GET_APPLICATIONS_KEEP_ALIVE_BY_EDM) { + return QueryKeepAliveApplicationsByEDMInner(data, reply); + } + return ERR_CODE_NOT_EXIST; +} + int AbilityManagerStub::OnRemoteRequestInner(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { @@ -868,6 +886,10 @@ int AbilityManagerStub::HandleOnRemoteRequestInnerSecond(uint32_t code, MessageP if (retCode != ERR_CODE_NOT_EXIST) { return retCode; } + retCode = OnRemoteRequestInnerTwentieth(code, data, reply, option); + if (retCode != ERR_CODE_NOT_EXIST) { + return retCode; + } return ERR_CODE_NOT_EXIST; } @@ -4093,5 +4115,69 @@ int32_t AbilityManagerStub::UpdateAssociateConfigListInner(MessageParcel &data, reply.WriteInt32(result); return NO_ERROR; } + +int AbilityManagerStub::SetApplicationKeepAliveInner(MessageParcel &data, MessageParcel &reply) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + std::string bundleName = data.ReadString(); + int32_t userId = data.ReadInt32(); + bool flag = data.ReadBool(); + int32_t result = SetApplicationKeepAlive(bundleName, userId, flag); + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return result; +} + +int AbilityManagerStub::QueryKeepAliveApplicationsInner(MessageParcel &data, MessageParcel &reply) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + int32_t appType = data.ReadInt32(); + int32_t userId = data.ReadInt32(); + std::vector list; + int32_t result = QueryKeepAliveApplications(appType, userId, list); + reply.WriteInt32(list.size()); + for (auto &it : list) { + if (!reply.WriteParcelable(&it)) { + return ERR_INVALID_VALUE; + } + } + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return result; +} + +int AbilityManagerStub::SetApplicationKeepAliveByEDMInner(MessageParcel &data, MessageParcel &reply) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + std::string bundleName = data.ReadString(); + int32_t userId = data.ReadInt32(); + bool flag = data.ReadBool(); + int32_t result = SetApplicationKeepAliveByEDM(bundleName, userId, flag); + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return result; +} + +int AbilityManagerStub::QueryKeepAliveApplicationsByEDMInner(MessageParcel &data, MessageParcel &reply) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + int32_t appType = data.ReadInt32(); + int32_t userId = data.ReadInt32(); + std::vector list; + int32_t result = QueryKeepAliveApplicationsByEDM(appType, userId, list); + reply.WriteInt32(list.size()); + for (auto &it : list) { + if (!reply.WriteParcelable(&it)) { + return ERR_INVALID_VALUE; + } + } + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return result; +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/ability_record.cpp b/services/abilitymgr/src/ability_record.cpp index 666410a3d9..bb07998321 100644 --- a/services/abilitymgr/src/ability_record.cpp +++ b/services/abilitymgr/src/ability_record.cpp @@ -32,6 +32,7 @@ #include "global_constant.h" #include "hitrace_meter.h" #include "image_source.h" +#include "keep_alive_process_manager.h" #include "multi_instance_utils.h" #include "os_account_manager_wrapper.h" #include "ui_service_extension_connection_constants.h" @@ -322,25 +323,18 @@ int AbilityRecord::LoadAbility(bool isShellCall) } std::string appName = abilityInfo_.applicationInfo.name; - if (appName.empty()) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "app name empty"); - return ERR_INVALID_VALUE; - } - - if (!CanRestartRootLauncher()) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "root launcher restart out of max"); - return ERR_INVALID_VALUE; - } + CHECK_TRUE_RETURN_RET(appName.empty(), ERR_INVALID_VALUE, "app name empty"); + CHECK_TRUE_RETURN_RET(!CanRestartRootLauncher(), ERR_INVALID_VALUE, "root launcher restart out of max"); if (isRestarting_) { restartTime_ = AbilityUtil::SystemTimeMillis(); } - sptr callerToken_ = nullptr; + sptr callerToken = nullptr; if (!callerList_.empty() && callerList_.back()) { auto caller = callerList_.back()->GetCaller(); if (caller) { - callerToken_ = caller->GetToken(); + callerToken = caller->GetToken(); } } @@ -348,22 +342,22 @@ int AbilityRecord::LoadAbility(bool isShellCall) want_.SetParam(ABILITY_OWNER_USERID, ownerMissionUserId_); AbilityRuntime::LoadParam loadParam; loadParam.abilityRecordId = recordId_; - if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - loadParam.isShellCall = isShellCall; - } else { - loadParam.isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall(); - } + loadParam.isShellCall = Rosen::SceneBoardJudgement::IsSceneBoardEnabled() ? isShellCall + : AAFwk::PermissionVerification::GetInstance()->IsShellCall(); loadParam.token = token_; - loadParam.preToken = callerToken_; + loadParam.preToken = callerToken; loadParam.instanceKey = instanceKey_; + want_.RemoveParam(Want::PARAM_APP_KEEP_ALIVE_ENABLED); + if (KeepAliveProcessManager::GetInstance().IsKeepAliveBundle(abilityInfo_.applicationInfo.bundleName, -1)) { + want_.SetParam(Want::PARAM_APP_KEEP_ALIVE_ENABLED, true); + loadParam.isKeepAlive = true; + } auto result = DelayedSingleton::GetInstance()->LoadAbility( loadParam, abilityInfo_, abilityInfo_.applicationInfo, want_); want_.RemoveParam(ABILITY_OWNER_USERID); want_.RemoveParam(Want::PARAMS_NEED_CHECK_CALLER_IS_EXIST); SetLoadState(AbilityLoadState::LOADING); - - auto isAttachDebug = DelayedSingleton::GetInstance()->IsAttachDebug(abilityInfo_.bundleName); - if (isAttachDebug) { + if (DelayedSingleton::GetInstance()->IsAttachDebug(abilityInfo_.bundleName)) { SetAttachDebug(true); } return result; diff --git a/services/abilitymgr/src/app_scheduler.cpp b/services/abilitymgr/src/app_scheduler.cpp index cc4be61718..2dd4dc0448 100644 --- a/services/abilitymgr/src/app_scheduler.cpp +++ b/services/abilitymgr/src/app_scheduler.cpp @@ -215,6 +215,13 @@ void AppScheduler::NotifyStartResidentProcess(std::vectorNotifyStartResidentProcess(bundleInfos); } +void AppScheduler::NotifyStartKeepAliveProcess(std::vector &bundleInfos) +{ + auto callback = callback_.lock(); + CHECK_POINTER(callback); + callback->NotifyStartKeepAliveProcess(bundleInfos); +} + void AppScheduler::OnAppRemoteDied(const std::vector> &abilityTokens) { auto callback = callback_.lock(); diff --git a/services/abilitymgr/src/keep_alive/ability_keep_alive_data_manager.cpp b/services/abilitymgr/src/keep_alive/ability_keep_alive_data_manager.cpp index 683360d78b..7d47322e95 100644 --- a/services/abilitymgr/src/keep_alive/ability_keep_alive_data_manager.cpp +++ b/services/abilitymgr/src/keep_alive/ability_keep_alive_data_manager.cpp @@ -17,10 +17,8 @@ #include -#include "accesstoken_kit.h" #include "hilog_tag_wrapper.h" #include "json_utils.h" -#include "os_account_manager_wrapper.h" namespace OHOS { namespace AbilityRuntime { @@ -32,7 +30,6 @@ const std::string JSON_KEY_BUNDLE_NAME = "bundleName"; const std::string JSON_KEY_USERID = "userId"; const std::string JSON_KEY_APP_TYPE = "appType"; const std::string JSON_KEY_SETTER = "setter"; -const std::string JSON_KEY_IS_KEEP_ALIVE = "isKeepAlive"; } // namespace const DistributedKv::AppId AbilityKeepAliveDataManager::APP_ID = { "keep_alive_storage" }; const DistributedKv::StoreId AbilityKeepAliveDataManager::STORE_ID = { "keep_alive_infos" }; @@ -114,7 +111,7 @@ int32_t AbilityKeepAliveDataManager::InsertKeepAliveData(const KeepAliveInfo &in } DistributedKv::Key key = ConvertKeepAliveDataToKey(info); - DistributedKv::Value value = ConvertKeepAliveStatusToValue(true); + DistributedKv::Value value = ConvertKeepAliveStatusToValue(info.setter); DistributedKv::Status status; { std::lock_guard lock(kvStorePtrMutex_); @@ -200,8 +197,9 @@ KeepAliveStatus AbilityKeepAliveDataManager::QueryKeepAliveData(const KeepAliveI kaStatus.code = ERR_NAME_NOT_FOUND; for (const auto &item : allEntries) { if (IsEqual(item.key, info)) { - ConvertKeepAliveStatusFromValue(item.value, kaStatus.isKeepAlive); + ConvertKeepAliveStatusFromValue(item.value, kaStatus.setter); kaStatus.code = ERR_OK; + break; } } @@ -238,35 +236,32 @@ int32_t AbilityKeepAliveDataManager::QueryKeepAliveApplications( if (!IsEqual(item.key, queryParam)) { continue; } - bool isKeepAlive; - ConvertKeepAliveStatusFromValue(item.value, isKeepAlive); - if (isKeepAlive) { - infoList.emplace_back(ConvertKeepAliveInfoFromKey(item.key)); - } + infoList.emplace_back(ConvertKeepAliveInfoFromKey(item.key)); } TAG_LOGD(AAFwkTag::KEEP_ALIVE, "InfoList.size: %{public}zu", infoList.size()); return ERR_OK; } -DistributedKv::Value AbilityKeepAliveDataManager::ConvertKeepAliveStatusToValue(bool isKeepAlive) +DistributedKv::Value AbilityKeepAliveDataManager::ConvertKeepAliveStatusToValue(KeepAliveSetter setter) { nlohmann::json jsonObject = nlohmann::json { - { JSON_KEY_IS_KEEP_ALIVE, isKeepAlive }, + { JSON_KEY_SETTER, setter }, }; DistributedKv::Value value(jsonObject.dump()); TAG_LOGD(AAFwkTag::KEEP_ALIVE, "value: %{public}s", value.ToString().c_str()); return value; } -void AbilityKeepAliveDataManager::ConvertKeepAliveStatusFromValue(const DistributedKv::Value &value, bool &isKeepAlive) +void AbilityKeepAliveDataManager::ConvertKeepAliveStatusFromValue(const DistributedKv::Value &value, + KeepAliveSetter &setter) { nlohmann::json jsonObject = nlohmann::json::parse(value.ToString(), nullptr, false); if (jsonObject.is_discarded()) { TAG_LOGE(AAFwkTag::KEEP_ALIVE, "parse jsonObject fail"); return; } - if (jsonObject.contains(JSON_KEY_IS_KEEP_ALIVE) && jsonObject[JSON_KEY_IS_KEEP_ALIVE].is_boolean()) { - isKeepAlive = jsonObject.at(JSON_KEY_IS_KEEP_ALIVE).get(); + if (jsonObject.contains(JSON_KEY_SETTER) && jsonObject[JSON_KEY_SETTER].is_number()) { + setter = KeepAliveSetter(jsonObject.at(JSON_KEY_SETTER).get()); } } @@ -333,10 +328,6 @@ bool AbilityKeepAliveDataManager::IsEqual(const DistributedKv::Key &key, const K return false; } - if (info.setter != KeepAliveSetter::UNSPECIFIED && - !AAFwk::JsonUtils::GetInstance().IsEqual(jsonObject, JSON_KEY_SETTER, static_cast(info.setter))) { - return false; - } return true; } } // namespace AbilityRuntime diff --git a/services/abilitymgr/src/keep_alive/ability_keep_alive_service.cpp b/services/abilitymgr/src/keep_alive/ability_keep_alive_service.cpp index 42e3260a46..5e34ffb3de 100644 --- a/services/abilitymgr/src/keep_alive/ability_keep_alive_service.cpp +++ b/services/abilitymgr/src/keep_alive/ability_keep_alive_service.cpp @@ -17,18 +17,16 @@ #include "ability_keep_alive_data_manager.h" #include "ability_manager_service.h" -#include "ability_util.h" #include "hilog_tag_wrapper.h" -#include "in_process_call_wrapper.h" -#include "main_element_utils.h" -#include "permission_constants.h" namespace OHOS { namespace AbilityRuntime { using namespace OHOS::AAFwk; -namespace { -constexpr char PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED[] = "const.product.enterprisefeature.setting.enabled"; -} // namespace +AbilityKeepAliveService &AbilityKeepAliveService::GetInstance() +{ + static AbilityKeepAliveService instance; + return instance; +} AbilityKeepAliveService::AbilityKeepAliveService() {} @@ -39,14 +37,8 @@ int32_t AbilityKeepAliveService::SetApplicationKeepAlive(KeepAliveInfo &info, bo TAG_LOGD(AAFwkTag::KEEP_ALIVE, "SetApplicationKeepAlive is called," " bundleName: %{public}s, userId: %{public}d, flag: %{public}d", info.bundleName.c_str(), info.userId, static_cast(flag)); - int32_t code = CheckPermission(); - if (code != ERR_OK) { - return code; - } GetValidUserId(info.userId); - info.appType = KeepAliveAppType::APP; - info.setter = KeepAliveSetter::USER; if (flag) { return SetKeepAliveTrue(info); @@ -56,36 +48,22 @@ int32_t AbilityKeepAliveService::SetApplicationKeepAlive(KeepAliveInfo &info, bo int32_t AbilityKeepAliveService::SetKeepAliveTrue(const KeepAliveInfo &info) { - auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper(); - if (bundleMgrHelper == nullptr) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "null bundleMgrHelper"); - return INNER_ERR; - } - - // check main element - AppExecFwk::BundleInfo bundleInfo; - if (!IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfo(info.bundleName, - AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, info.userId))) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "failed get bundle info"); - return ERR_TARGET_BUNDLE_NOT_EXIST; - } - std::string mainElementName; - if (!MainElementUtils::CheckMainUIAbility(bundleInfo, mainElementName)) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "bundle has no main uiability"); - return ERR_NO_MAIN_ABILITY; - } - KeepAliveStatus status = AbilityKeepAliveDataManager::GetInstance().QueryKeepAliveData(info); if (status.code != ERR_OK && status.code != ERR_NAME_NOT_FOUND) { TAG_LOGE(AAFwkTag::KEEP_ALIVE, "QueryKeepAliveData fail"); return status.code; } - if (status.code == ERR_OK) { - TAG_LOGI(AAFwkTag::KEEP_ALIVE, "app is already set"); - return status.code; + if (status.code == ERR_NAME_NOT_FOUND) { + return AbilityKeepAliveDataManager::GetInstance().InsertKeepAliveData(info); } + if (static_cast(status.setter) <= static_cast(info.setter)) { + TAG_LOGI(AAFwkTag::KEEP_ALIVE, "app is already set"); + return ERR_OK; + } + + (void)AbilityKeepAliveDataManager::GetInstance().DeleteKeepAliveData(info); return AbilityKeepAliveDataManager::GetInstance().InsertKeepAliveData(info); } @@ -97,69 +75,29 @@ int32_t AbilityKeepAliveService::CancelKeepAlive(const KeepAliveInfo &info) return status.code; } - if (!status.isKeepAlive) { + if (status.code == ERR_NAME_NOT_FOUND) { return ERR_TARGET_BUNDLE_NOT_EXIST; } + if (static_cast(status.setter) < static_cast(info.setter)) { + TAG_LOGE(AAFwkTag::KEEP_ALIVE, "app is set keep-alive by system, cannot unset by user"); + return CHECK_PERMISSION_FAILED; + } + return AbilityKeepAliveDataManager::GetInstance().DeleteKeepAliveData(info); } int32_t AbilityKeepAliveService::QueryKeepAliveApplications(int32_t userId, int32_t appType, std::vector &infoList) { - int32_t code = CheckPermission(); - if (code != ERR_OK) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "permission verification fail"); - return code; - } - GetValidUserId(userId); KeepAliveInfo queryParam; queryParam.userId = userId; queryParam.appType = KeepAliveAppType(appType); - queryParam.setter = KeepAliveSetter::USER; return AbilityKeepAliveDataManager::GetInstance().QueryKeepAliveApplications( queryParam, infoList); } -int32_t AbilityKeepAliveService::QueryKeepAliveApplicationsByEDM(int32_t userId, - int32_t appType, std::vector &infoList) -{ - int32_t code = CheckPermissionForEDM(); - if (code != ERR_OK) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "permission verification fail"); - return code; - } - - GetValidUserId(userId); - KeepAliveInfo queryParam; - queryParam.userId = userId; - queryParam.appType = KeepAliveAppType(appType); - queryParam.setter = KeepAliveSetter::SYSTEM; - return AbilityKeepAliveDataManager::GetInstance().QueryKeepAliveApplications( - queryParam, infoList); -} - -int32_t AbilityKeepAliveService::SetApplicationKeepAliveByEDM(KeepAliveInfo &info, bool flag) -{ - TAG_LOGD(AAFwkTag::KEEP_ALIVE, "SetApplicationKeepAliveByEDM is called," - " bundleName: %{public}s, userId: %{public}d, flag: %{public}d", - info.bundleName.c_str(), info.userId, static_cast(flag)); - int32_t code = CheckPermissionForEDM(); - if (code != ERR_OK) { - return code; - } - - GetValidUserId(info.userId); - info.appType = KeepAliveAppType::APP; - info.setter = KeepAliveSetter::SYSTEM; - - if (flag) { - return SetKeepAliveTrue(info); - } - return CancelKeepAlive(info); -} - void AbilityKeepAliveService::GetValidUserId(int32_t &userId) { if (userId >= 0) { @@ -176,54 +114,11 @@ void AbilityKeepAliveService::GetValidUserId(int32_t &userId) } } -int32_t AbilityKeepAliveService::CheckPermission() +bool AbilityKeepAliveService::IsKeepAliveApp(const std::string &bundleName, int32_t userId) { - if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "not supported"); - return ERR_CAPABILITY_NOT_SUPPORT; - } - - if (!PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "not use system-api"); - return ERR_NOT_SYSTEM_APP; - } - - if (!PermissionVerification::GetInstance()->VerifyCallingPermission( - PermissionConstants::PERMISSION_MANAGE_APP_KEEP_ALIVE)) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "verify PERMISSION_MANAGE_APP_KEEP_ALIVE fail"); - return CHECK_PERMISSION_FAILED; - } - - return ERR_OK; -} - -int32_t AbilityKeepAliveService::CheckPermissionForEDM() -{ - if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "not supported"); - return ERR_CAPABILITY_NOT_SUPPORT; - } - if (!PermissionVerification::GetInstance()->IsSACall() || - !PermissionVerification::GetInstance()->VerifyCallingPermission( - PermissionConstants::PERMISSION_MANAGE_APP_KEEP_ALIVE_INTERNAL)) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "verify PERMISSION_MANAGE_APP_KEEP_ALIVE_INTERNAL fail"); - return CHECK_PERMISSION_FAILED; - } - return ERR_OK; -} - -int32_t AbilityKeepAliveService::GetKeepAliveProcessEnable(const std::string &bundleName, int32_t userId, - bool &isKeepAlive) -{ - if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) { - TAG_LOGI(AAFwkTag::KEEP_ALIVE, "not supported"); - isKeepAlive = false; - return ERR_OK; - } - if (bundleName.empty()) { TAG_LOGE(AAFwkTag::KEEP_ALIVE, "bundle name empty"); - return ERR_INVALID_VALUE; + return false; } GetValidUserId(userId); @@ -231,20 +126,11 @@ int32_t AbilityKeepAliveService::GetKeepAliveProcessEnable(const std::string &bu info.bundleName = bundleName; info.userId = userId; KeepAliveStatus status = AbilityKeepAliveDataManager::GetInstance().QueryKeepAliveData(info); - if (status.code != ERR_OK) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "QueryKeepAliveData fail"); - return status.code; - } - isKeepAlive = status.isKeepAlive; - return ERR_OK; + return (status.code == ERR_OK); } int32_t AbilityKeepAliveService::GetKeepAliveApplications(int32_t userId, std::vector &infoList) { - if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) { - TAG_LOGI(AAFwkTag::KEEP_ALIVE, "not supported"); - return ERR_OK; - } KeepAliveInfo queryParam; queryParam.userId = userId; return AbilityKeepAliveDataManager::GetInstance().QueryKeepAliveApplications( diff --git a/services/abilitymgr/src/keep_alive/keep_alive_process_manager.cpp b/services/abilitymgr/src/keep_alive/keep_alive_process_manager.cpp index 7a8c742849..0319a1dc58 100644 --- a/services/abilitymgr/src/keep_alive/keep_alive_process_manager.cpp +++ b/services/abilitymgr/src/keep_alive/keep_alive_process_manager.cpp @@ -19,22 +19,27 @@ #include "ffrt.h" #include "keep_alive_utils.h" #include "main_element_utils.h" +#include "permission_constants.h" #include "process_options.h" namespace OHOS { namespace AAFwk { +namespace { +constexpr char PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED[] = "const.product.enterprisefeature.setting.enabled"; +constexpr char FOUNDATION_PROCESS_NAME[] = "foundation"; +} // namespace + constexpr int32_t CREATE_STATUS_BAR_TIMEOUT_SECONDS = 5; // 5s -KeepAliveProcessManager::KeepAliveProcessManager() +KeepAliveProcessManager &KeepAliveProcessManager::GetInstance() { - abilityKeepAliveService_ = std::make_shared(); + static KeepAliveProcessManager instance; + return instance; } -KeepAliveProcessManager::~KeepAliveProcessManager() -{ - abilityKeepAliveService_.reset(); - abilityKeepAliveService_ = nullptr; -} +KeepAliveProcessManager::KeepAliveProcessManager() {} + +KeepAliveProcessManager::~KeepAliveProcessManager() {} void KeepAliveProcessManager::StartKeepAliveProcessWithMainElement(std::vector &bundleInfos, int32_t userId) @@ -47,13 +52,7 @@ void KeepAliveProcessManager::StartKeepAliveProcessWithMainElement(std::vectorGetKeepAliveProcessEnable(bundleInfo.name, userId, keepAliveEnable); - if (!keepAliveEnable) { + if (!IsKeepAliveBundle(bundleInfo.name, userId)) { return; } @@ -68,8 +67,8 @@ void KeepAliveProcessManager::StartKeepAliveProcessWithMainElementPerBundle(cons return; } - ffrt::submit([self = shared_from_this(), bundleInfo, mainElementName, userId]() { - self->AfterStartKeepAliveApp(bundleInfo, mainElementName, userId); + ffrt::submit([bundleInfo, mainElementName, userId]() { + KeepAliveProcessManager::GetInstance().AfterStartKeepAliveApp(bundleInfo, mainElementName, userId); }); } @@ -82,7 +81,7 @@ int32_t KeepAliveProcessManager::StartAbility(const std::string &bundleName, con bundleName.c_str(), abilityName.c_str()); StartOptions options; options.processOptions = std::make_shared(); - options.processOptions->processMode = ProcessMode::ATTACH_TO_STATUS_BAR_ITEM; + options.processOptions->isRestartKeepAlive = true; options.processOptions->startupVisibility = StartupVisibility::STARTUP_HIDE; auto ret = IN_PROCESS_CALL(DelayedSingleton::GetInstance()->StartAbility(want, options, nullptr, userId, DEFAULT_INVAL_VALUE)); @@ -103,15 +102,13 @@ void KeepAliveProcessManager::AfterStartKeepAliveApp(const AppExecFwk::BundleInf abilityMgr = DelayedSingleton::GetInstance()]() { if (accessTokenId == 0) { TAG_LOGE(AAFwkTag::KEEP_ALIVE, "access token id is invalid"); - std::lock_guard lock(taskMutex); *isCanceled = true; taskCv.notify_all(); return; } - while (abilityMgr && !abilityMgr->IsInStatusBar(accessTokenId)) { + while (!abilityMgr || !abilityMgr->IsInStatusBar(accessTokenId)) { { - std::lock_guard lock(taskMutex); - if (*isCanceled) { + if (!isCanceled || *isCanceled) { TAG_LOGI(AAFwkTag::KEEP_ALIVE, "canceled in the middle"); return; } @@ -126,7 +123,7 @@ void KeepAliveProcessManager::AfterStartKeepAliveApp(const AppExecFwk::BundleInf taskCv.notify_all(); TAG_LOGI(AAFwkTag::KEEP_ALIVE, "finished checking status bar"); }); - auto condition = [&isCreated, &isCanceled] { return (isCreated || isCanceled); }; + auto condition = [&isCreated, isCanceled] { return (isCreated || (isCanceled && *isCanceled)); }; { std::unique_lock lock(taskMutex); TAG_LOGI(AAFwkTag::KEEP_ALIVE, "wait for condition"); @@ -134,16 +131,20 @@ void KeepAliveProcessManager::AfterStartKeepAliveApp(const AppExecFwk::BundleInf TAG_LOGE(AAFwkTag::KEEP_ALIVE, "attach status bar timeout"); *isCanceled = true; } + TAG_LOGI(AAFwkTag::KEEP_ALIVE, "wait is over"); } - if (isCreated) { - return; - } + if (isCreated) { return; } + TAG_LOGW(AAFwkTag::KEEP_ALIVE, "not created, cancel keep-alive"); SetApplicationKeepAlive(bundleInfo.name, userId, false, true); + (void)DelayedSingleton::GetInstance()->KillApplication(bundleInfo.name); } int32_t KeepAliveProcessManager::SetApplicationKeepAlive(const std::string &bundleName, int32_t userId, bool updateEnable, bool isByEDM) { + auto result = isByEDM ? CheckPermissionForEDM() : CheckPermission(); + CHECK_RET_RETURN_RET(result, "permission denied"); + CHECK_TRUE_RETURN_RET(bundleName.empty(), INVALID_PARAMETERS_ERR, "input parameter error"); auto bms = AbilityUtil::GetBundleManagerHelper(); @@ -151,31 +152,25 @@ int32_t KeepAliveProcessManager::SetApplicationKeepAlive(const std::string &bund auto abilityMgr = DelayedSingleton::GetInstance(); CHECK_POINTER_AND_RETURN(abilityMgr, INNER_ERR); + userId = userId < 0 ? abilityMgr->GetUserId() : userId; AppExecFwk::BundleInfo bundleInfo; - if (userId < 0) { - userId = abilityMgr->GetUserId(); - } - if (!IN_PROCESS_CALL(bms->GetBundleInfo( bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) { TAG_LOGE(AAFwkTag::KEEP_ALIVE, "get bundle info failed"); - return ERR_INVALID_VALUE; + return ERR_TARGET_BUNDLE_NOT_EXIST; } - CHECK_POINTER_AND_RETURN(abilityKeepAliveService_, INNER_ERR); - bool localEnable = false; - auto result = abilityKeepAliveService_->GetKeepAliveProcessEnable(bundleName, userId, localEnable); - CHECK_TRUE_RETURN_RET((result != ERR_OK && result != ERR_NAME_NOT_FOUND), - result, "GetKeepAliveProcessEnable failed"); - CHECK_TRUE_RETURN_RET((updateEnable == localEnable), - ERR_OK, "no change to the KeepAlive process setting properties"); - auto appMgrClient = DelayedSingleton::GetInstance(); CHECK_POINTER_AND_RETURN(appMgrClient, INNER_ERR); + + bool localEnable = IsKeepAliveBundle(bundleName, userId); if (updateEnable) { + std::string mainElementName; + CHECK_TRUE_RETURN_RET(!MainElementUtils::CheckMainUIAbility(bundleInfo, mainElementName), + ERR_NO_MAIN_ABILITY, "bundle has no main uiability"); bool isRunning = false; - result = IN_PROCESS_CALL(appMgrClient->IsApplicationRunning(bundleName, isRunning)); - CHECK_RET_RETURN_RET(result, "IsApplicationRunning failed"); + result = IN_PROCESS_CALL(appMgrClient->IsAppRunning(bundleName, 0, isRunning)); + CHECK_RET_RETURN_RET(result, "IsAppRunning failed"); CHECK_TRUE_RETURN_RET((!isRunning && !MainElementUtils::CheckStatusBarAbility(bundleInfo)), ERR_NO_STATUS_BAR_ABILITY, "app has no status bar"); CHECK_TRUE_RETURN_RET((isRunning && !IsRunningAppInStatusBar(abilityMgr, bundleInfo)), @@ -185,11 +180,16 @@ int32_t KeepAliveProcessManager::SetApplicationKeepAlive(const std::string &bund KeepAliveInfo info; info.bundleName = bundleName; info.userId = userId; - result = isByEDM ? abilityKeepAliveService_->SetApplicationKeepAliveByEDM(info, updateEnable) - : abilityKeepAliveService_->SetApplicationKeepAlive(info, updateEnable); - CHECK_RET_RETURN_RET(result, "KeepAlive process attribute update failed"); - IN_PROCESS_CALL_WITHOUT_RET(appMgrClient->SetKeepAliveEnableState(bundleName, updateEnable, 0)); - UpdateKeepAliveProcessesStatus(bundleInfo, userId, localEnable, updateEnable); + info.appType = bundleInfo.applicationInfo.isSystemApp ? KeepAliveAppType::SYSTEM : KeepAliveAppType::THIRD_PARTY; + info.setter = isByEDM ? KeepAliveSetter::SYSTEM : KeepAliveSetter::USER; + result = AbilityKeepAliveService::GetInstance().SetApplicationKeepAlive(info, updateEnable); + CHECK_RET_RETURN_RET(result, "set keep-alive failed"); + IN_PROCESS_CALL_WITHOUT_RET(appMgrClient->SetKeepAliveDkv(bundleName, updateEnable, 0)); + if (!updateEnable && localEnable) { + // just update + std::vector bundleInfos{ bundleInfo }; + KeepAliveUtils::NotifyDisableKeepAliveProcesses(bundleInfos, userId); + } return ERR_OK; } @@ -212,16 +212,6 @@ bool KeepAliveProcessManager::IsRunningAppInStatusBar(std::shared_ptrIsInStatusBar(accessTokenId); } -void KeepAliveProcessManager::UpdateKeepAliveProcessesStatus( - const AppExecFwk::BundleInfo &bundleInfo, int32_t userId, bool localEnable, bool updateEnable) -{ - if (!updateEnable && localEnable) { - // just update - std::vector bundleInfos{ bundleInfo }; - KeepAliveUtils::NotifyDisableKeepAliveProcesses(bundleInfos, userId); - } -} - void KeepAliveProcessManager::OnAppStateChanged(const AppInfo &info) { if (info.state != AppState::BEGIN) { @@ -248,43 +238,40 @@ void KeepAliveProcessManager::OnAppStateChanged(const AppInfo &info) return; } - if (abilityKeepAliveService_ == nullptr) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "abilityKeepAliveService_ null"); - return; - } - bool localEnable = false; - auto result = abilityKeepAliveService_->GetKeepAliveProcessEnable(bundleName, -1, localEnable); - if (result != ERR_OK) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "GetKeepAliveProcessEnable failed: %{public}d", result); + bool localEnable = IsKeepAliveBundle(bundleName, -1); + if (!localEnable) { return; } auto appMgrClient = DelayedSingleton::GetInstance(); if (appMgrClient == nullptr) { - TAG_LOGE(AAFwkTag::KEEP_ALIVE, "set keep alive enable state error"); + TAG_LOGE(AAFwkTag::KEEP_ALIVE, "appMgrClient is null"); return; } - IN_PROCESS_CALL_WITHOUT_RET(appMgrClient->SetKeepAliveEnableState(bundleName, localEnable, uid)); + IN_PROCESS_CALL_WITHOUT_RET(appMgrClient->SetKeepAliveDkv(bundleName, localEnable, uid)); } bool KeepAliveProcessManager::IsKeepAliveBundle(const std::string &bundleName, int32_t userId) { - CHECK_POINTER_AND_RETURN(abilityKeepAliveService_, false); - bool keepAliveEnable = false; - abilityKeepAliveService_->GetKeepAliveProcessEnable(bundleName, userId, keepAliveEnable); - return keepAliveEnable; + if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) { + TAG_LOGI(AAFwkTag::KEEP_ALIVE, "not supported"); + return false; + } + return AbilityKeepAliveService::GetInstance().IsKeepAliveApp(bundleName, userId); } bool KeepAliveProcessManager::GetKeepAliveBundleInfosForUser(std::vector &bundleInfos, int32_t userId) { + if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) { + TAG_LOGW(AAFwkTag::KEEP_ALIVE, "not supported"); + return false; + } auto bundleMgrHelper = DelayedSingleton::GetInstance(); CHECK_POINTER_AND_RETURN(bundleMgrHelper, false); - CHECK_POINTER_AND_RETURN(abilityKeepAliveService_, false); - std::vector infoList; - auto ret = abilityKeepAliveService_->GetKeepAliveApplications(userId, infoList); + auto ret = AbilityKeepAliveService::GetInstance().GetKeepAliveApplications(userId, infoList); if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::KEEP_ALIVE, "failed get keep_alive bundle info: %{public}d", ret); return false; @@ -341,11 +328,46 @@ void KeepAliveProcessManager::AddFailedKeepAliveAbility(const std::string &bundl int32_t KeepAliveProcessManager::QueryKeepAliveApplications(int32_t appType, int32_t userId, std::vector &infoList, bool isByEDM) { - CHECK_POINTER_AND_RETURN(abilityKeepAliveService_, INNER_ERR); - if (isByEDM) { - return abilityKeepAliveService_->QueryKeepAliveApplicationsByEDM(userId, appType, infoList); + auto result = isByEDM ? CheckPermissionForEDM() : CheckPermission(); + CHECK_RET_RETURN_RET(result, "permission denied"); + return AbilityKeepAliveService::GetInstance().QueryKeepAliveApplications(userId, appType, infoList); +} + +int32_t KeepAliveProcessManager::CheckPermission() +{ + if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) { + TAG_LOGE(AAFwkTag::KEEP_ALIVE, "not supported"); + return ERR_CAPABILITY_NOT_SUPPORT; } - return abilityKeepAliveService_->QueryKeepAliveApplications(userId, appType, infoList); + + if (!PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { + TAG_LOGE(AAFwkTag::KEEP_ALIVE, "not use system-api"); + return ERR_NOT_SYSTEM_APP; + } + + if (!PermissionVerification::GetInstance()->VerifyCallingPermission( + PermissionConstants::PERMISSION_MANAGE_APP_KEEP_ALIVE)) { + TAG_LOGE(AAFwkTag::KEEP_ALIVE, "verify PERMISSION_MANAGE_APP_KEEP_ALIVE fail"); + return CHECK_PERMISSION_FAILED; + } + + return ERR_OK; +} + +int32_t KeepAliveProcessManager::CheckPermissionForEDM() +{ + if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) { + TAG_LOGE(AAFwkTag::KEEP_ALIVE, "not supported"); + return ERR_CAPABILITY_NOT_SUPPORT; + } + if (PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS_NAME) + || (PermissionVerification::GetInstance()->IsSACall() + && PermissionVerification::GetInstance()->VerifyCallingPermission( + PermissionConstants::PERMISSION_MANAGE_APP_KEEP_ALIVE_INTERNAL))) { + return ERR_OK; + } + TAG_LOGE(AAFwkTag::KEEP_ALIVE, "verify PERMISSION_MANAGE_APP_KEEP_ALIVE_INTERNAL fail"); + return CHECK_PERMISSION_FAILED; } } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/process_options.cpp b/services/abilitymgr/src/process_options.cpp index ad712e0861..9c8d729e6f 100644 --- a/services/abilitymgr/src/process_options.cpp +++ b/services/abilitymgr/src/process_options.cpp @@ -24,6 +24,7 @@ bool ProcessOptions::ReadFromParcel(Parcel &parcel) processMode = static_cast(parcel.ReadInt32()); startupVisibility = static_cast(parcel.ReadInt32()); processName = parcel.ReadString(); + isRestartKeepAlive = parcel.ReadBool(); return true; } @@ -56,6 +57,10 @@ bool ProcessOptions::Marshalling(Parcel &parcel) const TAG_LOGE(AAFwkTag::ABILITYMGR, "ProcessName write failed"); return false; } + if (!parcel.WriteBool(isRestartKeepAlive)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "isRestartKeepAlive write failed"); + return false; + } return true; } diff --git a/services/abilitymgr/src/resident_process/resident_process_manager.cpp b/services/abilitymgr/src/resident_process/resident_process_manager.cpp index 9712ed3aa9..9e9c280cca 100644 --- a/services/abilitymgr/src/resident_process/resident_process_manager.cpp +++ b/services/abilitymgr/src/resident_process/resident_process_manager.cpp @@ -19,6 +19,7 @@ #include "ability_resident_process_rdb.h" #include "ability_util.h" #include "ffrt.h" +#include "keep_alive_utils.h" #include "main_element_utils.h" namespace OHOS { @@ -70,40 +71,7 @@ void ResidentProcessManager::StartResidentProcessWithMainElement(std::vector needEraseIndexSet; for (size_t i = 0; i < bundleInfos.size(); i++) { - if (userId != 0 && !AmsConfigurationParameter::GetInstance().InResidentWhiteList(bundleInfos[i].name)) { - needEraseIndexSet.insert(i); - continue; - } - std::string processName = bundleInfos[i].applicationInfo.process; - bool keepAliveEnable = bundleInfos[i].isKeepAlive; - // Check startup permissions - AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleInfos[i].name, keepAliveEnable); - if (!keepAliveEnable || processName.empty()) { - needEraseIndexSet.insert(i); - continue; - } - for (auto hapModuleInfo : bundleInfos[i].hapModuleInfos) { - std::string mainElement; - if (!MainElementUtils::CheckMainElement(hapModuleInfo, - processName, mainElement, needEraseIndexSet, i, userId)) { - continue; - } - - needEraseIndexSet.insert(i); - // startAbility - Want want; - want.SetElementName(hapModuleInfo.bundleName, mainElement); - ResidentAbilityInfoGuard residentAbilityInfoGuard(hapModuleInfo.bundleName, mainElement, userId); - TAG_LOGI(AAFwkTag::ABILITYMGR, "call, bundleName: %{public}s, mainElement: %{public}s", - hapModuleInfo.bundleName.c_str(), mainElement.c_str()); - auto ret = DelayedSingleton::GetInstance()->StartAbility(want, userId, - DEFAULT_INVAL_VALUE); - MainElementUtils::UpdateMainElement(hapModuleInfo.bundleName, - hapModuleInfo.name, mainElement, true, userId); - if (ret != ERR_OK) { - AddFailedResidentAbility(hapModuleInfo.bundleName, mainElement, userId); - } - } + StartResidentProcessWithMainElementPerBundle(bundleInfos[i], i, needEraseIndexSet, userId); } // delete item which process has been started. @@ -112,21 +80,59 @@ void ResidentProcessManager::StartResidentProcessWithMainElement(std::vector &bundleInfos, - int32_t userId) +void ResidentProcessManager::StartResidentProcessWithMainElementPerBundle(const AppExecFwk::BundleInfo &bundleInfo, + size_t index, std::set &needEraseIndexSet, int32_t userId) { - std::set needEraseIndexSet; // no use - for (size_t i = 0; i < bundleInfos.size(); i++) { - std::string processName = bundleInfos[i].applicationInfo.process; - for (const auto &hapModuleInfo : bundleInfos[i].hapModuleInfos) { - std::string mainElement; - if (!MainElementUtils::CheckMainElement(hapModuleInfo, - processName, mainElement, needEraseIndexSet, i, userId)) { - continue; - } - MainElementUtils::UpdateMainElement(hapModuleInfo.bundleName, - hapModuleInfo.name, mainElement, false, userId); + if (userId != 0 && !AmsConfigurationParameter::GetInstance().InResidentWhiteList(bundleInfo.name)) { + needEraseIndexSet.insert(index); + return; + } + std::string processName = bundleInfo.applicationInfo.process; + bool keepAliveEnable = bundleInfo.isKeepAlive; + // Check startup permissions + AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleInfo.name, keepAliveEnable); + if (!keepAliveEnable || processName.empty()) { + needEraseIndexSet.insert(index); + return; + } + for (auto hapModuleInfo : bundleInfo.hapModuleInfos) { + StartResidentProcessWithMainElementPerBundleHap(hapModuleInfo, processName, index, needEraseIndexSet, userId); + } +} + +void ResidentProcessManager::StartResidentProcessWithMainElementPerBundleHap( + const AppExecFwk::HapModuleInfo &hapModuleInfo, const std::string &processName, + size_t index, std::set &needEraseIndexSet, int32_t userId) +{ + std::string mainElement; + bool isDataAbility = false; + std::string uriStr; + if (!MainElementUtils::CheckMainElement(hapModuleInfo, + processName, mainElement, isDataAbility, uriStr, userId)) { + if (isDataAbility) { + // dataability, need use AcquireDataAbility + needEraseIndexSet.insert(index); + TAG_LOGI(AAFwkTag::ABILITYMGR, "call, mainElement: %{public}s, uri: %{public}s", + mainElement.c_str(), uriStr.c_str()); + Uri uri(uriStr); + DelayedSingleton::GetInstance()->AcquireDataAbility(uri, true, nullptr); } + return; + } + + needEraseIndexSet.insert(index); + // startAbility + Want want; + want.SetElementName(hapModuleInfo.bundleName, mainElement); + ResidentAbilityInfoGuard residentAbilityInfoGuard(hapModuleInfo.bundleName, mainElement, userId); + TAG_LOGI(AAFwkTag::ABILITYMGR, "call, bundleName: %{public}s, mainElement: %{public}s", + hapModuleInfo.bundleName.c_str(), mainElement.c_str()); + auto ret = DelayedSingleton::GetInstance()->StartAbility(want, userId, + DEFAULT_INVAL_VALUE); + MainElementUtils::UpdateMainElement(hapModuleInfo.bundleName, + hapModuleInfo.name, mainElement, true, userId); + if (ret != ERR_OK) { + AddFailedResidentAbility(hapModuleInfo.bundleName, mainElement, userId); } } @@ -211,7 +217,7 @@ void ResidentProcessManager::UpdateResidentProcessesStatus( } else if (!updateEnable && localEnable) { // just update std::vector bundleInfos{ bundleInfo }; - NotifyDisableResidentProcess(bundleInfos, userId); + KeepAliveUtils::NotifyDisableKeepAliveProcesses(bundleInfos, userId); } } } diff --git a/services/abilitymgr/src/scene_board/status_bar_delegate_manager.cpp b/services/abilitymgr/src/scene_board/status_bar_delegate_manager.cpp index 19c5d5ae83..4813071433 100644 --- a/services/abilitymgr/src/scene_board/status_bar_delegate_manager.cpp +++ b/services/abilitymgr/src/scene_board/status_bar_delegate_manager.cpp @@ -50,6 +50,21 @@ bool StatusBarDelegateManager::IsCallerInStatusBar() return isExist; } +bool StatusBarDelegateManager::IsInStatusBar(uint32_t accessTokenId) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + auto statusBarDelegate = GetStatusBarDelegate(); + CHECK_POINTER_AND_RETURN(statusBarDelegate, false); + bool isExist = false; + auto ret = statusBarDelegate->CheckIfStatusBarItemExists(accessTokenId, isExist); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "failed, ret: %{public}d", ret); + return false; + } + TAG_LOGI(AAFwkTag::ABILITYMGR, "isExist: %{public}d", isExist); + return isExist; +} + int32_t StatusBarDelegateManager::DoProcessAttachment(std::shared_ptr abilityRecord) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); diff --git a/services/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp b/services/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp index 5523a970ec..6cf6f77c26 100644 --- a/services/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp +++ b/services/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp @@ -2505,6 +2505,13 @@ bool UIAbilityLifecycleManager::IsCallerInStatusBar() return statusBarDelegateManager->IsCallerInStatusBar(); } +bool UIAbilityLifecycleManager::IsInStatusBar(uint32_t accessTokenId) +{ + auto statusBarDelegateManager = GetStatusBarDelegateManager(); + CHECK_POINTER_AND_RETURN(statusBarDelegateManager, false); + return statusBarDelegateManager->IsInStatusBar(accessTokenId); +} + int32_t UIAbilityLifecycleManager::DoProcessAttachment(std::shared_ptr abilityRecord) { auto statusBarDelegateManager = GetStatusBarDelegateManager(); @@ -2591,14 +2598,16 @@ int UIAbilityLifecycleManager::ChangeAbilityVisibility(sptr token auto sessionInfo = abilityRecord->GetSessionInfo(); CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE); - if (!IsCallerInStatusBar() && (sessionInfo->processOptions != nullptr && - !ProcessOptions::IsNoAttachmentMode(sessionInfo->processOptions->processMode))) { + if (!IsCallerInStatusBar() && sessionInfo->processOptions != nullptr && + !ProcessOptions::IsNoAttachmentMode(sessionInfo->processOptions->processMode) && + !sessionInfo->processOptions->isRestartKeepAlive) { TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not add to status bar"); return ERR_START_OPTIONS_CHECK_FAILED; } if (sessionInfo->processOptions == nullptr || (!ProcessOptions::IsAttachToStatusBarMode(sessionInfo->processOptions->processMode) && - !ProcessOptions::IsNoAttachmentMode(sessionInfo->processOptions->processMode))) { + !ProcessOptions::IsNoAttachmentMode(sessionInfo->processOptions->processMode) && + !sessionInfo->processOptions->isRestartKeepAlive)) { auto ret = DoCallerProcessAttachment(abilityRecord); if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "caller attach to status bar failed, ret: %{public}d", ret); diff --git a/services/abilitymgr/src/utils/keep_alive_utils.cpp b/services/abilitymgr/src/utils/keep_alive_utils.cpp new file mode 100644 index 0000000000..20c5fab15c --- /dev/null +++ b/services/abilitymgr/src/utils/keep_alive_utils.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "keep_alive_utils.h" + +#include "ability_resident_process_rdb.h" +#include "ability_util.h" +#include "keep_alive_process_manager.h" +#include "main_element_utils.h" + +namespace OHOS { +namespace AAFwk { +void KeepAliveUtils::NotifyDisableKeepAliveProcesses( + const std::vector &bundleInfos, int32_t userId) +{ + for (size_t i = 0; i < bundleInfos.size(); i++) { + std::string processName = bundleInfos[i].applicationInfo.process; + for (const auto &hapModuleInfo : bundleInfos[i].hapModuleInfos) { + std::string mainElement; + bool isDataAbility = false; + std::string uriStr; + if (!MainElementUtils::CheckMainElement(hapModuleInfo, + processName, mainElement, isDataAbility, uriStr, userId)) { + continue; + } + MainElementUtils::UpdateMainElement(hapModuleInfo.bundleName, + hapModuleInfo.name, mainElement, false, userId); + } + } +} + +bool KeepAliveUtils::IsKeepAliveBundle(const AppExecFwk::BundleInfo &bundleInfo, int32_t userId, KeepAliveType &type) +{ + if (KeepAliveProcessManager::GetInstance().IsKeepAliveBundle(bundleInfo.name, userId)) { + type = KeepAliveType::THIRD_PARTY; + return true; + } + + bool keepAliveEnable = bundleInfo.isKeepAlive; + AbilityRuntime::AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleInfo.name, keepAliveEnable); + if (keepAliveEnable) { + type = KeepAliveType::RESIDENT_PROCESS; + } + return keepAliveEnable; +} +} // namespace AAFwk +} // namespace OHOS diff --git a/services/abilitymgr/src/utils/main_element_utils.cpp b/services/abilitymgr/src/utils/main_element_utils.cpp index d58da29aec..ca91b78228 100644 --- a/services/abilitymgr/src/utils/main_element_utils.cpp +++ b/services/abilitymgr/src/utils/main_element_utils.cpp @@ -65,8 +65,8 @@ void MainElementUtils::UpdateMainElement(const std::string &bundleName, const st } bool MainElementUtils::CheckMainElement(const AppExecFwk::HapModuleInfo &hapModuleInfo, - const std::string &processName, std::string &mainElement, - std::set &needEraseIndexSet, size_t bundleInfoIndex, int32_t userId) + const std::string &processName, std::string &mainElement, bool &isDataAbility, + std::string &uriStr, int32_t userId) { if (!hapModuleInfo.isModuleJson) { // old application model @@ -87,16 +87,9 @@ bool MainElementUtils::CheckMainElement(const AppExecFwk::HapModuleInfo &hapModu return false; } - std::string uriStr; - bool getDataAbilityUri = DelayedSingleton::GetInstance()->GetDataAbilityUri( + isDataAbility = DelayedSingleton::GetInstance()->GetDataAbilityUri( hapModuleInfo.abilityInfos, mainElement, uriStr); - if (getDataAbilityUri) { - // dataability, need use AcquireDataAbility - TAG_LOGI(AAFwkTag::ABILITYMGR, "call, mainElement: %{public}s, uri: %{public}s", - mainElement.c_str(), uriStr.c_str()); - Uri uri(uriStr); - DelayedSingleton::GetInstance()->AcquireDataAbility(uri, true, nullptr); - needEraseIndexSet.insert(bundleInfoIndex); + if (isDataAbility) { return false; } } else { @@ -116,5 +109,61 @@ bool MainElementUtils::CheckMainElement(const AppExecFwk::HapModuleInfo &hapModu } return IsMainElementTypeOk(hapModuleInfo, mainElement, userId); } + +bool MainElementUtils::CheckMainUIAbility(const AppExecFwk::BundleInfo &bundleInfo, std::string& mainElementName) +{ + for (const auto& hapModuleInfo : bundleInfo.hapModuleInfos) { + if (hapModuleInfo.moduleType != AppExecFwk::ModuleType::ENTRY) { + continue; + } + + mainElementName = hapModuleInfo.mainElementName; + if (mainElementName.empty()) { + return false; + } + for (const auto &abilityInfo: hapModuleInfo.abilityInfos) { + if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) { + continue; + } + if (abilityInfo.name == mainElementName) { + return true; + } + } + break; + } + return false; +} + +bool MainElementUtils::CheckStatusBarAbility(const AppExecFwk::BundleInfo &bundleInfo) +{ + for (const auto& hapModuleInfo : bundleInfo.hapModuleInfos) { + for (const auto &extensionInfo: hapModuleInfo.extensionInfos) { + if (extensionInfo.type == AppExecFwk::ExtensionAbilityType::STATUS_BAR_VIEW) { + return true; + } + } + } + return false; +} + +void MainElementUtils::GetMainUIAbilityAccessTokenId(const AppExecFwk::BundleInfo &bundleInfo, + const std::string &mainElementName, uint32_t &accessTokenId) +{ + for (const auto& hapModuleInfo : bundleInfo.hapModuleInfos) { + if (hapModuleInfo.moduleType != AppExecFwk::ModuleType::ENTRY || + hapModuleInfo.mainElementName != mainElementName) { + continue; + } + + for (const auto &abilityInfo: hapModuleInfo.abilityInfos) { + if (abilityInfo.type != AppExecFwk::AbilityType::PAGE || + abilityInfo.name != mainElementName) { + continue; + } + accessTokenId = abilityInfo.applicationInfo.accessTokenId; + } + return; + } +} } // namespace AAFwk } // namespace OHOS diff --git a/services/appmgr/include/ams_mgr_scheduler.h b/services/appmgr/include/ams_mgr_scheduler.h index cda0259a57..67f66b3a89 100644 --- a/services/appmgr/include/ams_mgr_scheduler.h +++ b/services/appmgr/include/ams_mgr_scheduler.h @@ -370,6 +370,14 @@ public: */ void SetKeepAliveEnableState(const std::string &bundleName, bool enable, int32_t uid) override; + /** + * @brief Set non-resident keep-alive process status. + * @param bundleName The application bundle name. + * @param enable The current updated enable status. + * @param uid indicates user, 0 for all users + */ + void SetKeepAliveDkv(const std::string &bundleName, bool enable, int32_t uid) override; + /** * To clear the process by ability token. * diff --git a/services/appmgr/include/app_mgr_service_inner.h b/services/appmgr/include/app_mgr_service_inner.h index f11dd32893..aadcf5bd66 100644 --- a/services/appmgr/include/app_mgr_service_inner.h +++ b/services/appmgr/include/app_mgr_service_inner.h @@ -1269,6 +1269,16 @@ public: */ void SetKeepAliveEnableState(const std::string &bundleName, bool enable, int32_t uid); + /** + * @brief Set non-resident keep-alive process status. + * when one process started, this method will be called from ability mgr with data selected from db. + * + * @param bundleName processed of witch to be configed + * @param enable config value + * @param uid indicates user, 0 for all users + */ + void SetKeepAliveDkv(const std::string &bundleName, bool enable, int32_t uid); + int32_t GetAppRunningUniqueIdByPid(pid_t pid, std::string &appRunningUniqueId); int32_t GetAllUIExtensionRootHostPid(pid_t pid, std::vector &hostPids); @@ -1413,6 +1423,11 @@ private: */ void RestartResidentProcess(std::shared_ptr appRecord); + /** + * If one app needs keepalive and dies, restart the app again + */ + void RestartKeepAliveProcess(std::shared_ptr appRecord); + bool CheckLoadAbilityConditions(std::shared_ptr want, std::shared_ptr loadParam, const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo); @@ -1609,6 +1624,8 @@ private: void ApplicationTerminatedSendProcessEvent(const std::shared_ptr &appRecord); void ClearAppRunningDataForKeepAlive(const std::shared_ptr &appRecord); + void ClearResidentProcessAppRunningData(const std::shared_ptr &appRecord); + void ClearNonResidentKeepAliveAppRunningData(const std::shared_ptr &appRecord); int32_t StartChildProcessPreCheck(pid_t callingPid, int32_t childProcessType); @@ -1822,6 +1839,7 @@ private: void AddUIExtensionLauncherItem(std::shared_ptr want, std::shared_ptr appRecord, sptr token); void NotifyStartResidentProcess(std::vector &bundleInfos); + void NotifyStartKeepAliveProcess(std::vector &bundleInfos); void RemoveUIExtensionLauncherItem(std::shared_ptr appRecord, sptr token); bool IsSceneBoardCall(); void CheckCleanAbilityByUserRequest(const std::shared_ptr &appRecord, diff --git a/services/appmgr/include/app_running_record.h b/services/appmgr/include/app_running_record.h index 4c0d58b916..56291113ef 100644 --- a/services/appmgr/include/app_running_record.h +++ b/services/appmgr/include/app_running_record.h @@ -589,6 +589,11 @@ public: */ bool IsKeepAliveApp() const; + /** + * @brief Whether the process is non-resident keep-alive. + */ + bool IsKeepAliveDkv() const; + /** * @brief Whether the process can keep empty alive. */ @@ -615,6 +620,14 @@ public: */ void SetKeepAliveEnableState(bool isKeepAliveEnable); + /** + * @brief A process can be configured non-resident keep-alive. + * when one process started, this method will be called from ability mgr with data selected from db. + * + * @param isKeepAliveDkv new value + */ + void SetKeepAliveDkv(bool isKeepAliveDkv); + /** * @brief roughly considered as a value from the process's bundle info. * @@ -1056,6 +1069,7 @@ private: bool isKeepAliveRdb_ = false; // Only resident processes can be set to true, please choose carefully bool isKeepAliveBundle_ = false; bool isEmptyKeepAliveApp_ = false; // Only empty resident processes can be set to true, please choose carefully + bool isKeepAliveDkv_ = false; // Only non-resident keep-alive processes can be set to true, please choose carefully bool isMainProcess_ = true; // Only MainProcess can be keepalive bool isSingleton_ = false; bool isStageBasedModel_ = false; diff --git a/services/appmgr/src/ams_mgr_scheduler.cpp b/services/appmgr/src/ams_mgr_scheduler.cpp index 753c8d4a6f..ea4ba003a8 100644 --- a/services/appmgr/src/ams_mgr_scheduler.cpp +++ b/services/appmgr/src/ams_mgr_scheduler.cpp @@ -627,6 +627,15 @@ void AmsMgrScheduler::SetKeepAliveEnableState(const std::string &bundleName, boo amsMgrServiceInner_->SetKeepAliveEnableState(bundleName, enable, uid); } +void AmsMgrScheduler::SetKeepAliveDkv(const std::string &bundleName, bool enable, int32_t uid) +{ + if (!IsReady()) { + TAG_LOGE(AAFwkTag::APPMGR, "not ready"); + return; + } + amsMgrServiceInner_->SetKeepAliveDkv(bundleName, enable, uid); +} + void AmsMgrScheduler::ClearProcessByToken(sptr token) { if (!IsReady()) { diff --git a/services/appmgr/src/app_mgr_service_inner.cpp b/services/appmgr/src/app_mgr_service_inner.cpp index 17c93eff14..bcf1b6fd0c 100644 --- a/services/appmgr/src/app_mgr_service_inner.cpp +++ b/services/appmgr/src/app_mgr_service_inner.cpp @@ -2608,6 +2608,7 @@ std::shared_ptr AppMgrServiceInner::CreateAppRunningRecord( appRecord->SetProcessAndExtensionType(abilityInfo); appRecord->SetKeepAliveEnableState(bundleInfo.isKeepAlive); + appRecord->SetKeepAliveDkv(loadParam->isKeepAlive); appRecord->SetEmptyKeepAliveAppState(false); appRecord->SetTaskHandler(taskHandler_); appRecord->SetEventHandler(eventHandler_); @@ -4193,6 +4194,36 @@ bool AppMgrServiceInner::CheckRemoteClient() return true; } +void AppMgrServiceInner::RestartKeepAliveProcess(std::shared_ptr appRecord) +{ + TAG_LOGI(AAFwkTag::APPMGR, "restart keep-alive process begins."); + if (appRecord == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "appRecord null"); + return; + } + + if (!CheckRemoteClient() || !appRecord || !appRunningManager_) { + TAG_LOGE(AAFwkTag::APPMGR, "restart keep-alive fail"); + return; + } + + auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper(); + BundleInfo bundleInfo; + auto userId = GetUserIdByUid(appRecord->GetUid()); + auto flags = BundleFlag::GET_BUNDLE_DEFAULT | BundleFlag::GET_BUNDLE_WITH_REQUESTED_PERMISSION; + if (!IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfo( + appRecord->GetBundleName(), + static_cast(flags), + bundleInfo, userId))) { + TAG_LOGE(AAFwkTag::APPMGR, "getBundleInfo fail"); + return; + } + std::vector infos; + infos.emplace_back(bundleInfo); + TAG_LOGI(AAFwkTag::APPMGR, "keepAliveProcess %{public}s", appRecord->GetProcessName().c_str()); + NotifyStartKeepAliveProcess(infos); +} + void AppMgrServiceInner::RestartResidentProcess(std::shared_ptr appRecord) { if (appRecord == nullptr) { @@ -6895,6 +6926,12 @@ void AppMgrServiceInner::ApplicationTerminatedSendProcessEvent(const std::shared } void AppMgrServiceInner::ClearAppRunningDataForKeepAlive(const std::shared_ptr &appRecord) +{ + ClearResidentProcessAppRunningData(appRecord); + ClearNonResidentKeepAliveAppRunningData(appRecord); +} + +void AppMgrServiceInner::ClearResidentProcessAppRunningData(const std::shared_ptr &appRecord) { if (appRecord == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "appRecord null"); @@ -6942,6 +6979,38 @@ void AppMgrServiceInner::ClearAppRunningDataForKeepAlive(const std::shared_ptr &appRecord) +{ + if (appRecord == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "appRecord null"); + return; + } + + auto userId = GetUserIdByUid(appRecord->GetUid()); + if (appRecord->IsKeepAliveDkv() && (userId == 0 || userId == currentUserId_) && + appRecord->GetBundleName() != SCENE_BOARD_BUNDLE_NAME) { + if (ExitResidentProcessManager::GetInstance().IsKilledForUpgradeWeb(appRecord->GetBundleName())) { + TAG_LOGI(AAFwkTag::APPMGR, "is killed for upgrade web"); + return; + } + if (!IsMemorySizeSufficient()) { + TAG_LOGI(AAFwkTag::APPMGR, "memory size insufficient"); + return; + } + TAG_LOGI(AAFwkTag::APPMGR, "memory size sufficient"); + auto restartProcess = [appRecord, innerService = shared_from_this()]() { + TAG_LOGI(AAFwkTag::APPMGR, "restarting keep-alive process."); + innerService->RestartKeepAliveProcess(appRecord); + }; + if (taskHandler_ == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ null"); + return; + } + TAG_LOGI(AAFwkTag::APPMGR, "submit restart keep-alive process task."); + taskHandler_->SubmitTask(restartProcess, "RestartKeepAliveProcess"); + } +} + int32_t AppMgrServiceInner::NotifyPageShow(const sptr &token, const PageStateData &pageStateData) { if (!JudgeSelfCalledByToken(token, pageStateData)) { @@ -7741,6 +7810,7 @@ int32_t AppMgrServiceInner::NotifyMemorySizeStateChanged(bool isMemorySizeSuffic ExitResidentProcessManager::GetInstance().QueryExitBundleInfos(exitProcessInfos, exitBundleInfos); innerServicer->NotifyStartResidentProcess(exitBundleInfos); + innerServicer->NotifyStartKeepAliveProcess(exitBundleInfos); }; taskHandler_->SubmitTask(StartExitKeepAliveProcessTask, "startexitkeepaliveprocess"); return ERR_OK; @@ -7771,6 +7841,16 @@ void AppMgrServiceInner::NotifyStartResidentProcess(std::vector &bundleInfos) +{ + std::lock_guard lock(appStateCallbacksLock_); + for (const auto &item : appStateCallbacks_) { + if (item.callback != nullptr) { + item.callback->NotifyStartKeepAliveProcess(bundleInfos); + } + } +} + void AppMgrServiceInner::SetKeepAliveEnableState(const std::string &bundleName, bool enable, int32_t uid) { TAG_LOGD(AAFwkTag::APPMGR, "called"); @@ -7801,6 +7881,36 @@ void AppMgrServiceInner::SetKeepAliveEnableState(const std::string &bundleName, } } +void AppMgrServiceInner::SetKeepAliveDkv(const std::string &bundleName, bool enable, int32_t uid) +{ + TAG_LOGD(AAFwkTag::APPMGR, "called"); + if (bundleName.empty()) { + TAG_LOGE(AAFwkTag::APPMGR, "bundle name empty"); + return; + } + + if (appRunningManager_ == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "running manager error"); + return; + } + + auto callerUid = IPCSkeleton::GetCallingUid(); + if (callerUid != FOUNDATION_UID) { + TAG_LOGE(AAFwkTag::APPMGR, "not foundation call"); + return; + } + + for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) { + const auto &appRecord = item.second; + if (appRecord != nullptr && appRecord->GetBundleName() == bundleName && + (uid == 0 || appRecord->GetUid() == uid)) { + TAG_LOGD(AAFwkTag::APPMGR, "%{public}s update state: %{public}d", + bundleName.c_str(), static_cast(enable)); + appRecord->SetKeepAliveDkv(enable); + } + } +} + int32_t AppMgrServiceInner::SetSupportedProcessCacheSelf(bool isSupport) { TAG_LOGI(AAFwkTag::APPMGR, "call"); @@ -8059,6 +8169,7 @@ void AppMgrServiceInner::RestartResidentProcessDependedOnWeb() ExitResidentProcessManager::GetInstance().QueryExitBundleInfos(bundleNames, exitBundleInfos); innerServicer->NotifyStartResidentProcess(exitBundleInfos); + innerServicer->NotifyStartKeepAliveProcess(exitBundleInfos); }; taskHandler_->SubmitTask(RestartResidentProcessDependedOnWebTask, "RestartResidentProcessDependedOnWeb"); } diff --git a/services/appmgr/src/app_running_record.cpp b/services/appmgr/src/app_running_record.cpp index 346203ac50..d29705ee99 100644 --- a/services/appmgr/src/app_running_record.cpp +++ b/services/appmgr/src/app_running_record.cpp @@ -1458,11 +1458,21 @@ bool AppRunningRecord::IsKeepAliveApp() const return true; } +bool AppRunningRecord::IsKeepAliveDkv() const +{ + return isKeepAliveDkv_; +} + void AppRunningRecord::SetKeepAliveEnableState(bool isKeepAliveEnable) { isKeepAliveRdb_ = isKeepAliveEnable; } +void AppRunningRecord::SetKeepAliveDkv(bool isKeepAliveDkv) +{ + isKeepAliveDkv_ = isKeepAliveDkv; +} + void AppRunningRecord::SetKeepAliveBundle(bool isKeepAliveBundle) { isKeepAliveBundle_ = isKeepAliveBundle; diff --git a/services/common/include/hilog_tag_wrapper.h b/services/common/include/hilog_tag_wrapper.h index b4ef238027..cf24da24c5 100644 --- a/services/common/include/hilog_tag_wrapper.h +++ b/services/common/include/hilog_tag_wrapper.h @@ -90,6 +90,7 @@ enum class AAFwkLogTag : uint32_t { CONTINUATION, DISTRIBUTED, FREE_INSTALL, + KEEP_ALIVE, LOCAL_CALL = DEFAULT + 0x60, // 0xD001360 @@ -158,7 +159,7 @@ inline const char* GetDomainName5(AAFwkLogTag tag) { const char* tagNames[] = { "WantAgent", "AutoFillMgr", "ExtMgr", "ServiceRouter", "AutoStartup", "Startup", "Recovery", "ProcessMgr", "Continuation", - "Distributed", "FreeInstall" }; + "Distributed", "FreeInstall", "KeepAlive" }; uint32_t offset = GetOffset(tag, AAFwkLogTag::WANTAGENT); if (offset >= sizeof(tagNames) / sizeof(const char*)) { return "UN"; diff --git a/services/common/include/json_utils.h b/services/common/include/json_utils.h index 67c0c6c280..8eed8db121 100644 --- a/services/common/include/json_utils.h +++ b/services/common/include/json_utils.h @@ -24,16 +24,61 @@ namespace OHOS { namespace AAFwk { +/** + * @class JsonUtils + * provides json utilities. + */ class JsonUtils { public: + /** + * GetInstance, get an instance of JsonUtils. + * + * @return an instance of JsonUtils. + */ static JsonUtils &GetInstance() { static JsonUtils instance; return instance; } + + /** + * JsonUtils, destructor. + * + */ ~JsonUtils() = default; + + /** + * LoadConfiguration, load configuration. + * + * @param path The json file path. + * @param jsonBuf The json buffer to be returned. + * @param defaultPath The default output path. + * @return Whether or not the load operation succeeds. + */ bool LoadConfiguration(const std::string& path, nlohmann::json& jsonBuf, const std::string& defaultPath = ""); + /** + * IsEqual, check if json object contains certain key. + * + * @param jsonObject The json object. + * @param key The key. + * @param value The string value. + * @param checkEmpty The flag indicates whether the value can be empty. + * @return Whether or not the json object contains certain key. + */ + bool IsEqual(nlohmann::json &jsonObject, const std::string &key, + const std::string &value, bool checkEmpty = false); + + /** + * IsEqual, check if json object contains certain key. + * + * @param jsonObject The json object. + * @param key The key. + * @param value The int32_t value. + * @return Whether or not the json object contains certain key. + */ + bool IsEqual(nlohmann::json &jsonObject, const std::string &key, int32_t value); + private: std::string GetConfigPath(const std::string& path, const std::string& defaultPath); bool ReadFileInfoJson(const std::string &filePath, nlohmann::json &jsonBuf); diff --git a/services/common/include/permission_constants.h b/services/common/include/permission_constants.h index 478d479caa..854bb70f89 100644 --- a/services/common/include/permission_constants.h +++ b/services/common/include/permission_constants.h @@ -67,6 +67,8 @@ constexpr const char* PERMISSION_BLOCK_ALL_APP_START = "ohos.permission.BLOCK_AL constexpr const char* PERMISSION_START_UIABILITY_TO_HIDDEN = "ohos.permission.START_UIABILITY_TO_HIDDEN"; constexpr const char* PERMISSION_SUPERVISE_KIA_SERVICE = "ohos.permission.SUPERVISE_KIA_SERVICE"; constexpr const char* PERMISSION_GET_TELEPHONY_STATE = "ohos.permission.GET_TELEPHONY_STATE"; +constexpr const char* PERMISSION_MANAGE_APP_KEEP_ALIVE = "ohos.permission.MANAGE_APP_KEEP_ALIVE"; +constexpr const char* PERMISSION_MANAGE_APP_KEEP_ALIVE_INTERNAL = "ohos.permission.MANAGE_APP_KEEP_ALIVE_INTERNAL"; } // namespace PermissionConstants } // namespace AAFwk } // namespace OHOS diff --git a/services/common/src/json_utils.cpp b/services/common/src/json_utils.cpp index 3726cc3593..c9f79fd66e 100644 --- a/services/common/src/json_utils.cpp +++ b/services/common/src/json_utils.cpp @@ -91,5 +91,28 @@ bool JsonUtils::ReadFileInfoJson(const std::string &filePath, nlohmann::json &js return true; } + +bool JsonUtils::IsEqual(nlohmann::json &jsonObject, const std::string &key, const std::string &value, bool checkEmpty) +{ + if (jsonObject.contains(key) && jsonObject[key].is_string()) { + std::string jsonValue = jsonObject.at(key).get(); + if (checkEmpty && !jsonValue.empty() && jsonValue != value) { + return false; + } else if (value != jsonValue) { + return false; + } + } + return true; +} + +bool JsonUtils::IsEqual(nlohmann::json &jsonObject, const std::string &key, int32_t value) +{ + if (jsonObject.contains(key) && jsonObject[key].is_number()) { + if (value != jsonObject.at(key).get()) { + return false; + } + } + return true; +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/test/fuzztest/abilityautostartupdatamanager_fuzzer/abilityautostartupdatamanager_fuzzer.cpp b/test/fuzztest/abilityautostartupdatamanager_fuzzer/abilityautostartupdatamanager_fuzzer.cpp index cdbf00fb4f..bbd9f3e50f 100644 --- a/test/fuzztest/abilityautostartupdatamanager_fuzzer/abilityautostartupdatamanager_fuzzer.cpp +++ b/test/fuzztest/abilityautostartupdatamanager_fuzzer/abilityautostartupdatamanager_fuzzer.cpp @@ -73,8 +73,6 @@ bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) std::string keys(data, size); std::string values(data, size); bool checkEmpty = *data % ENABLE; - abilityAutoStartupDataManager->IsEqual(jsonObject, keys, values, checkEmpty); - abilityAutoStartupDataManager->IsEqual(jsonObject, keys, values); abilityAutoStartupDataManager->IsEqual(key, info); abilityAutoStartupDataManager->IsEqual(key, strParam); abilityAutoStartupDataManager->IsEqual(key, in32Param); diff --git a/test/fuzztest/abilityautostartupdatamanagera_fuzzer/BUILD.gn b/test/fuzztest/abilityautostartupdatamanagera_fuzzer/BUILD.gn index 7d31c46269..89af2d2aa5 100755 --- a/test/fuzztest/abilityautostartupdatamanagera_fuzzer/BUILD.gn +++ b/test/fuzztest/abilityautostartupdatamanagera_fuzzer/BUILD.gn @@ -52,6 +52,7 @@ ohos_fuzztest("AbilityAutoStartupDataManageraFuzzTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:app_util", "//third_party/jsoncpp:jsoncpp", ] diff --git a/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/BUILD.gn b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/BUILD.gn index bf4f2d2f73..d2ef28e0b3 100755 --- a/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/BUILD.gn +++ b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/BUILD.gn @@ -52,6 +52,7 @@ ohos_fuzztest("AbilityAutoStartupDataManagerbFuzzTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:app_util", "//third_party/jsoncpp:jsoncpp", ] diff --git a/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/abilityautostartupdatamanagerb_fuzzer.cpp b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/abilityautostartupdatamanagerb_fuzzer.cpp index be7c2e6d5c..cec71166dc 100755 --- a/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/abilityautostartupdatamanagerb_fuzzer.cpp +++ b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/abilityautostartupdatamanagerb_fuzzer.cpp @@ -101,14 +101,6 @@ void AbilityAutoStartupDataManagerFuzztest1(bool boolParam, std::string &stringP dataMgr->ConvertAutoStartupInfoFromKeyAndValue(key2, value3); nlohmann::json jsonObject = nlohmann::json::parse(key1.ToString(), nullptr, false); - dataMgr->IsEqual(jsonObject, "abilityName", "ability", boolParam); // branch,return true - dataMgr->IsEqual(jsonObject, "abilityName", "NaN", boolParam); // branch,return true - dataMgr->IsEqual(jsonObject, "userId", "ability", boolParam); // branch - dataMgr->IsEqual(jsonObject, "NaN", "ability", boolParam); // branch - - dataMgr->IsEqual(jsonObject, "userId", 100); // 100 means userid,branch - dataMgr->IsEqual(jsonObject, "userId", int32Param); // branch - dataMgr->IsEqual(jsonObject, "NaN", int32Param); dataMgr->IsEqual(key1, info); dataMgr->IsEqual(key2, info); dataMgr->IsEqual(key1Illegal, info); diff --git a/test/fuzztest/abilityautostartupservicea_fuzzer/BUILD.gn b/test/fuzztest/abilityautostartupservicea_fuzzer/BUILD.gn index 17b6f3ecbf..437bbb5e9e 100755 --- a/test/fuzztest/abilityautostartupservicea_fuzzer/BUILD.gn +++ b/test/fuzztest/abilityautostartupservicea_fuzzer/BUILD.gn @@ -56,6 +56,7 @@ ohos_fuzztest("AbilityAutoStartupServiceaFuzzTest") { "${ability_runtime_native_path}/ability/native:auto_startup_callback", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:perm_verification", "//third_party/jsoncpp:jsoncpp", ] diff --git a/test/fuzztest/abilityautostartupserviceb_fuzzer/BUILD.gn b/test/fuzztest/abilityautostartupserviceb_fuzzer/BUILD.gn index 804f7a8870..9eb21d705d 100755 --- a/test/fuzztest/abilityautostartupserviceb_fuzzer/BUILD.gn +++ b/test/fuzztest/abilityautostartupserviceb_fuzzer/BUILD.gn @@ -56,6 +56,7 @@ ohos_fuzztest("AbilityAutoStartupServicebFuzzTest") { "${ability_runtime_native_path}/ability/native:auto_startup_callback", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:perm_verification", "//third_party/jsoncpp:jsoncpp", ] diff --git a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/include/appmgr/app_state_callback_host.h b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/include/appmgr/app_state_callback_host.h index b2e173f544..e8ba483140 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/include/appmgr/app_state_callback_host.h +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/include/appmgr/app_state_callback_host.h @@ -56,6 +56,12 @@ public: */ virtual void NotifyStartResidentProcess(std::vector &bundleInfos) override; + /** + * @brief Notify abilityms start keep-alive process. + * @param bundleInfos resident process bundle infos. + */ + virtual void NotifyStartKeepAliveProcess(std::vector &bundleInfos) override; + /** * @brief Notify abilityms app process pre cache * @param pid process pid. @@ -67,6 +73,7 @@ private: int32_t HandleOnAppStateChanged(MessageParcel& data, MessageParcel& reply); int32_t HandleOnAbilityRequestDone(MessageParcel& data, MessageParcel& reply); int32_t HandleNotifyStartResidentProcess(MessageParcel &data, MessageParcel &reply); + int32_t HandleNotifyStartKeepAliveProcess(MessageParcel &data, MessageParcel &reply); int32_t HandleNotifyAppPreCache(MessageParcel &data, MessageParcel &reply); using AppStateCallbackFunc = int32_t(AppStateCallbackHost::*)(MessageParcel& data, MessageParcel& reply); diff --git a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_host.cpp b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_host.cpp index 54bb906ddd..4758c246b5 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_host.cpp +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_host.cpp @@ -49,6 +49,11 @@ void AppStateCallbackHost::NotifyStartResidentProcess(std::vector &bundleInfos) +{ + TAG_LOGD(AAFwkTag::APPMGR, "called"); +} + void AppStateCallbackHost::NotifyAppPreCache(int32_t pid, int32_t userId) { TAG_LOGD(AAFwkTag::TEST, "NotifyAppPreCache called"); @@ -68,6 +73,12 @@ int32_t AppStateCallbackHost::HandleNotifyStartResidentProcess(MessageParcel &da { return NO_ERROR; } + +int32_t AppStateCallbackHost::HandleNotifyStartKeepAliveProcess(MessageParcel &data, MessageParcel &reply) +{ + return NO_ERROR; +} + int32_t AppStateCallbackHost::HandleNotifyAppPreCache(MessageParcel &data, MessageParcel &reply) { return NO_ERROR; diff --git a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp index 918c329413..2073c733f4 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp @@ -40,5 +40,8 @@ void AppStateCallbackProxy::NotifyAppPreCache(int32_t pid, int32_t userId) void AppStateCallbackProxy::NotifyStartResidentProcess(std::vector &bundleInfos) {} + +void AppStateCallbackProxy::NotifyStartKeepAliveProcess(std::vector &bundleInfos) +{} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp index fec7ffd772..7d8d7b2d48 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp @@ -133,6 +133,11 @@ void AppScheduler::NotifyStartResidentProcess(std::vector &bundleInfos) +{ + TAG_LOGI(AAFwkTag::TEST, "Test AppScheduler::NotifyStartKeepAliveProcess()"); +} + void AppScheduler::OnAppRemoteDied(const std::vector> &abilityTokens) { TAG_LOGI(AAFwkTag::TEST, "Test AppScheduler::OnAppRemoteDied()"); diff --git a/test/mock/services_appmgr_test/include/mock_iapp_state_callback.h b/test/mock/services_appmgr_test/include/mock_iapp_state_callback.h index 43fca14b11..80e560b86d 100644 --- a/test/mock/services_appmgr_test/include/mock_iapp_state_callback.h +++ b/test/mock/services_appmgr_test/include/mock_iapp_state_callback.h @@ -34,6 +34,7 @@ public: MOCK_METHOD1(OnAppStateChanged, void(const AppProcessData&)); MOCK_METHOD2(OnAbilityRequestDone, void(const sptr&, const AbilityState)); MOCK_METHOD1(NotifyStartResidentProcess, void(std::vector&)); + MOCK_METHOD1(NotifyStartKeepAliveProcess, void(std::vector&)); MOCK_METHOD2(NotifyAppPreCache, void(int32_t, int32_t)); }; } // namespace AppExecFwk diff --git a/test/unittest/ability_auto_startup_data_manager_test/BUILD.gn b/test/unittest/ability_auto_startup_data_manager_test/BUILD.gn index dbc6f6d6d2..e10cc92243 100644 --- a/test/unittest/ability_auto_startup_data_manager_test/BUILD.gn +++ b/test/unittest/ability_auto_startup_data_manager_test/BUILD.gn @@ -41,6 +41,7 @@ ohos_unittest("ability_auto_startup_data_manager_test") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability:ability_context_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:perm_verification", "//third_party/googletest:gtest_main", ] diff --git a/test/unittest/ability_auto_startup_service_test/BUILD.gn b/test/unittest/ability_auto_startup_service_test/BUILD.gn index 2bd74a0fca..d743cce308 100644 --- a/test/unittest/ability_auto_startup_service_test/BUILD.gn +++ b/test/unittest/ability_auto_startup_service_test/BUILD.gn @@ -48,6 +48,7 @@ ohos_unittest("ability_auto_startup_service_test") { "${ability_runtime_native_path}/ability/native:auto_startup_callback", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:perm_verification", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", diff --git a/test/unittest/ability_bundle_event_callback_test/BUILD.gn b/test/unittest/ability_bundle_event_callback_test/BUILD.gn index 31997de481..8121c92087 100644 --- a/test/unittest/ability_bundle_event_callback_test/BUILD.gn +++ b/test/unittest/ability_bundle_event_callback_test/BUILD.gn @@ -44,6 +44,7 @@ ohos_unittest("ability_bundle_event_callback_test") { "${ability_runtime_native_path}/ability/native:auto_startup_callback", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:event_report", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_services_path}/common:task_handler_wrap", diff --git a/test/unittest/ability_manager_service_first_test/ability_manager_service_first_test.cpp b/test/unittest/ability_manager_service_first_test/ability_manager_service_first_test.cpp index 55045f91f0..2c4cf5a6d7 100644 --- a/test/unittest/ability_manager_service_first_test/ability_manager_service_first_test.cpp +++ b/test/unittest/ability_manager_service_first_test/ability_manager_service_first_test.cpp @@ -2113,6 +2113,19 @@ HWTEST_F(AbilityManagerServiceFirstTest, NotifyStartResidentProcess_0100, TestSi abilityMs->NotifyStartResidentProcess(bundleInfos); } +/** + * @tc.name: AbilityManagerServiceFirstTest_NotifyStartKeepAliveProcess_0100 + * @tc.desc: Test NotifyStartKeepAliveProcess. + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerServiceFirstTest, NotifyStartKeepAliveProcess_0100, TestSize.Level1) +{ + std::vector bundleInfos; + auto abilityMs = std::make_shared(); + EXPECT_NE(abilityMs, nullptr); + abilityMs->NotifyStartKeepAliveProcess(bundleInfos); +} + /** * @tc.name: AbilityManagerServiceFirstTest_OnAppRemoteDied_0100 * @tc.desc: Test OnAppRemoteDied. diff --git a/test/unittest/ability_manager_service_fourth_test/BUILD.gn b/test/unittest/ability_manager_service_fourth_test/BUILD.gn index 4dd74b1702..15d24b348d 100644 --- a/test/unittest/ability_manager_service_fourth_test/BUILD.gn +++ b/test/unittest/ability_manager_service_fourth_test/BUILD.gn @@ -73,6 +73,7 @@ ohos_unittest("ability_manager_service_fourth_test") { "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:perm_verification", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", diff --git a/test/unittest/ability_manager_service_third_test/BUILD.gn b/test/unittest/ability_manager_service_third_test/BUILD.gn index b4355e7c0b..e145cc50bc 100644 --- a/test/unittest/ability_manager_service_third_test/BUILD.gn +++ b/test/unittest/ability_manager_service_third_test/BUILD.gn @@ -61,6 +61,7 @@ ohos_unittest("ability_manager_service_third_test") { "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:perm_verification", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", diff --git a/test/unittest/ams_app_state_callback_test/ams_app_state_callback_test.cpp b/test/unittest/ams_app_state_callback_test/ams_app_state_callback_test.cpp index a70a30491c..2b73bf7040 100644 --- a/test/unittest/ams_app_state_callback_test/ams_app_state_callback_test.cpp +++ b/test/unittest/ams_app_state_callback_test/ams_app_state_callback_test.cpp @@ -122,6 +122,22 @@ HWTEST_F(AmsAppStateCallBackTest, NotifyStartResidentProcess_001, TestSize.Level host->NotifyStartResidentProcess(bundleInfos); } +/* + * Feature: AppStateCallBackHost + * Function: AppStateCallBackHost + * SubFunction: NotifyStartKeepAliveProcess Function + * FunctionPoints: NotifyStartKeepAliveProcess Onreceived interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if Onreceived works when ability request done. + */ +HWTEST_F(AmsAppStateCallBackTest, NotifyStartKeepAliveProcess_001, TestSize.Level1) +{ + sptr host(new AppStateCallbackHost()); + EXPECT_NE(host, nullptr); + std::vector bundleInfos; + host->NotifyStartKeepAliveProcess(bundleInfos); +} + /* * Feature: AppStateCallBackHost * Function: AppStateCallBackHost diff --git a/test/unittest/app_scheduler_test/app_scheduler_test.cpp b/test/unittest/app_scheduler_test/app_scheduler_test.cpp index e323a69428..6e0ebccf1e 100644 --- a/test/unittest/app_scheduler_test/app_scheduler_test.cpp +++ b/test/unittest/app_scheduler_test/app_scheduler_test.cpp @@ -594,6 +594,22 @@ HWTEST_F(AppSchedulerTest, AppScheduler_NotifyStartResidentProcess_001, TestSize DelayedSingleton::GetInstance()->NotifyStartResidentProcess(bundleInfos); } +/* + * Feature: AppScheduler + * Function: NotifyStartKeepAliveProcess + * SubFunction: NA + * FunctionPoints: AppScheduler NotifyStartKeepAliveProcess + * EnvConditions: NA + * CaseDescription: Verify NotifyStartKeepAliveProcess + */ +HWTEST_F(AppSchedulerTest, AppScheduler_NotifyStartKeepAliveProcess_001, TestSize.Level1) +{ + std::vector bundleInfos; + ASSERT_NE(appStateMock_, nullptr); + DelayedSingleton::GetInstance()->callback_ = appStateMock_; + DelayedSingleton::GetInstance()->NotifyStartKeepAliveProcess(bundleInfos); +} + /* * Feature: AppScheduler * Function: KillApplication diff --git a/test/unittest/app_scheduler_test/app_state_call_back_mock.h b/test/unittest/app_scheduler_test/app_state_call_back_mock.h index f0358e240e..bfb4596864 100644 --- a/test/unittest/app_scheduler_test/app_state_call_back_mock.h +++ b/test/unittest/app_scheduler_test/app_state_call_back_mock.h @@ -33,6 +33,7 @@ public: MOCK_METHOD2(OnAbilityRequestDone, void(const sptr&, const int32_t)); MOCK_METHOD1(OnAppStateChanged, void(const AppInfo& info)); MOCK_METHOD1(NotifyStartResidentProcess, void(std::vector&)); + MOCK_METHOD1(NotifyStartKeepAliveProcess, void(std::vector&)); MOCK_METHOD2(NotifyAppPreCache, void(int32_t, int32_t)); }; } // namespace AAFwk diff --git a/test/unittest/extension_permissions_util_test/BUILD.gn b/test/unittest/extension_permissions_util_test/BUILD.gn index cf4834c570..40bd0468cc 100644 --- a/test/unittest/extension_permissions_util_test/BUILD.gn +++ b/test/unittest/extension_permissions_util_test/BUILD.gn @@ -28,9 +28,7 @@ ohos_unittest("extension_permissions_util_test") { include_dirs = [ "mock/include", "${ability_runtime_services_path}/abilitymgr/include/utils", - "${ability_runtime_services_path}/abilitymgr/include/utils", "${ability_runtime_services_path}/abilitymgr/include", - "${ability_runtime_services_path}/common/include", ] diff --git a/test/unittest/frameworks_kits_ability_native_test/BUILD.gn b/test/unittest/frameworks_kits_ability_native_test/BUILD.gn index df8754ee02..706cf9b9a6 100644 --- a/test/unittest/frameworks_kits_ability_native_test/BUILD.gn +++ b/test/unittest/frameworks_kits_ability_native_test/BUILD.gn @@ -38,7 +38,6 @@ config("module_private_config") { "${ability_runtime_test_path}/mock/frameworks_kits_appkit_native_test/include", "${ability_runtime_services_path}/abilitymgr/include/utils", "${ability_runtime_services_path}/abilitymgr/include", - "${ability_runtime_services_path}/common/include", "${distributeddatamgr_path}/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", @@ -413,7 +412,6 @@ ohos_unittest("data_ability_helper_test") { include_dirs = [ "${ability_runtime_services_path}/abilitymgr/include/utils", "${ability_runtime_services_path}/abilitymgr/include", - "${ability_runtime_path}/interfaces/kits/native/ability/native", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", ] @@ -470,7 +468,6 @@ ohos_unittest("data_ability_helper_impl_test") { include_dirs = [ "${ability_runtime_services_path}/abilitymgr/include/utils", "${ability_runtime_services_path}/abilitymgr/include", - "${ability_runtime_path}/interfaces/kits/native/ability/native", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", "${ability_runtime_path}/interfaces/kits/native/ability/native", @@ -1302,7 +1299,6 @@ ohos_unittest("data_ability_impl_test") { include_dirs = [ "${ability_runtime_services_path}/abilitymgr/include/utils", "${ability_runtime_services_path}/abilitymgr/include", - "${ability_runtime_path}/interfaces/kits/native/ability/native", "${ability_base_kits_path}/extractortool/include", "${distributeddatamgr_path}/relational_store/frameworks/js/napi/rdb/include", diff --git a/test/unittest/main_element_utils_test/main_element_utils_test.cpp b/test/unittest/main_element_utils_test/main_element_utils_test.cpp index f453031c63..d6c369cf08 100755 --- a/test/unittest/main_element_utils_test/main_element_utils_test.cpp +++ b/test/unittest/main_element_utils_test/main_element_utils_test.cpp @@ -54,8 +54,8 @@ HWTEST_F(MainElementUtilsTest, CheckMainElement_001, TestSize.Level1) HapModuleInfo hapModuleInfo; std::string processName = "processName"; std::string mainElement = ""; - std::set needEraseIndexSet; - size_t bundleInfoIndex = 0; + bool isDataAbility = false; + std::string uriStr; AbilityInfo abilityInfo; hapModuleInfo.mainAbility = "mainAbility"; hapModuleInfo.isModuleJson = false; @@ -63,7 +63,7 @@ HWTEST_F(MainElementUtilsTest, CheckMainElement_001, TestSize.Level1) abilityInfo.name = "mainAbility"; hapModuleInfo.abilityInfos.push_back(abilityInfo); bool res = MainElementUtils::CheckMainElement(hapModuleInfo, - processName, mainElement, needEraseIndexSet, bundleInfoIndex); + processName, mainElement, isDataAbility, uriStr); EXPECT_FALSE(res); } @@ -80,8 +80,8 @@ HWTEST_F(MainElementUtilsTest, CheckMainElement_002, TestSize.Level1) HapModuleInfo hapModuleInfo; std::string processName = "processName"; std::string mainElement = ""; - std::set needEraseIndexSet; - size_t bundleInfoIndex = 0; + bool isDataAbility = false; + std::string uriStr; AbilityInfo abilityInfo; hapModuleInfo.mainAbility = "mainAbility"; hapModuleInfo.isModuleJson = false; @@ -89,7 +89,7 @@ HWTEST_F(MainElementUtilsTest, CheckMainElement_002, TestSize.Level1) abilityInfo.name = ""; hapModuleInfo.abilityInfos.push_back(abilityInfo); bool res = MainElementUtils::CheckMainElement(hapModuleInfo, - processName, mainElement, needEraseIndexSet, bundleInfoIndex); + processName, mainElement, isDataAbility, uriStr); EXPECT_FALSE(res); } @@ -106,8 +106,8 @@ HWTEST_F(MainElementUtilsTest, CheckMainElement_003, TestSize.Level1) HapModuleInfo hapModuleInfo; std::string processName = "processName"; std::string mainElement = ""; - std::set needEraseIndexSet; - size_t bundleInfoIndex = 0; + bool isDataAbility = false; + std::string uriStr; AbilityInfo abilityInfo; hapModuleInfo.mainAbility = "mainAbility"; hapModuleInfo.isModuleJson = false; @@ -117,7 +117,7 @@ HWTEST_F(MainElementUtilsTest, CheckMainElement_003, TestSize.Level1) abilityInfo.type = AbilityType::DATA; hapModuleInfo.abilityInfos.push_back(abilityInfo); bool res = MainElementUtils::CheckMainElement(hapModuleInfo, - processName, mainElement, needEraseIndexSet, bundleInfoIndex); + processName, mainElement, isDataAbility, uriStr); EXPECT_FALSE(res); } @@ -134,8 +134,8 @@ HWTEST_F(MainElementUtilsTest, CheckMainElement_004, TestSize.Level1) HapModuleInfo hapModuleInfo; std::string processName = "processName"; std::string mainElement = ""; - std::set needEraseIndexSet; - size_t bundleInfoIndex = 0; + bool isDataAbility = false; + std::string uriStr; AbilityInfo abilityInfo; hapModuleInfo.mainAbility = "mainAbility"; hapModuleInfo.isModuleJson = false; @@ -145,7 +145,7 @@ HWTEST_F(MainElementUtilsTest, CheckMainElement_004, TestSize.Level1) abilityInfo.type = AbilityType::PAGE; hapModuleInfo.abilityInfos.push_back(abilityInfo); bool res = MainElementUtils::CheckMainElement(hapModuleInfo, - processName, mainElement, needEraseIndexSet, bundleInfoIndex); + processName, mainElement, isDataAbility, uriStr); EXPECT_FALSE(res); } @@ -162,12 +162,12 @@ HWTEST_F(MainElementUtilsTest, CheckMainElement_005, TestSize.Level1) HapModuleInfo hapModuleInfo; std::string processName = "processName"; std::string mainElement = ""; - std::set needEraseIndexSet; - size_t bundleInfoIndex = 0; + bool isDataAbility = false; + std::string uriStr; hapModuleInfo.mainAbility = ""; hapModuleInfo.isModuleJson = true; bool res = MainElementUtils::CheckMainElement(hapModuleInfo, - processName, mainElement, needEraseIndexSet, bundleInfoIndex); + processName, mainElement, isDataAbility, uriStr); EXPECT_FALSE(res); } @@ -184,13 +184,13 @@ HWTEST_F(MainElementUtilsTest, CheckMainElement_006, TestSize.Level1) HapModuleInfo hapModuleInfo; std::string processName = "processName"; std::string mainElement = ""; - std::set needEraseIndexSet; - size_t bundleInfoIndex = 0; + bool isDataAbility = false; + std::string uriStr; hapModuleInfo.mainAbility = "mainAbility"; hapModuleInfo.isModuleJson = true; hapModuleInfo.process = ""; bool res = MainElementUtils::CheckMainElement(hapModuleInfo, - processName, mainElement, needEraseIndexSet, bundleInfoIndex); + processName, mainElement, isDataAbility, uriStr); EXPECT_FALSE(res); } } // namespace AAFwk diff --git a/test/unittest/multi_app_utils_test/BUILD.gn b/test/unittest/multi_app_utils_test/BUILD.gn index 56a9b7f65a..dae59ec054 100644 --- a/test/unittest/multi_app_utils_test/BUILD.gn +++ b/test/unittest/multi_app_utils_test/BUILD.gn @@ -28,9 +28,7 @@ ohos_unittest("multi_app_utils_test") { include_dirs = [ "include", "${ability_runtime_services_path}/abilitymgr/include/utils", - "${ability_runtime_services_path}/abilitymgr/include/utils", "${ability_runtime_services_path}/abilitymgr/include", - "${ability_runtime_services_path}/appmgr/include", "${ability_runtime_services_path}/common/include", "${ability_runtime_test_path}/mock/services_appmgr_test/include", diff --git a/test/unittest/want_utils_test/BUILD.gn b/test/unittest/want_utils_test/BUILD.gn index ce36dbe7b2..db274ea713 100644 --- a/test/unittest/want_utils_test/BUILD.gn +++ b/test/unittest/want_utils_test/BUILD.gn @@ -28,9 +28,7 @@ ohos_unittest("want_utils_test") { include_dirs = [ "include", "${ability_runtime_services_path}/abilitymgr/include/utils", - "${ability_runtime_services_path}/abilitymgr/include/utils", "${ability_runtime_services_path}/abilitymgr/include", - "${ability_runtime_services_path}/common/include", ] diff --git a/test/unittest/window_options_utils_test/BUILD.gn b/test/unittest/window_options_utils_test/BUILD.gn index c514b95d8f..7f57dbd911 100644 --- a/test/unittest/window_options_utils_test/BUILD.gn +++ b/test/unittest/window_options_utils_test/BUILD.gn @@ -28,13 +28,9 @@ ohos_unittest("window_options_utils_test") { include_dirs = [ "mock/include", "${ability_runtime_services_path}/abilitymgr/include/utils", - "${ability_runtime_services_path}/abilitymgr/include/utils", "${ability_runtime_services_path}/abilitymgr/include", - "${ability_runtime_services_path}/common/include", "${ability_runtime_path}interfaces/inner_api/ability_manager/include", - "${ability_runtime_services_path}/abilitymgr/include/utils", - "${ability_runtime_services_path}/abilitymgr/include", ] sources = [ @@ -55,6 +51,7 @@ ohos_unittest("window_options_utils_test") { ] external_deps = [ + "ability_base:base", "ability_runtime:app_manager", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", diff --git a/utils/server/startup/include/param.h b/utils/server/startup/include/param.h index fd096cf47a..bf8dcdf9aa 100644 --- a/utils/server/startup/include/param.h +++ b/utils/server/startup/include/param.h @@ -43,6 +43,7 @@ struct LoadParam : public Parcelable { sptr token = nullptr; sptr preToken = nullptr; std::string instanceKey = ""; + bool isKeepAlive = false; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/utils/server/startup/src/param.cpp b/utils/server/startup/src/param.cpp index 5905392a58..26ac50aa09 100644 --- a/utils/server/startup/src/param.cpp +++ b/utils/server/startup/src/param.cpp @@ -51,6 +51,9 @@ bool LoadParam::Marshalling(Parcel &parcel) const return false; } } + if (!parcel.WriteBool(isKeepAlive)) { + return false; + } return true; } @@ -71,6 +74,7 @@ bool LoadParam::ReadFromParcel(Parcel &parcel) return false; } } + isKeepAlive = parcel.ReadBool(); return true; }