From 39731416b674c7b46610a88ff67dada3d4a87170 Mon Sep 17 00:00:00 2001 From: fengyang Date: Tue, 29 Apr 2025 18:13:05 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=8C=87=E9=92=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: fengyang --- BUILD.gn | 46 ++- .../bundle_active_app_state_observer.h | 3 +- .../bundle_active_common_event_subscriber.h | 11 +- .../bundle_active_continuous_task_observer.h | 3 +- services/common/include/bundle_active_core.h | 12 +- .../common/include/bundle_active_service.h | 6 +- .../src/bundle_active_app_state_obsever.cpp | 13 +- ...bundle_active_continuous_task_observer.cpp | 13 +- services/common/src/bundle_active_core.cpp | 306 +++++++++--------- services/common/src/bundle_active_service.cpp | 72 ++--- .../include/bundle_active_group_controller.h | 21 +- .../include/bundle_active_group_handler.h | 5 +- .../src/bundle_active_group_controller.cpp | 92 ++++-- .../src/bundle_active_group_handler.cpp | 39 ++- .../include/bundle_active_report_controller.h | 42 +++ .../include/bundle_active_report_handler.h | 4 +- .../src/bundle_active_report_controller.cpp | 68 ++++ .../src/bundle_active_report_handler.cpp | 14 +- .../appgroupcallbackstub_fuzzer/BUILD.gn | 2 +- test/unittest/BUILD.gn | 50 +++ test/unittest/bundle_active_test_util.h | 63 ++++ test/unittest/bundle_active_total_test.cpp | 22 +- .../device_usage_statistics_mock_test.cpp | 7 +- .../device_usage_statistics_multi_test.cpp | 3 + .../device_usage_statistics_service_test.cpp | 233 ++++++------- .../unittest/device_usage_statistics_test.cpp | 3 + test/unittest/package_usage_test.cpp | 74 ++--- 27 files changed, 729 insertions(+), 498 deletions(-) create mode 100644 services/packageusage/include/bundle_active_report_controller.h create mode 100644 services/packageusage/src/bundle_active_report_controller.cpp create mode 100644 test/unittest/bundle_active_test_util.h diff --git a/BUILD.gn b/BUILD.gn index 5e72de7..ed3b8b1 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -87,7 +87,6 @@ ohos_shared_library("usagestatsinner") { "c_utils:utils", "ffrt:libffrt", "hilog:libhilog", - "hitrace:hitrace_meter", "ipc:ipc_core", "ipc:ipc_single", "samgr:samgr_proxy", @@ -246,6 +245,7 @@ ohos_shared_library("usagestatservice") { "services/packageusage/src/bundle_active_event_list.cpp", "services/packageusage/src/bundle_active_event_tracker.cpp", "services/packageusage/src/bundle_active_period_stats.cpp", + "services/packageusage/src/bundle_active_report_controller.cpp", "services/packageusage/src/bundle_active_report_handler.cpp", "services/packageusage/src/bundle_active_stats_combiner.cpp", "services/packageusage/src/bundle_active_user_service.cpp", @@ -325,6 +325,7 @@ ohos_static_library("usagestatservice_static") { "services/packageusage/src/bundle_active_event_list.cpp", "services/packageusage/src/bundle_active_event_tracker.cpp", "services/packageusage/src/bundle_active_period_stats.cpp", + "services/packageusage/src/bundle_active_report_controller.cpp", "services/packageusage/src/bundle_active_report_handler.cpp", "services/packageusage/src/bundle_active_stats_combiner.cpp", "services/packageusage/src/bundle_active_user_service.cpp", @@ -383,6 +384,49 @@ ohos_static_library("usagestatservice_static") { } } +ohos_static_library("usagestatsinner_static") { + cflags_cc = [ "-DDEVICE_USAGE_UNIT_TEST" ] + sources = [ + "interfaces/innerkits/src/app_group_callback_info.cpp", + "interfaces/innerkits/src/bundle_active_client.cpp", + "interfaces/innerkits/src/bundle_active_event.cpp", + "interfaces/innerkits/src/bundle_active_event_stats.cpp", + "interfaces/innerkits/src/bundle_active_form_record.cpp", + "interfaces/innerkits/src/bundle_active_module_record.cpp", + "interfaces/innerkits/src/bundle_active_package_stats.cpp", + ] + public_configs = [ ":usagestats_public_config" ] + deps = [ + ":app_group_callback_interface", + ":bundle_active_interface", + ":usagestatsutils", + ] + external_deps = [ + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] + + bundle_active_output_values = get_target_outputs(":bundle_active_interface") + sources += filter_include(bundle_active_output_values, [ "*.cpp" ]) + app_group_callback_output_values = + get_target_outputs(":app_group_callback_interface") + sources += filter_include(app_group_callback_output_values, [ "*.cpp" ]) + + part_name = "${device_usage_statistics_part_name}" + subsystem_name = "resourceschedule" + branch_protector_ret = "pac_ret" + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } +} + ohos_shared_library("usagestatsutils") { cflags_cc = [ "-fdata-sections", diff --git a/services/common/include/bundle_active_app_state_observer.h b/services/common/include/bundle_active_app_state_observer.h index ae985ea..34add74 100644 --- a/services/common/include/bundle_active_app_state_observer.h +++ b/services/common/include/bundle_active_app_state_observer.h @@ -33,7 +33,7 @@ using OHOS::AppExecFwk::ProcessData; class BundleActiveAppStateObserver : public ApplicationStateObserverStub { public: void OnAbilityStateChanged(const AbilityStateData &abilityStateData) override; - void Init(const std::shared_ptr& reportHandler); + void Init(); private: inline bool ValidateAppStateData(const AppStateData &appStateData) const { @@ -54,7 +54,6 @@ private: return processData.uid > 0 && processData.pid >= 0 && processData.bundleName.size() > 0; } - std::shared_ptr reportHandler_; }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/common/include/bundle_active_common_event_subscriber.h b/services/common/include/bundle_active_common_event_subscriber.h index c1e0b78..b0b2060 100644 --- a/services/common/include/bundle_active_common_event_subscriber.h +++ b/services/common/include/bundle_active_common_event_subscriber.h @@ -35,16 +35,11 @@ using CommonEventSupport = OHOS::EventFwk::CommonEventSupport; using CommonEventManager = OHOS::EventFwk::CommonEventManager; using MatchingSkills = OHOS::EventFwk::MatchingSkills; class BundleActiveGroupController; -class BundleActiveReportHandler; class BundleActiveCommonEventSubscriber : public CommonEventSubscriber { public: - BundleActiveCommonEventSubscriber(const CommonEventSubscribeInfo &subscriberInfo, - const std::shared_ptr activeGroupController, - const std::weak_ptr - bundleActiveReportHandler) : CommonEventSubscriber(subscriberInfo), - activeGroupController_(activeGroupController), - bundleActiveReportHandler_(bundleActiveReportHandler) {} + BundleActiveCommonEventSubscriber( + const CommonEventSubscribeInfo &subscriberInfo) : CommonEventSubscriber(subscriberInfo) {} ~BundleActiveCommonEventSubscriber() = default; void OnReceiveEvent(const CommonEventData &data) override; @@ -56,8 +51,6 @@ private: void HandlePackageAddEvent(const CommonEventData &data); void HandleLockEvent(const CommonEventData &data); ffrt::mutex mutex_; - std::weak_ptr activeGroupController_; - std::weak_ptr bundleActiveReportHandler_; }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/common/include/bundle_active_continuous_task_observer.h b/services/common/include/bundle_active_continuous_task_observer.h index ca7f97e..0a17687 100644 --- a/services/common/include/bundle_active_continuous_task_observer.h +++ b/services/common/include/bundle_active_continuous_task_observer.h @@ -38,11 +38,10 @@ public: void OnContinuousTaskStop(const std::shared_ptr &continuousTaskCallbackInfo) override; void OnRemoteDied(const wptr &object) override; - void Init(const std::shared_ptr& reportHandler); std::atomic isRemoteDied_ {false}; private: sptr bundleMgr_; - std::shared_ptr reportHandler_; + bool GetBundleMgr(); void ReportContinuousTaskEvent(const std::shared_ptr& continuousTaskCallbackInfo, const bool isStart); diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 4ad90d7..6d46b1c 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -68,7 +68,6 @@ public: } }; -class BundleActiveReportHandler; class BundleActiveCore : public BundleActiveStatsUpdateListener, public std::enable_shared_from_this { @@ -127,12 +126,6 @@ public: */ void InitBundleGroupController(); - /* - * function: SetHandler, BundleActiveService call it to set event report handler - * parameters: reportHandler - */ - void SetHandler(const std::shared_ptr& reportHandler); - /* * function: RestoreToDatabase, restore bundle usage data and form data to database * parameters: userId @@ -263,10 +256,7 @@ private: static const int64_t TIME_CHANGE_THRESHOLD_MILLIS = TWO_SECONDS; const int32_t DEFAULT_USER_ID = -1; std::map visibleActivities_; - // use weak_ptr to avoid circulate reference of core and handler. - std::weak_ptr handler_; - std::shared_ptr bundleGroupController_; - std::shared_ptr bundleGroupHandler_; + int64_t systemTimeShot_; int64_t realTimeShot_; ffrt::mutex mutex_; diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index 19f145d..5e86c33 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -223,7 +223,7 @@ protected: private: std::shared_ptr bundleActiveCore_; - std::shared_ptr reportHandler_; + sptr appStateObserver_; #ifdef BGTASKMGR_ENABLE std::shared_ptr continuousTaskObserver_; @@ -240,8 +240,8 @@ private: OHOS::Security::AccessToken::AccessTokenID tokenId); ErrCode CheckSystemAppOrNativePermission(const int32_t uid, OHOS::Security::AccessToken::AccessTokenID tokenId); ErrCode CheckNativePermission(OHOS::Security::AccessToken::AccessTokenID tokenId); - void InitAppStateSubscriber(const std::shared_ptr& reportHandler); - void InitContinuousSubscriber(const std::shared_ptr& reportHandler); + void InitAppStateSubscriber(); + void InitContinuousSubscriber(); bool SubscribeAppState(); bool SubscribeContinuousTask(); OHOS::sptr GetAppManagerInstance(); diff --git a/services/common/src/bundle_active_app_state_obsever.cpp b/services/common/src/bundle_active_app_state_obsever.cpp index caba8de..6273f54 100644 --- a/services/common/src/bundle_active_app_state_obsever.cpp +++ b/services/common/src/bundle_active_app_state_obsever.cpp @@ -20,16 +20,10 @@ #include "bundle_active_report_handler.h" #include "bundle_active_event.h" #include "bundle_active_account_helper.h" +#include "bundle_active_report_controller.h" namespace OHOS { namespace DeviceUsageStats { -void BundleActiveAppStateObserver::Init(const std::shared_ptr& reportHandler) -{ - if (reportHandler != nullptr) { - BUNDLE_ACTIVE_LOGI("Init report handler is not null, init success"); - reportHandler_ = reportHandler; - } -} void BundleActiveAppStateObserver::OnAbilityStateChanged(const AbilityStateData &abilityStateData) { @@ -65,10 +59,11 @@ void BundleActiveAppStateObserver::OnAbilityStateChanged(const AbilityStateData return; } BUNDLE_ACTIVE_LOGI("OnAblityStateChanged %{public}s", tmpHandlerObject.ToString().c_str()); - if (reportHandler_ != nullptr) { + auto reportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (reportHandler != nullptr) { std::shared_ptr handlerobjToPtr = std::make_shared(tmpHandlerObject); - reportHandler_->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr); + reportHandler->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr); } } return; diff --git a/services/common/src/bundle_active_continuous_task_observer.cpp b/services/common/src/bundle_active_continuous_task_observer.cpp index ee8b664..a5afa52 100644 --- a/services/common/src/bundle_active_continuous_task_observer.cpp +++ b/services/common/src/bundle_active_continuous_task_observer.cpp @@ -22,16 +22,10 @@ #include "bundle_active_event.h" #include "bundle_active_account_helper.h" #include "bundle_active_continuous_task_observer.h" +#include "bundle_active_report_controller.h" namespace OHOS { namespace DeviceUsageStats { -void BundleActiveContinuousTaskObserver::Init(const std::shared_ptr& reportHandler) -{ - if (reportHandler != nullptr) { - BUNDLE_ACTIVE_LOGI("report handler is not null, init success"); - reportHandler_ = reportHandler; - } -} void BundleActiveContinuousTaskObserver::OnContinuousTaskStart( const std::shared_ptr& continuousTaskCallbackInfo) @@ -111,11 +105,12 @@ void BundleActiveContinuousTaskObserver::ReportContinuousTaskEvent( tmpHandlerObject.userId_, tmpHandlerObject.event_.bundleName_.c_str(), tmpHandlerObject.event_.continuousTaskAbilityName_.c_str(), tmpHandlerObject.event_.eventId_, uid, pid); - if (reportHandler_ != nullptr) { + auto reportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (reportHandler != nullptr) { BUNDLE_ACTIVE_LOGI("BundleActiveAppStateObserver::OnAbilityStateChanged handler not null, SEND"); std::shared_ptr handlerobjToPtr = std::make_shared(tmpHandlerObject); - reportHandler_->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr); + reportHandler->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr); } } } diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index e371877..2212de0 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -27,7 +27,7 @@ #include "ffrt_inner.h" #include "bundle_constants.h" #include "hisysevent.h" - +#include "bundle_active_report_controller.h" namespace OHOS { namespace DeviceUsageStats { @@ -78,12 +78,8 @@ BundleActiveCore::~BundleActiveCore() void BundleActiveCore::DeInit() { - if (bundleGroupHandler_ != nullptr) { - bundleGroupHandler_->DeInit(); - } - if (!handler_.expired()) { - handler_.lock()->DeInit(); - } + BundleActiveGroupController::GetInstance().DeInit(); + BundleActiveReportController::GetInstance().DeInit(); } void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &data) @@ -109,48 +105,41 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da void BundleActiveCommonEventSubscriber::HandleScreenEvent() { - if (!bundleActiveReportHandler_.expired()) { + auto groupHandler = BundleActiveGroupController::GetInstance().GetBundleGroupHandler(); + if (groupHandler != nullptr) { sptr timer = MiscServices::TimeServiceClient::GetInstance(); - auto groupController = activeGroupController_.lock(); - if (groupController == nullptr) { - return; - } - bool isScreenOn = groupController->IsScreenOn(); + bool isScreenOn = BundleActiveGroupController::GetInstance().IsScreenOn(); BUNDLE_ACTIVE_LOGI("screen state change to %{public}d", isScreenOn); - groupController->OnScreenChanged(isScreenOn, timer->GetBootTimeMs()); + BundleActiveGroupController::GetInstance().OnScreenChanged(isScreenOn, timer->GetBootTimeMs()); } } void BundleActiveCommonEventSubscriber::HandleUserRemoveEvent(const CommonEventData &data) { - if (!bundleActiveReportHandler_.expired()) { - int32_t userId = data.GetCode(); - BUNDLE_ACTIVE_LOGI("remove user id %{public}d", userId); - BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); - std::shared_ptr handlerobjToPtr = - std::make_shared(tmpHandlerObject); - auto reportHandler = bundleActiveReportHandler_.lock(); - if (reportHandler == nullptr) { - return; - } - reportHandler->SendEvent(BundleActiveReportHandler::MSG_REMOVE_USER, handlerobjToPtr); + int32_t userId = data.GetCode(); + BUNDLE_ACTIVE_LOGI("remove user id %{public}d", userId); + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); + std::shared_ptr handlerobjToPtr = + std::make_shared(tmpHandlerObject); + auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (bundleActiveReportHandler == nullptr) { + return; } + bundleActiveReportHandler->SendEvent(BundleActiveReportHandler::MSG_REMOVE_USER, handlerobjToPtr); } void BundleActiveCommonEventSubscriber::HandleUserSwitchEvent(const CommonEventData &data) { - if (!bundleActiveReportHandler_.expired()) { - int32_t userId = data.GetCode(); - BUNDLE_ACTIVE_LOGI("OnReceiveEvent receive switched user event, user id is %{public}d", userId); - BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); - std::shared_ptr handlerobjToPtr = - std::make_shared(tmpHandlerObject); - auto reportHandler = bundleActiveReportHandler_.lock(); - if (reportHandler == nullptr) { - return; - } - reportHandler->SendEvent(BundleActiveReportHandler::MSG_SWITCH_USER, handlerobjToPtr); + auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (bundleActiveReportHandler == nullptr) { + return; } + int32_t userId = data.GetCode(); + BUNDLE_ACTIVE_LOGI("OnReceiveEvent receive switched user event, user id is %{public}d", userId); + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); + std::shared_ptr handlerobjToPtr = + std::make_shared(tmpHandlerObject); + bundleActiveReportHandler->SendEvent(BundleActiveReportHandler::MSG_SWITCH_USER, handlerobjToPtr); } void BundleActiveCommonEventSubscriber::HandlePackageRemoveEvent(const CommonEventData &data) @@ -160,19 +149,17 @@ void BundleActiveCommonEventSubscriber::HandlePackageRemoveEvent(const CommonEve std::string bundleName = data.GetWant().GetElement().GetBundleName(); BUNDLE_ACTIVE_LOGI("action is %{public}s, userID is %{public}d, bundlename is %{public}s", action.c_str(), userId, bundleName.c_str()); - if (!bundleActiveReportHandler_.expired()) { - BundleActiveReportHandlerObject tmpHandlerObject(userId, bundleName); - tmpHandlerObject.uid_ = data.GetWant().GetIntParam("uid", -1); - tmpHandlerObject.appIndex_ = data.GetWant().GetIntParam("appIndex", -1); - std::shared_ptr handlerobjToPtr = - std::make_shared(tmpHandlerObject); - auto reportHandler = bundleActiveReportHandler_.lock(); - if (reportHandler == nullptr) { - return; - } - reportHandler->SendEvent(BundleActiveReportHandler::MSG_BUNDLE_UNINSTALLED, - handlerobjToPtr); + BundleActiveReportHandlerObject tmpHandlerObject(userId, bundleName); + tmpHandlerObject.uid_ = data.GetWant().GetIntParam("uid", -1); + tmpHandlerObject.appIndex_ = data.GetWant().GetIntParam("appIndex", -1); + std::shared_ptr handlerobjToPtr = + std::make_shared(tmpHandlerObject); + auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (bundleActiveReportHandler == nullptr) { + return; } + bundleActiveReportHandler->SendEvent(BundleActiveReportHandler::MSG_BUNDLE_UNINSTALLED, + handlerobjToPtr); } void BundleActiveCommonEventSubscriber::HandlePackageAddEvent(const CommonEventData &data) @@ -182,19 +169,17 @@ void BundleActiveCommonEventSubscriber::HandlePackageAddEvent(const CommonEventD std::string bundleName = data.GetWant().GetElement().GetBundleName(); BUNDLE_ACTIVE_LOGI("action is %{public}s, userID is %{public}d, bundlename is %{public}s", action.c_str(), userId, bundleName.c_str()); - if (!bundleActiveReportHandler_.expired()) { - BundleActiveReportHandlerObject tmpHandlerObject(userId, bundleName); - tmpHandlerObject.uid_ = data.GetWant().GetIntParam("uid", -1); - tmpHandlerObject.appIndex_ = data.GetWant().GetIntParam("appIndex", -1); - std::shared_ptr handlerobjToPtr = - std::make_shared(tmpHandlerObject); - auto reportHandler = bundleActiveReportHandler_.lock(); - if (reportHandler == nullptr) { - return; - } - reportHandler->SendEvent(BundleActiveReportHandler::MSG_BUNDLE_INSTALLED, - handlerobjToPtr); + BundleActiveReportHandlerObject tmpHandlerObject(userId, bundleName); + tmpHandlerObject.uid_ = data.GetWant().GetIntParam("uid", -1); + tmpHandlerObject.appIndex_ = data.GetWant().GetIntParam("appIndex", -1); + std::shared_ptr handlerobjToPtr = + std::make_shared(tmpHandlerObject); + auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (bundleActiveReportHandler == nullptr) { + return; } + bundleActiveReportHandler->SendEvent(BundleActiveReportHandler::MSG_BUNDLE_INSTALLED, + handlerobjToPtr); } void BundleActiveCommonEventSubscriber::HandleLockEvent(const CommonEventData &data) @@ -202,9 +187,6 @@ void BundleActiveCommonEventSubscriber::HandleLockEvent(const CommonEventData &d std::string action = data.GetWant().GetAction(); int32_t userId = data.GetWant().GetIntParam("userId", 0); BUNDLE_ACTIVE_LOGI("action is %{public}s, userID is %{public}d", action.c_str(), userId); - if (bundleActiveReportHandler_.expired()) { - return; - } BundleActiveReportHandlerObject tmpHandlerObject(-1, ""); BundleActiveEvent newEvent; tmpHandlerObject.event_ = newEvent; @@ -217,7 +199,11 @@ void BundleActiveCommonEventSubscriber::HandleLockEvent(const CommonEventData &d sptr timer = MiscServices::TimeServiceClient::GetInstance(); tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); auto handlerobjToPtr = std::make_shared(tmpHandlerObject); - bundleActiveReportHandler_.lock()->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr); + auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (bundleActiveReportHandler == nullptr) { + return; + } + bundleActiveReportHandler->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr); } void BundleActiveCore::RegisterSubscriber() @@ -232,8 +218,7 @@ void BundleActiveCore::RegisterSubscriber() matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED); CommonEventSubscribeInfo subscriberInfo(matchingSkills); - commonEventSubscriber_ = std::make_shared(subscriberInfo, - bundleGroupController_, handler_); + commonEventSubscriber_ = std::make_shared(subscriberInfo); bool subscribeResult = CommonEventManager::SubscribeCommonEvent(commonEventSubscriber_); SubscriberLockScreenCommonEvent(); BUNDLE_ACTIVE_LOGD("Register for events result is %{public}d", subscribeResult); @@ -246,8 +231,7 @@ void BundleActiveCore::SubscriberLockScreenCommonEvent() matchingSkills.AddEvent(COMMON_EVENT_LOCK_SCREEN); CommonEventSubscribeInfo subscriberInfo(matchingSkills); subscriberInfo.SetPublisherBundleName(AppExecFwk::Constants::SCENE_BOARD_BUNDLE_NAME); - lockScreenSubscriber_ = std::make_shared(subscriberInfo, - bundleGroupController_, handler_); + lockScreenSubscriber_ = std::make_shared(subscriberInfo); CommonEventManager::SubscribeCommonEvent(lockScreenSubscriber_); } @@ -266,7 +250,6 @@ void BundleActiveCore::Init() } while (realTimeShot_ == -1 && systemTimeShot_ == -1); realTimeShot_ = timer->GetBootTimeMs(); systemTimeShot_ = GetSystemTimeMs(); - bundleGroupController_ = std::make_shared(debugCore_); BUNDLE_ACTIVE_LOGD("system time shot is %{public}lld", (long long)systemTimeShot_); bundleActiveConfigReader_ = std::make_shared(); bundleActiveConfigReader_->LoadConfig(); @@ -275,35 +258,21 @@ void BundleActiveCore::Init() void BundleActiveCore::InitBundleGroupController() { BUNDLE_ACTIVE_LOGD("InitBundleGroupController called"); - bundleGroupHandler_ = std::make_shared(debugCore_); - if (bundleGroupHandler_ == nullptr) { - return; - } - if (bundleGroupController_ != nullptr) { - bundleGroupHandler_->Init(bundleGroupController_); - bundleGroupController_->SetHandlerAndCreateUserHistory(bundleGroupHandler_, realTimeShot_, shared_from_this()); - BUNDLE_ACTIVE_LOGI("Init Set group controller and handler done"); - } else { - return; - } + BundleActiveGroupController::GetInstance().Init(debugCore_); + BundleActiveGroupController::GetInstance().CreateUserHistory(realTimeShot_, shared_from_this()); RegisterSubscriber(); std::vector activatedOsAccountIds; - bundleGroupController_->bundleGroupEnable_ = true; + BundleActiveGroupController::GetInstance().SetBundleGroupEnable(true); GetAllActiveUser(activatedOsAccountIds); if (activatedOsAccountIds.size() == 0) { BUNDLE_ACTIVE_LOGI("query activated account failed, no account activated"); return; } for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) { - bundleGroupController_->PeriodCheckBundleState(activatedOsAccountIds[i]); + BundleActiveGroupController::GetInstance().PeriodCheckBundleState(activatedOsAccountIds[i]); } } -void BundleActiveCore::SetHandler(const std::shared_ptr& reportHandler) -{ - handler_ = reportHandler; -} - std::shared_ptr WEAK_FUNC BundleActiveCore::GetUserDataAndInitializeIfNeeded( const int32_t userId, const int64_t timeStamp, const bool debug) { @@ -337,7 +306,7 @@ void BundleActiveCore::OnBundleUninstalled(const int32_t userId, const std::stri AddbundleUninstalledUid(uid); DelayRemoveBundleUninstalledUid(uid); service->DeleteUninstalledBundleStats(bundleName, uid, appIndex); - bundleGroupController_->OnBundleUninstalled(userId, bundleName, uid, appIndex); + BundleActiveGroupController::GetInstance().OnBundleUninstalled(userId, bundleName, uid, appIndex); } void BundleActiveCore::OnBundleInstalled(const int32_t userId, const std::string& bundleName, @@ -387,15 +356,18 @@ bool BundleActiveCore::isUninstalledApp(const int32_t uid) void BundleActiveCore::OnStatsChanged(const int32_t userId) { - if (!handler_.expired()) { - BundleActiveReportHandlerObject tmpHandlerObject; - tmpHandlerObject.userId_ = userId; - std::shared_ptr handlerobjToPtr = - std::make_shared(tmpHandlerObject); - if (handler_.lock()->HasEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK) == false) { - BUNDLE_ACTIVE_LOGI("OnStatsChanged send flush to disk event for user %{public}d", userId); - handler_.lock()->SendEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK, handlerobjToPtr, flushInterval_); - } + auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (bundleActiveReportHandler == nullptr) { + return; + } + BundleActiveReportHandlerObject tmpHandlerObject; + tmpHandlerObject.userId_ = userId; + std::shared_ptr handlerobjToPtr = + std::make_shared(tmpHandlerObject); + if (bundleActiveReportHandler->HasEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK) == false) { + BUNDLE_ACTIVE_LOGI("OnStatsChanged send flush to disk event for user %{public}d", userId); + bundleActiveReportHandler->SendEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK, + handlerobjToPtr, flushInterval_); } } @@ -409,17 +381,17 @@ void BundleActiveCore::RestoreAllData() } BUNDLE_ACTIVE_LOGI("userid is %{public}d ", service->userId_); service->RestoreStats(true); - if (bundleGroupController_ != nullptr && bundleGroupController_->bundleUserHistory_ != nullptr) { - bundleGroupController_->RestoreToDatabase(it.first); + if (BundleActiveGroupController::GetInstance().bundleUserHistory_ != nullptr) { + BundleActiveGroupController::GetInstance().RestoreToDatabase(it.first); } } - if (bundleGroupController_ != nullptr) { - bundleGroupController_->RestoreDurationToDatabase(); - } - if (!handler_.expired()) { - BUNDLE_ACTIVE_LOGI("RestoreAllData remove flush to disk event"); - handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); + BundleActiveGroupController::GetInstance().RestoreDurationToDatabase(); + auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (bundleActiveReportHandler == nullptr) { + return; } + BUNDLE_ACTIVE_LOGI("RestoreAllData remove flush to disk event"); + bundleActiveReportHandler->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); } void BundleActiveCore::RestoreToDatabase(const int32_t userId) @@ -443,34 +415,36 @@ void BundleActiveCore::RestoreToDatabaseLocked(const int32_t userId) if (it != userStatServices_.end()) { it->second->RestoreStats(false); } - if (bundleGroupController_ != nullptr) { - bundleGroupController_->RestoreDurationToDatabase(); - } - if (!handler_.expired()) { - BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked remove flush to disk event"); - handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); + BundleActiveGroupController::GetInstance().RestoreDurationToDatabase(); + auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (bundleActiveReportHandler == nullptr) { + return; } + BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked remove flush to disk event"); + bundleActiveReportHandler->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); } void BundleActiveCore::PreservePowerStateInfo(const int32_t eventId) { - if (!handler_.expired()) { - int32_t userId = -1; - std::vector currentActiveUser; - BundleActiveCore::GetAllActiveUser(currentActiveUser); - if (currentActiveUser.size() == 1) { - userId = currentActiveUser.front(); - } - BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); - BundleActiveEvent newEvent; - tmpHandlerObject.event_ = newEvent; - tmpHandlerObject.event_.eventId_ = eventId; - sptr timer = MiscServices::TimeServiceClient::GetInstance(); - tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); - std::shared_ptr handlerobjToPtr = - std::make_shared(tmpHandlerObject); - handler_.lock()->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr); + auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (bundleActiveReportHandler == nullptr) { + return; } + int32_t userId = -1; + std::vector currentActiveUser; + BundleActiveCore::GetAllActiveUser(currentActiveUser); + if (currentActiveUser.size() == 1) { + userId = currentActiveUser.front(); + } + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); + BundleActiveEvent newEvent; + tmpHandlerObject.event_ = newEvent; + tmpHandlerObject.event_.eventId_ = eventId; + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); + std::shared_ptr handlerobjToPtr = + std::make_shared(tmpHandlerObject); + bundleActiveReportHandler->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr); } void BundleActiveCore::ShutDown() @@ -488,7 +462,7 @@ void BundleActiveCore::ShutDown() return; } for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) { - bundleGroupController_->ShutDown(timeStamp, activatedOsAccountIds[i]); + BundleActiveGroupController::GetInstance().ShutDown(timeStamp, activatedOsAccountIds[i]); } ReportEventToAllUserId(event); RestoreAllData(); @@ -497,7 +471,7 @@ void BundleActiveCore::ShutDown() void BundleActiveCore::OnStatsReload() { BUNDLE_ACTIVE_LOGD("OnStatsReload called"); - bundleGroupController_->CheckIdleStatsOneTime(); + BundleActiveGroupController::GetInstance().CheckIdleStatsOneTime(); } void BundleActiveCore::OnSystemUpdate(int32_t userId) @@ -518,27 +492,31 @@ int64_t WEAK_FUNC BundleActiveCore::CheckTimeChangeAndGetWallTime(int32_t userId BUNDLE_ACTIVE_LOGD("asystime is %{public}lld, artime is %{public}lld, esystime is %{public}lld, " "diff is %{public}lld", (long long)actualSystemTime, (long long)actualRealTime, (long long)expectedSystemTime, (long long)diffSystemTime); - if (std::abs(diffSystemTime) > TIME_CHANGE_THRESHOLD_MILLIS) { - // 时区变换逻辑 - auto it = userStatServices_.find(userId); - if (it != userStatServices_.end()) { - BundleActiveEvent event; - event.eventId_ = BundleActiveEvent::FLUSH; - event.timeStamp_ = expectedSystemTime; - event.abilityId_ = ""; - it->second->ReportEvent(event); - it->second->RestoreStats(true); - it->second->RenewTableTime(expectedSystemTime, actualSystemTime); - it->second->LoadActiveStats(actualSystemTime, true, true); - it->second->LoadModuleAndFormStats(); - if (!handler_.expired()) { - BUNDLE_ACTIVE_LOGI("CheckTimeChangeAndGetWallTime remove flush to disk event"); - handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); - } + if (std::abs(diffSystemTime) < TIME_CHANGE_THRESHOLD_MILLIS) { + return actualSystemTime; + } + + // 时区变换逻辑 + auto it = userStatServices_.find(userId); + if (it != userStatServices_.end()) { + BundleActiveEvent event; + event.eventId_ = BundleActiveEvent::FLUSH; + event.timeStamp_ = expectedSystemTime; + event.abilityId_ = ""; + it->second->ReportEvent(event); + it->second->RestoreStats(true); + it->second->RenewTableTime(expectedSystemTime, actualSystemTime); + it->second->LoadActiveStats(actualSystemTime, true, true); + it->second->LoadModuleAndFormStats(); + auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (bundleActiveReportHandler == nullptr) { + return actualSystemTime; } - realTimeShot_ = actualRealTime; - systemTimeShot_ = actualSystemTime; + BUNDLE_ACTIVE_LOGI("CheckTimeChangeAndGetWallTime remove flush to disk event"); + bundleActiveReportHandler->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); } + realTimeShot_ = actualRealTime; + systemTimeShot_ = actualSystemTime; return actualSystemTime; } @@ -559,7 +537,7 @@ void BundleActiveCore::OnUserRemoved(const int32_t userId) userStatServices_[userId]->OnUserRemoved(); userStatServices_[userId].reset(); userStatServices_.erase(userId); - bundleGroupController_->OnUserRemoved(userId); + BundleActiveGroupController::GetInstance().OnUserRemoved(userId); } void BundleActiveCore::OnUserSwitched(const int32_t userId) @@ -584,7 +562,7 @@ void BundleActiveCore::OnUserSwitched(const int32_t userId) } for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) { BUNDLE_ACTIVE_LOGI("start to period check for userId %{public}d", activatedOsAccountIds[i]); - bundleGroupController_->OnUserSwitched(activatedOsAccountIds[i], currentUsedUser_); + BundleActiveGroupController::GetInstance().OnUserSwitched(activatedOsAccountIds[i], currentUsedUser_); } currentUsedUser_ = userId; OnStatsChanged(userId); @@ -607,7 +585,7 @@ int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, int32_t userId) int64_t bootBasedTimeStamp = timer->GetBootTimeMs(); if (BundleActiveBundleMgrHelper::GetInstance()->IsLauncherApp(event.bundleName_, userId)) { BUNDLE_ACTIVE_LOGI("launcher event, only update app group"); - bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId); + BundleActiveGroupController::GetInstance().ReportEvent(event, bootBasedTimeStamp, userId); return 0; } BUNDLE_ACTIVE_LOGD("report event called, bundle name %{public}s time %{public}lld userId %{public}d, " @@ -630,7 +608,7 @@ int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, int32_t userId) } service->ReportModuleEvent(event); service->ReportEvent(event); - bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId); + BundleActiveGroupController::GetInstance().ReportEvent(event, bootBasedTimeStamp, userId); return 0; } @@ -776,23 +754,23 @@ ErrCode BundleActiveCore::SetAppGroup( int32_t newReason = GROUP_CONTROL_REASON_FORCED; sptr timer = MiscServices::TimeServiceClient::GetInstance(); int64_t bootBasedTimeStamp = timer->GetBootTimeMs(); - return bundleGroupController_->SetAppGroup( + return BundleActiveGroupController::GetInstance().SetAppGroup( bundleName, userId, newGroup, newReason, bootBasedTimeStamp, isFlush); } ErrCode BundleActiveCore::QueryAppGroup(int32_t& appGroup, const std::string& bundleName, const int32_t userId) { - return bundleGroupController_->QueryAppGroup(appGroup, bundleName, userId); + return BundleActiveGroupController::GetInstance().QueryAppGroup(appGroup, bundleName, userId); } int32_t BundleActiveCore::IsBundleIdle(const std::string& bundleName, const int32_t userId) { - return bundleGroupController_->IsBundleIdle(bundleName, userId); + return BundleActiveGroupController::GetInstance().IsBundleIdle(bundleName, userId); } bool BundleActiveCore::IsBundleUsePeriod(const std::string& bundleName, const int32_t userId) { - if (!bundleGroupController_->IsBundleInstalled(bundleName, userId)) { + if (!BundleActiveGroupController::GetInstance().IsBundleInstalled(bundleName, userId)) { BUNDLE_ACTIVE_LOGI("IsBundleUsePeriod is not bundleInstalled"); return false; } @@ -852,9 +830,13 @@ void BundleActiveCore::OnAppGroupChanged(const AppGroupCallbackInfo& callbackInf { std::shared_ptr bundleActiveCore = shared_from_this(); AccessToken::HapTokenInfo tokenInfo = AccessToken::HapTokenInfo(); - bundleGroupHandler_->PostTask([bundleActiveCore, callbackInfo, tokenInfo]() { - bundleActiveCore->NotifOberserverGroupChanged(callbackInfo, tokenInfo); - }); + auto bundleGroupHandler = BundleActiveGroupController::GetInstance().GetBundleGroupHandler(); + if (bundleGroupHandler != nullptr) { + bundleGroupHandler->PostTask([bundleActiveCore, callbackInfo, tokenInfo]() { + bundleActiveCore->NotifOberserverGroupChanged(callbackInfo, tokenInfo); + }); + } + HiSysEventWrite(RSS, "UPDATE_GROUP_SCENE", HiviewDFX::HiSysEvent::EventType::STATISTIC, "UPDATE_GROUP_BUNDLENAME", callbackInfo.GetBundleName(), @@ -970,7 +952,11 @@ void BundleActiveCore::OnObserverDied(const wptr &remote) return; } std::shared_ptr bundleActiveCore = shared_from_this(); - bundleGroupHandler_->PostSyncTask([bundleActiveCore, &remote]() { + auto bundleGroupHandler = BundleActiveGroupController::GetInstance().GetBundleGroupHandler(); + if (bundleGroupHandler == nullptr) { + return; + } + bundleGroupHandler->PostSyncTask([bundleActiveCore, &remote]() { bundleActiveCore->OnObserverDiedInner(remote); }); } diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index a0dc92d..134ffb4 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -33,6 +33,7 @@ #include "tokenid_kit.h" #include "xcollie/watchdog.h" #include "bundle_active_util.h" +#include "bundle_active_report_controller.h" #include "bundle_active_service.h" @@ -130,19 +131,12 @@ void BundleActiveService::InitService() bundleActiveCore_ = std::make_shared(); bundleActiveCore_->Init(); } - if (reportHandler_ == nullptr) { - reportHandler_ = std::make_shared(); - if (reportHandler_ == nullptr) { - return; - } - reportHandler_->Init(bundleActiveCore_); - } - if (reportHandler_ != nullptr && bundleActiveCore_ != nullptr) { - BUNDLE_ACTIVE_LOGI("core and handler is not null"); - bundleActiveCore_->SetHandler(reportHandler_); - } else { + BundleActiveReportController::GetInstance().Init(bundleActiveCore_); + auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (bundleActiveReportHandler == nullptr || bundleActiveCore_ == nullptr) { return; } + BUNDLE_ACTIVE_LOGI("core and handler is not null"); #ifdef DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE shutdownCallback_ = new (std::nothrow) BundleActiveShutdownCallbackService(bundleActiveCore_); powerStateCallback_ = new (std::nothrow) BundleActivePowerStateCallbackService(bundleActiveCore_); @@ -155,8 +149,8 @@ void BundleActiveService::InitService() powerManagerClient.RegisterPowerStateCallback(powerStateCallback_); } #endif - InitAppStateSubscriber(reportHandler_); - InitContinuousSubscriber(reportHandler_); + InitAppStateSubscriber(); + InitContinuousSubscriber(); bundleActiveCore_->InitBundleGroupController(); SubscribeAppState(); SubscribeContinuousTask(); @@ -173,7 +167,7 @@ OHOS::sptr BundleActiveService::GetAppManagerInstance return OHOS::iface_cast(object); } -void BundleActiveService::InitAppStateSubscriber(const std::shared_ptr& reportHandler) +void BundleActiveService::InitAppStateSubscriber() { if (!appStateObserver_) { appStateObserver_ = new (std::nothrow)BundleActiveAppStateObserver(); @@ -181,16 +175,14 @@ void BundleActiveService::InitAppStateSubscriber(const std::shared_ptrInit(reportHandler); } } -void BundleActiveService::InitContinuousSubscriber(const std::shared_ptr& reportHandler) +void BundleActiveService::InitContinuousSubscriber() { #ifdef BGTASKMGR_ENABLE if (continuousTaskObserver_ == nullptr) { continuousTaskObserver_ = std::make_shared(); - continuousTaskObserver_->Init(reportHandler); } #endif } @@ -238,6 +230,7 @@ void BundleActiveService::OnStop() return; } #endif + bundleActiveCore_->DeInit(); BUNDLE_ACTIVE_LOGI("[Server] OnStop"); ready_ = false; } @@ -245,30 +238,33 @@ void BundleActiveService::OnStop() ErrCode BundleActiveService::ReportEvent(const BundleActiveEvent& event, int32_t userId) { AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); - if (CheckNativePermission(tokenId) == ERR_OK) { - AccessToken::NativeTokenInfo callingTokenInfo; - AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, callingTokenInfo); - int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGD("calling process name is %{public}s, uid is %{public}d", - callingTokenInfo.processName.c_str(), callingUid); - if (callingTokenInfo.processName == PERMITTED_PROCESS_NAME) { - BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); - BundleActiveEvent eventNew(event); - tmpHandlerObject.event_ = eventNew; - sptr timer = MiscServices::TimeServiceClient::GetInstance(); - tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); - std::shared_ptr handlerobjToPtr = - std::make_shared(tmpHandlerObject); - reportHandler_->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr); - return ERR_OK; - } else { - BUNDLE_ACTIVE_LOGE("token does not belong to fms service process, return"); - return ERR_PERMISSION_DENIED; - } - } else { + if (CheckNativePermission(tokenId) != ERR_OK) { BUNDLE_ACTIVE_LOGE("token does not belong to native process, return"); return ERR_PERMISSION_DENIED; } + + AccessToken::NativeTokenInfo callingTokenInfo; + AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, callingTokenInfo); + int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); + BUNDLE_ACTIVE_LOGD("calling process name is %{public}s, uid is %{public}d", + callingTokenInfo.processName.c_str(), callingUid); + if (callingTokenInfo.processName != PERMITTED_PROCESS_NAME) { + BUNDLE_ACTIVE_LOGE("token does not belong to fms service process, return"); + return ERR_PERMISSION_DENIED; + } + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); + BundleActiveEvent eventNew(event); + tmpHandlerObject.event_ = eventNew; + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); + std::shared_ptr handlerobjToPtr = + std::make_shared(tmpHandlerObject); + auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (bundleActiveReportHandler == nullptr) { + return ERR_OK; + } + bundleActiveReportHandler->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr); + return ERR_OK; } ErrCode BundleActiveService::IsBundleIdle(bool& isBundleIdle, const std::string& bundleName, int32_t userId) diff --git a/services/packagegroup/include/bundle_active_group_controller.h b/services/packagegroup/include/bundle_active_group_controller.h index d587f93..e9c7f29 100644 --- a/services/packagegroup/include/bundle_active_group_controller.h +++ b/services/packagegroup/include/bundle_active_group_controller.h @@ -35,8 +35,11 @@ namespace DeviceUsageStats { using namespace DeviceUsageStatsGroupConst; class BundleActiveGroupHandler; -class BundleActiveGroupController : public std::enable_shared_from_this { +class BundleActiveGroupController { public: + static BundleActiveGroupController& GetInstance(); + void Init(const bool debug); + void DeInit(); #ifdef DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE using PowerMgrClient = OHOS::PowerMgr::PowerMgrClient; #endif @@ -46,7 +49,6 @@ public: using BundleFlag = OHOS::AppExecFwk::BundleFlag; using ApplicationFlag = OHOS::AppExecFwk::ApplicationFlag; OHOS::AppExecFwk::ApplicationFlag flag = OHOS::AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO; - bool bundleGroupEnable_ = true; const int32_t LEVEL_GROUP[4] = { ACTIVE_GROUP_ALIVE, ACTIVE_GROUP_DAILY, @@ -55,10 +57,8 @@ public: }; std::vector screenTimeLevel_ = {0, 0, 0, 0}; std::vector bootTimeLevel_ = {0, 0, 0, 0}; - BundleActiveGroupController(const bool debug); - ~BundleActiveGroupController() {} std::shared_ptr bundleUserHistory_; - void SetHandlerAndCreateUserHistory(const std::shared_ptr& groupHandler, + void CreateUserHistory( const int64_t bootFromTimeStamp, const std::shared_ptr& bundleActiveCore); void ReportEvent(const BundleActiveEvent& event, const int64_t bootBasedTimeStamp, const int32_t userId); void CheckAndUpdateGroup(const std::string& bundleName, int32_t userId, @@ -83,16 +83,23 @@ public: ErrCode QueryAppGroup(int32_t& appGroup, const std::string& bundleName, const int32_t userId); void ShutDown(const int64_t bootBasedTimeStamp, const int32_t userId); void OnUserSwitched(const int32_t userId, const int32_t currentUsedUser); - + void SetBundleGroupEnable(bool bundleGroupEnable); + bool GetBundleGroupEnable(); + std::shared_ptr GetBundleGroupHandler(); private: + BundleActiveGroupController() = default; + ~BundleActiveGroupController() = default; ffrt::mutex mutex_; + ffrt::mutex initMutex_; bool GetBundleMgrProxy(); - std::weak_ptr activeGroupHandler_; + std::shared_ptr activeGroupHandler_; int64_t timeoutForDirectlyUse_; int64_t timeoutForNotifySeen_; int64_t timeoutForSystemInteraction_; int64_t timeoutCalculated_ = 0; std::map eventIdMatchReason_; + bool bundleGroupEnable_ = true; + bool isInit_ = false; sptr sptrBundleMgr_; bool calculationTimeOut(const std::shared_ptr& oneBundleHistory, const int64_t bootBasedTimeStamp); diff --git a/services/packagegroup/include/bundle_active_group_handler.h b/services/packagegroup/include/bundle_active_group_handler.h index 6c8b188..ffb093d 100644 --- a/services/packagegroup/include/bundle_active_group_handler.h +++ b/services/packagegroup/include/bundle_active_group_handler.h @@ -35,7 +35,7 @@ public: ~BundleActiveGroupHandlerObject() {} }; -class BundleActiveGroupHandler : public std::enable_shared_from_this { +class BundleActiveGroupHandler { public: explicit BundleActiveGroupHandler(const bool debug); ~BundleActiveGroupHandler() = default; @@ -55,7 +55,7 @@ public: void RemoveCheckBundleMsg(const std::string& msgKey); void PostSyncTask(const std::function& fuc); void PostTask(const std::function& fuc); - void Init(const std::shared_ptr& bundleActiveController); + void Init(); void DeInit(); static const int32_t MSG_CHECK_DEFAULT_BUNDLE_STATE; static const int32_t MSG_ONE_TIME_CHECK_BUNDLE_STATE; @@ -71,7 +71,6 @@ private: std::shared_ptr ffrtQueue_; std::map> taskHandlerMap_; std::map checkBundleTaskMap_; - std::shared_ptr bundleActiveGroupController_; }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index 3ce28c4..eadc901 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -26,16 +26,26 @@ namespace OHOS { namespace DeviceUsageStats { using namespace DeviceUsageStatsGroupConst; const int32_t MAIN_APP_INDEX = 0; + +BundleActiveGroupController& BundleActiveGroupController::GetInstance() +{ + static BundleActiveGroupController instance; + return instance; +} BundleActiveGroupHandlerObject::BundleActiveGroupHandlerObject() { - bundleName_ = ""; - userId_ = -1; - uid_ = -1; + bundleName_ = ""; + userId_ = -1; + uid_ = -1; } -BundleActiveGroupController::BundleActiveGroupController(const bool debug) +void BundleActiveGroupController::Init(const bool debug) { + std::lock_guard lock(initMutex_); + if (isInit_) { + return; + } timeoutForDirectlyUse_ = debug ? THREE_MINUTE : ONE_HOUR; timeoutForNotifySeen_ = debug ? ONE_MINUTE : TWELVE_HOUR; timeoutForSystemInteraction_ = debug ? ONE_MINUTE : TEN_MINUTE; @@ -50,6 +60,29 @@ BundleActiveGroupController::BundleActiveGroupController(const bool debug) {BundleActiveEvent::NOTIFICATION_SEEN, GROUP_EVENT_REASON_NOTIFY_SEEN}, {BundleActiveEvent::LONG_TIME_TASK_STARTTED, GROUP_EVENT_REASON_LONG_TIME_TASK_STARTTED}, }; + activeGroupHandler_ = std::make_shared(debug); + activeGroupHandler_->Init(); + isInit_ = true; +} + +void BundleActiveGroupController::DeInit() +{ + std::lock_guard lock(initMutex_); + if (!isInit_) { + return; + } + isInit_ = false; + activeGroupHandler_->DeInit(); +} + + +std::shared_ptr BundleActiveGroupController::GetBundleGroupHandler() +{ + std::lock_guard lock(initMutex_); + if (!isInit_) { + return nullptr; + } + return activeGroupHandler_; } void BundleActiveGroupController::RestoreDurationToDatabase() @@ -68,41 +101,48 @@ void BundleActiveGroupController::OnUserRemoved(const int32_t userId) { std::lock_guard lock(mutex_); bundleUserHistory_->userHistory_.erase(userId); - if (!activeGroupHandler_.expired()) { - activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE); + if (activeGroupHandler_ != nullptr) { + activeGroupHandler_->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE); } } +void BundleActiveGroupController::SetBundleGroupEnable(bool bundleGroupEnable) +{ + bundleGroupEnable_ = bundleGroupEnable; +} + +bool BundleActiveGroupController::GetBundleGroupEnable() +{ + return bundleGroupEnable_; +} + void BundleActiveGroupController::OnUserSwitched(const int32_t userId, const int32_t currentUsedUser) { BUNDLE_ACTIVE_LOGI("last time check for user %{public}d", currentUsedUser); CheckEachBundleState(currentUsedUser); bundleUserHistory_->WriteBundleUsage(currentUsedUser); std::lock_guard lock(mutex_); - auto activeGroupHandler = activeGroupHandler_.lock(); - if (!activeGroupHandler_.expired()) { - activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE); - activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_DEFAULT_BUNDLE_STATE); - activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_NOTIFICATION_SEEN_BUNDLE_STATE); - activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_SYSTEM_INTERACTIVE_BUNDLE_STATE); + if (activeGroupHandler_ != nullptr) { + activeGroupHandler_->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE); + activeGroupHandler_->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_DEFAULT_BUNDLE_STATE); + activeGroupHandler_->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_NOTIFICATION_SEEN_BUNDLE_STATE); + activeGroupHandler_->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_SYSTEM_INTERACTIVE_BUNDLE_STATE); } PeriodCheckBundleState(userId); } void BundleActiveGroupController::OnScreenChanged(const bool& isScreenOn, const int64_t bootFromTimeStamp) { - if (!activeGroupHandler_.expired()) { - std::shared_ptr bundleActiveGroupController = shared_from_this(); - activeGroupHandler_.lock()->PostTask([bundleActiveGroupController, isScreenOn, bootFromTimeStamp]() { - std::lock_guard lock(bundleActiveGroupController->mutex_); - bundleActiveGroupController->bundleUserHistory_->UpdateBootBasedAndScreenTime(isScreenOn, + if (activeGroupHandler_ != nullptr) { + activeGroupHandler_->PostTask([isScreenOn, bootFromTimeStamp]() { + std::lock_guard lock(BundleActiveGroupController::GetInstance().mutex_); + BundleActiveGroupController::GetInstance().bundleUserHistory_->UpdateBootBasedAndScreenTime(isScreenOn, bootFromTimeStamp); }); } } -void BundleActiveGroupController::SetHandlerAndCreateUserHistory( - const std::shared_ptr& groupHandler, const int64_t bootFromTimeStamp, +void BundleActiveGroupController::CreateUserHistory(const int64_t bootFromTimeStamp, const std::shared_ptr& bundleActiveCore) { if (bundleUserHistory_ == nullptr) { @@ -111,7 +151,6 @@ void BundleActiveGroupController::SetHandlerAndCreateUserHistory( bundleUserHistory_ = std::make_shared(bootFromTimeStamp, bundleActiveCore); } OnScreenChanged(IsScreenOn(), bootFromTimeStamp); - activeGroupHandler_ = groupHandler; } void BundleActiveGroupController::OnBundleUninstalled(const int32_t userId, const std::string& bundleName, @@ -176,12 +215,12 @@ bool BundleActiveGroupController::GetBundleMgrProxy() void BundleActiveGroupController::PeriodCheckBundleState(const int32_t userId) { BUNDLE_ACTIVE_LOGI("PeriodCheckBundleState called"); - if (!activeGroupHandler_.expired()) { + if (activeGroupHandler_ != nullptr) { BundleActiveGroupHandlerObject tmpGroupHandlerObj; tmpGroupHandlerObj.userId_ = userId; std::shared_ptr handlerobjToPtr = std::make_shared(tmpGroupHandlerObj); - activeGroupHandler_.lock()->SendEvent(BundleActiveGroupHandler::MSG_CHECK_DEFAULT_BUNDLE_STATE, + activeGroupHandler_->SendEvent(BundleActiveGroupHandler::MSG_CHECK_DEFAULT_BUNDLE_STATE, handlerobjToPtr, FIVE_SECOND); } } @@ -208,9 +247,8 @@ void BundleActiveGroupController::CheckIdleStatsOneTime() BundleActiveGroupHandlerObject tmpGroupHandlerObj; std::shared_ptr handlerobjToPtr = std::make_shared(tmpGroupHandlerObj); - auto activeGroupHandler = activeGroupHandler_.lock(); - if (!activeGroupHandler_.expired()) { - activeGroupHandler_.lock()->SendEvent(BundleActiveGroupHandler::MSG_ONE_TIME_CHECK_BUNDLE_STATE, + if (activeGroupHandler_ != nullptr) { + activeGroupHandler_->SendEvent(BundleActiveGroupHandler::MSG_ONE_TIME_CHECK_BUNDLE_STATE, handlerobjToPtr); } } @@ -291,8 +329,8 @@ void BundleActiveGroupController::SendCheckBundleMsg(const BundleActiveEvent& ev tmpGroupHandlerObj.uid_ = event.uid_; std::shared_ptr handlerobjToPtr = std::make_shared(tmpGroupHandlerObj); - if (!activeGroupHandler_.expired()) { - activeGroupHandler_.lock()->SendCheckBundleMsg(checkBundleMsgEventId, handlerobjToPtr, timeUntilNextCheck); + if (activeGroupHandler_ != nullptr) { + activeGroupHandler_->SendCheckBundleMsg(checkBundleMsgEventId, handlerobjToPtr, timeUntilNextCheck); } } diff --git a/services/packagegroup/src/bundle_active_group_handler.cpp b/services/packagegroup/src/bundle_active_group_handler.cpp index c7c8b7f..058ac01 100644 --- a/services/packagegroup/src/bundle_active_group_handler.cpp +++ b/services/packagegroup/src/bundle_active_group_handler.cpp @@ -65,14 +65,9 @@ void BundleActiveGroupHandler::DeInit() checkBundleTaskMap_.clear(); } -void BundleActiveGroupHandler::Init(const std::shared_ptr& bundleActiveController) +void BundleActiveGroupHandler::Init() { BUNDLE_ACTIVE_LOGI("Init called"); - if (bundleActiveController == nullptr) { - BUNDLE_ACTIVE_LOGE("Init failed bundleActiveController is null"); - return; - } - bundleActiveGroupController_ = bundleActiveController; ffrtQueue_ = std::make_shared(DEVICE_GROUP_HANDLE_QUEUE.c_str(), ffrt::queue_attr().qos(ffrt::qos_default)); if (ffrtQueue_ == nullptr) { @@ -98,8 +93,11 @@ void BundleActiveGroupHandler::SendCheckBundleMsg(const int32_t& eventId, if (checkBundleTaskMap_.find(msgKey) != checkBundleTaskMap_.end()) { RemoveCheckBundleMsg(msgKey); } - auto groupHandler = shared_from_this(); - checkBundleTaskMap_[msgKey] = ffrtQueue_->submit_h([groupHandler, eventId, handlerobj, msgKey]() { + checkBundleTaskMap_[msgKey] = ffrtQueue_->submit_h([eventId, handlerobj, msgKey]() { + auto groupHandler = BundleActiveGroupController::GetInstance().GetBundleGroupHandler(); + if (groupHandler == nullptr) { + return; + } groupHandler->ProcessEvent(eventId, handlerobj); std::lock_guard lock(groupHandler->checkBundleTaskMutex_); if (groupHandler->checkBundleTaskMap_.find(msgKey) == groupHandler->checkBundleTaskMap_.end()) { @@ -141,13 +139,20 @@ void BundleActiveGroupHandler::SendEvent(const int32_t& eventId, BUNDLE_ACTIVE_LOGE("init failed"); return; } - auto groupHandler = shared_from_this(); int64_t ffrtDelayTime = BundleActiveUtil::GetFFRTDelayTime(delayTime); std::lock_guard lock(taskHandlerMutex_); if (taskHandlerMap_.find(eventId) == taskHandlerMap_.end()) { taskHandlerMap_[eventId] = std::queue(); } - ffrt::task_handle taskHandle = ffrtQueue_->submit_h([groupHandler, eventId, handlerobj]() { + ffrt::task_handle taskHandle = ffrtQueue_->submit_h([eventId, handlerobj]() { + auto groupHandler = BundleActiveGroupController::GetInstance().GetBundleGroupHandler(); + if (groupHandler == nullptr) { + return; + } + if (!groupHandler->isInited_) { + BUNDLE_ACTIVE_LOGE("init failed"); + return; + } groupHandler->ProcessEvent(eventId, handlerobj); std::lock_guard lock(groupHandler->taskHandlerMutex_); if (groupHandler->taskHandlerMap_.find(eventId) == groupHandler->taskHandlerMap_.end()) { @@ -212,17 +217,17 @@ void BundleActiveGroupHandler::ProcessEvent(const int32_t& eventId, BundleActiveGroupHandlerObject tmpHandlerobj = *handlerobj; sptr timer = MiscServices::TimeServiceClient::GetInstance(); int64_t bootBasedTimeStamp = timer->GetBootTimeMs(); - bundleActiveGroupController_->CheckAndUpdateGroup( + BundleActiveGroupController::GetInstance().CheckAndUpdateGroup( tmpHandlerobj.bundleName_, tmpHandlerobj.userId_, tmpHandlerobj.uid_, bootBasedTimeStamp); - bundleActiveGroupController_->RestoreToDatabase(tmpHandlerobj.userId_); + BundleActiveGroupController::GetInstance().RestoreToDatabase(tmpHandlerobj.userId_); break; } case MSG_ONE_TIME_CHECK_BUNDLE_STATE: { std::vector activatedOsAccountIds; BundleActiveAccountHelper::GetActiveUserId(activatedOsAccountIds); for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) { - bundleActiveGroupController_->CheckEachBundleState(activatedOsAccountIds[i]); - bundleActiveGroupController_->RestoreToDatabase(activatedOsAccountIds[i]); + BundleActiveGroupController::GetInstance().CheckEachBundleState(activatedOsAccountIds[i]); + BundleActiveGroupController::GetInstance().RestoreToDatabase(activatedOsAccountIds[i]); } RemoveEvent(MSG_ONE_TIME_CHECK_BUNDLE_STATE); break; @@ -232,13 +237,13 @@ void BundleActiveGroupHandler::ProcessEvent(const int32_t& eventId, return; } BundleActiveGroupHandlerObject tmpHandlerobj = *handlerobj; - if (bundleActiveGroupController_->CheckEachBundleState(tmpHandlerobj.userId_) && - bundleActiveGroupController_->bundleGroupEnable_) { + if (BundleActiveGroupController::GetInstance().CheckEachBundleState(tmpHandlerobj.userId_) && + BundleActiveGroupController::GetInstance().GetBundleGroupEnable()) { BundleActiveGroupHandlerObject GroupHandlerObj; GroupHandlerObj.userId_ = tmpHandlerobj.userId_; std::shared_ptr handlerobjToPtr = std::make_shared(GroupHandlerObj); - bundleActiveGroupController_->RestoreToDatabase(GroupHandlerObj.userId_); + BundleActiveGroupController::GetInstance().RestoreToDatabase(GroupHandlerObj.userId_); SendEvent(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE, handlerobjToPtr, checkIdleInterval_); } break; diff --git a/services/packageusage/include/bundle_active_report_controller.h b/services/packageusage/include/bundle_active_report_controller.h new file mode 100644 index 0000000..958c1a2 --- /dev/null +++ b/services/packageusage/include/bundle_active_report_controller.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BUNDLE_ACTIVE_REPORT_CONTROLLER_H +#define BUNDLE_ACTIVE_REPORT_CONTROLLER_H + +#include "bundle_active_report_handler.h" +#include "bundle_active_core.h" +#include "ffrt.h" + +namespace OHOS { +namespace DeviceUsageStats { +class BundleActiveReportController { +public: + static BundleActiveReportController& GetInstance(); + void Init(const std::shared_ptr& bundleActiveCore); + void DeInit(); + std::shared_ptr GetBundleReportHandler(); +private: + BundleActiveReportController() = default; + ~BundleActiveReportController() = default; + std::shared_ptr activeReportHandler_; + bool isInit_ = false; + ffrt::mutex mutex_; +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_REPORT_CONTROLLER_H + + \ No newline at end of file diff --git a/services/packageusage/include/bundle_active_report_handler.h b/services/packageusage/include/bundle_active_report_handler.h index 1388eca..0956833 100644 --- a/services/packageusage/include/bundle_active_report_handler.h +++ b/services/packageusage/include/bundle_active_report_handler.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -25,7 +25,7 @@ namespace OHOS { namespace DeviceUsageStats { -class BundleActiveReportHandler : public std::enable_shared_from_this { +class BundleActiveReportHandler { public: BundleActiveReportHandler() = default; ~BundleActiveReportHandler() = default; diff --git a/services/packageusage/src/bundle_active_report_controller.cpp b/services/packageusage/src/bundle_active_report_controller.cpp new file mode 100644 index 0000000..685fe9b --- /dev/null +++ b/services/packageusage/src/bundle_active_report_controller.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "bundle_active_report_controller.h" + +#include "bundle_active_log.h" +#include "bundle_active_user_history.h" +#include "bundle_active_group_handler.h" +#include "ibundle_active_service.h" +#include "bundle_active_group_controller.h" +#include "bundle_active_util.h" + +namespace OHOS { +namespace DeviceUsageStats { +BundleActiveReportController& BundleActiveReportController::GetInstance() +{ + static BundleActiveReportController instance; + return instance; +} + +void BundleActiveReportController::Init(const std::shared_ptr& bundleActiveCore) +{ + std::lock_guard lock(mutex_); + if (isInit_) { + return; + } + activeReportHandler_ = std::make_shared(); + if (activeReportHandler_ == nullptr) { + return; + } + activeReportHandler_->Init(bundleActiveCore); + isInit_ = true; +} + +void BundleActiveReportController::DeInit() +{ + if (!isInit_) { + return; + } + std::lock_guard lock(mutex_); + isInit_ = false; + activeReportHandler_->DeInit(); +} + +std::shared_ptr BundleActiveReportController::GetBundleReportHandler() +{ + std::lock_guard lock(mutex_); + if (!isInit_) { + return nullptr; + } + return activeReportHandler_; +} +} // namespace DeviceUsageStats +} // namespace OHOS + + \ No newline at end of file diff --git a/services/packageusage/src/bundle_active_report_handler.cpp b/services/packageusage/src/bundle_active_report_handler.cpp index c45c62f..e0ed8b0 100644 --- a/services/packageusage/src/bundle_active_report_handler.cpp +++ b/services/packageusage/src/bundle_active_report_handler.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,6 +17,7 @@ #include "bundle_active_report_handler.h" #include "bundle_active_event.h" #include "bundle_active_util.h" +#include "bundle_active_report_controller.h" namespace OHOS { namespace DeviceUsageStats { @@ -60,13 +61,20 @@ void BundleActiveReportHandler::SendEvent(const int32_t& eventId, BUNDLE_ACTIVE_LOGE("init failed"); return; } - auto reportHandler = shared_from_this(); int64_t ffrtDelayTime = BundleActiveUtil::GetFFRTDelayTime(delayTime); std::lock_guard lock(taskHandlerMutex_); if (taskHandlerMap_.find(eventId) == taskHandlerMap_.end()) { taskHandlerMap_[eventId] = std::queue(); } - ffrt::task_handle taskHandle = ffrtQueue_->submit_h([reportHandler, eventId, handlerobj]() { + ffrt::task_handle taskHandle = ffrtQueue_->submit_h([eventId, handlerobj]() { + auto reportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler(); + if (reportHandler == nullptr) { + return; + } + if (!reportHandler->isInited_) { + BUNDLE_ACTIVE_LOGE("init failed"); + return; + } reportHandler->ProcessEvent(eventId, handlerobj); std::lock_guard lock(reportHandler->taskHandlerMutex_); if (reportHandler->taskHandlerMap_.find(eventId) == reportHandler->taskHandlerMap_.end()) { diff --git a/test/fuzztest/appgroupcallbackstub_fuzzer/BUILD.gn b/test/fuzztest/appgroupcallbackstub_fuzzer/BUILD.gn index c923b47..fc39fe0 100644 --- a/test/fuzztest/appgroupcallbackstub_fuzzer/BUILD.gn +++ b/test/fuzztest/appgroupcallbackstub_fuzzer/BUILD.gn @@ -49,7 +49,7 @@ ohos_fuzztest("AppgroupcallbackstubFuzzTest") { "appgroupcallbackstub_fuzzer.cpp", ] - public_deps = [ "${usage_statistics_path}:usagestatservice_static" ] + public_deps = [ "${usage_statistics_path}:usagestatsinner_static" ] external_deps = [ "ability_runtime:app_manager", "ability_runtime:wantagent_innerkits", diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index d59cd22..05fcc7e 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -68,6 +68,13 @@ ohos_unittest("BundleActiveTotalTest") { defines += [ "DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE" ] external_deps += [ "power_manager:powermgr_client" ] } + if (os_account_part_enabled) { + external_deps += [ "os_account:os_account_innerkits" ] + } + if (bgtaskmgr_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + defines += [ "BGTASKMGR_ENABLE" ] + } branch_protector_ret = "pac_ret" sanitize = { @@ -95,6 +102,8 @@ ohos_unittest("DeviceUsageStatsTest") { ] external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", @@ -103,15 +112,24 @@ ohos_unittest("DeviceUsageStatsTest") { "hilog:libhilog", "ipc:ipc_single", "jsoncpp:jsoncpp", + "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr:samgr_proxy", "selinux_adapter:librestorecon", + "time_service:time_client", ] defines = [] if (device_usage_statistics_with_powermgr_power_manager_enable) { defines += [ "DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE" ] external_deps += [ "power_manager:powermgr_client" ] } + if (os_account_part_enabled) { + external_deps += [ "os_account:os_account_innerkits" ] + } + if (bgtaskmgr_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + defines += [ "BGTASKMGR_ENABLE" ] + } branch_protector_ret = "pac_ret" sanitize = { @@ -139,6 +157,8 @@ ohos_unittest("DeviceUsageStatsMultiTest") { ] external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", @@ -147,15 +167,24 @@ ohos_unittest("DeviceUsageStatsMultiTest") { "hilog:libhilog", "ipc:ipc_single", "jsoncpp:jsoncpp", + "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr:samgr_proxy", "selinux_adapter:librestorecon", + "time_service:time_client", ] defines = [] if (device_usage_statistics_with_powermgr_power_manager_enable) { defines += [ "DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE" ] external_deps += [ "power_manager:powermgr_client" ] } + if (os_account_part_enabled) { + external_deps += [ "os_account:os_account_innerkits" ] + } + if (bgtaskmgr_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + defines += [ "BGTASKMGR_ENABLE" ] + } branch_protector_ret = "pac_ret" sanitize = { @@ -204,6 +233,13 @@ ohos_unittest("DeviceUsageStatsServiceTest") { defines += [ "DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE" ] external_deps += [ "power_manager:powermgr_client" ] } + if (os_account_part_enabled) { + external_deps += [ "os_account:os_account_innerkits" ] + } + if (bgtaskmgr_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + defines += [ "BGTASKMGR_ENABLE" ] + } sanitize = { cfi = true @@ -257,6 +293,13 @@ ohos_unittest("DeviceUsageStatsMockTest") { defines += [ "DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE" ] external_deps += [ "power_manager:powermgr_client" ] } + if (os_account_part_enabled) { + external_deps += [ "os_account:os_account_innerkits" ] + } + if (bgtaskmgr_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + defines += [ "BGTASKMGR_ENABLE" ] + } branch_protector_ret = "pac_ret" sanitize = { @@ -301,6 +344,13 @@ ohos_unittest("DeviceUsagePackageUsageTest") { defines += [ "DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE" ] external_deps += [ "power_manager:powermgr_client" ] } + if (os_account_part_enabled) { + external_deps += [ "os_account:os_account_innerkits" ] + } + if (bgtaskmgr_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + defines += [ "BGTASKMGR_ENABLE" ] + } branch_protector_ret = "pac_ret" sanitize = { diff --git a/test/unittest/bundle_active_test_util.h b/test/unittest/bundle_active_test_util.h new file mode 100644 index 0000000..28d5f58 --- /dev/null +++ b/test/unittest/bundle_active_test_util.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 BUNDLE_ACTIVE_TEST_UTIL_H +#define BUNDLE_ACTIVE_TEST_UTIL_H + +#include +#include + +#include "bundle_active_core.h" +#include "bundle_active_report_controller.h" +#include "bundle_active_group_controller.h" + +namespace OHOS { +namespace DeviceUsageStats { +namespace BundleActiveTestUtil { +std::shared_ptr TestInit() +{ + std::shared_ptr bundleActiveCore = std::make_shared(); + bundleActiveCore->Init(); + bundleActiveCore->InitBundleGroupController(); + BundleActiveGroupController::GetInstance().Init(false); + return bundleActiveCore; +}; + +void TestDeInit() +{ + BundleActiveReportController::GetInstance().DeInit(); + BundleActiveGroupController::GetInstance().DeInit(); + auto activeGroupHandler = BundleActiveGroupController::GetInstance().activeGroupHandler_; + if (activeGroupHandler && activeGroupHandler->ffrtQueue_) { + auto handle = activeGroupHandler->ffrtQueue_->submit_h([]() {}); + activeGroupHandler->ffrtQueue_->wait(handle); + activeGroupHandler->ffrtQueue_.reset(); + } + auto activeReportHandler = BundleActiveReportController::GetInstance().activeReportHandler_; + if (activeReportHandler && activeReportHandler->ffrtQueue_) { + auto handle = activeReportHandler->ffrtQueue_->submit_h([]() {}); + activeReportHandler->ffrtQueue_->wait(handle); + activeReportHandler->ffrtQueue_.reset(); + } + int64_t sleepTimeEnd = 1; + std::this_thread::sleep_for(std::chrono::seconds(sleepTimeEnd)); +} +}; + + +} // namespace DeviceUsageStats +} +#endif // BUNDLE_ACTIVE_TEST_UTIL_H + \ No newline at end of file diff --git a/test/unittest/bundle_active_total_test.cpp b/test/unittest/bundle_active_total_test.cpp index 3f8c01e..c0aedde 100644 --- a/test/unittest/bundle_active_total_test.cpp +++ b/test/unittest/bundle_active_total_test.cpp @@ -32,6 +32,8 @@ #include "bundle_active_shutdown_callback_service.h" #include "bundle_active_binary_search.h" #include "bundle_active_debug_mode.h" +#include "bundle_active_report_controller.h" +#include "bundle_active_test_util.h" using namespace testing::ext; @@ -48,10 +50,12 @@ public: void BundleActiveTotalTest::SetUpTestCase(void) { + BundleActiveTestUtil::TestInit(); } void BundleActiveTotalTest::TearDownTestCase(void) { + BundleActiveTestUtil::TestDeInit(); } void BundleActiveTotalTest::SetUp(void) @@ -87,13 +91,8 @@ HWTEST_F(BundleActiveTotalTest, BundleActiveContinuousTaskObserverTest_001, Func { #ifdef BGTASKMGR_ENABLE #ifdef OS_ACCOUNT_PART_ENABLED - std::shared_ptr runner; - auto reportHandler = std::make_shared(runner); - auto reportHandler1 = std::make_shared(runner); + BundleActiveReportController::GetInstance().Init(); BundleActiveContinuousTaskObserver test; - test.Init(reportHandler); - test.Init(reportHandler1); - EXPECT_TRUE(test.reportHandler_ != nullptr); std::shared_ptr continuousTaskCallbackInfo; test.OnContinuousTaskStart(continuousTaskCallbackInfo); @@ -104,8 +103,7 @@ HWTEST_F(BundleActiveTotalTest, BundleActiveContinuousTaskObserverTest_001, Func test.GetBundleMgr(); test.bundleMgr_ = nullptr; - test.GetBundleMgr(); - SUCCEED(); + EXPECT_TRUE(test.GetBundleMgr()); #endif #endif } @@ -195,16 +193,16 @@ HWTEST_F(BundleActiveTotalTest, BundleActiveBundleMgrHelperTest_004, Function | */ HWTEST_F(BundleActiveTotalTest, BundleActiveAppStateObserverTest_001, Function | MediumTest | Level0) { + std::shared_ptr bundleActiveCore = std::make_shared(); + BundleActiveReportController::GetInstance().Init(bundleActiveCore); AbilityStateData abilityStateData; - auto reportHandler = std::make_shared(); + abilityStateData.abilityType = 1; BundleActiveAppStateObserver test; - test.Init(reportHandler); test.OnAbilityStateChanged(abilityStateData); - test.Init(reportHandler); abilityStateData.abilityState = static_cast(AppExecFwk::AbilityState::ABILITY_STATE_FOREGROUND); test.OnAbilityStateChanged(abilityStateData); - EXPECT_TRUE(test.reportHandler_ != nullptr); + EXPECT_TRUE(BundleActiveReportController::GetInstance().GetBundleReportHandler() != nullptr); abilityStateData.abilityState = static_cast(AppExecFwk::AbilityState::ABILITY_STATE_BACKGROUND); test.OnAbilityStateChanged(abilityStateData); diff --git a/test/unittest/device_usage_statistics_mock_test.cpp b/test/unittest/device_usage_statistics_mock_test.cpp index 5336bce..6f0f797 100644 --- a/test/unittest/device_usage_statistics_mock_test.cpp +++ b/test/unittest/device_usage_statistics_mock_test.cpp @@ -25,6 +25,7 @@ #include "iapp_group_callback.h" #include "bundle_active_constant.h" #include "bundle_active_usage_database.h" +#include "bundle_active_test_util.h" using namespace testing::ext; @@ -52,10 +53,12 @@ public: void DeviceUsageStatisticsMockTest::SetUpTestCase(void) { + BundleActiveTestUtil::TestInit(); } void DeviceUsageStatisticsMockTest::TearDownTestCase(void) { + BundleActiveTestUtil::TestDeInit(); } void DeviceUsageStatisticsMockTest::SetUp(void) @@ -338,7 +341,7 @@ HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_CheckTimeC HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_getUserHistory_001, Function | MediumTest | Level0) { - auto groupController = std::make_shared(false); + auto groupController = std::make_shared(); const int64_t timeStamp = g_largeNum; int32_t uid = 0; int32_t appIndex = 0; @@ -358,7 +361,7 @@ HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_getUserHis HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_calculationTimeOut_001, Function | MediumTest | Level0) { - auto groupController = std::make_shared(false); + auto groupController = std::make_shared(); std::shared_ptr history = nullptr; groupController->calculationTimeOut(history, g_largeNum); diff --git a/test/unittest/device_usage_statistics_multi_test.cpp b/test/unittest/device_usage_statistics_multi_test.cpp index 2bb99fa..a954c8b 100644 --- a/test/unittest/device_usage_statistics_multi_test.cpp +++ b/test/unittest/device_usage_statistics_multi_test.cpp @@ -35,6 +35,7 @@ #include "accesstoken_kit.h" #include "token_setproc.h" #include "nativetoken_kit.h" +#include "bundle_active_test_util.h" using namespace testing::ext; using namespace testing::mt; @@ -88,10 +89,12 @@ void DeviceUsageStatisticsMultiTest::SetUpTestCase(void) tokenId = GetAccessTokenId(&infoInstance); SetSelfTokenID(tokenId); AccessTokenKit::ReloadNativeTokenInfo(); + BundleActiveTestUtil::TestInit(); } void DeviceUsageStatisticsMultiTest::TearDownTestCase(void) { + BundleActiveTestUtil::TestDeInit(); } void DeviceUsageStatisticsMultiTest::SetUp(void) diff --git a/test/unittest/device_usage_statistics_service_test.cpp b/test/unittest/device_usage_statistics_service_test.cpp index 82b8c8e..c73d7a4 100644 --- a/test/unittest/device_usage_statistics_service_test.cpp +++ b/test/unittest/device_usage_statistics_service_test.cpp @@ -32,6 +32,8 @@ #include "accesstoken_kit.h" #include "token_setproc.h" #include "nativetoken_kit.h" +#include "bundle_active_report_controller.h" +#include "bundle_active_test_util.h" using namespace testing::ext; @@ -45,7 +47,6 @@ public: void SetUp(); void TearDown(); static std::shared_ptr bundleActiveCore_; - static void TestBundleActiveCoreDeInit(std::shared_ptr& bundleActiveCore); }; std::shared_ptr DeviceUsageStatisticsServiceTest::bundleActiveCore_ = nullptr; @@ -69,14 +70,13 @@ void DeviceUsageStatisticsServiceTest::SetUpTestCase(void) tokenId = GetAccessTokenId(&infoInstance); SetSelfTokenID(tokenId); AccessTokenKit::ReloadNativeTokenInfo(); - bundleActiveCore_ = std::make_shared(); - bundleActiveCore_->Init(); - bundleActiveCore_->InitBundleGroupController(); + bundleActiveCore_ = BundleActiveTestUtil::TestInit(); } void DeviceUsageStatisticsServiceTest::TearDownTestCase(void) { - TestBundleActiveCoreDeInit(bundleActiveCore_); + bundleActiveCore_->DeInit(); + BundleActiveTestUtil::TestDeInit(); int64_t sleepTime = 10; std::this_thread::sleep_for(std::chrono::seconds(sleepTime)); } @@ -91,18 +91,6 @@ void DeviceUsageStatisticsServiceTest::TearDown(void) std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime)); } -void DeviceUsageStatisticsServiceTest::TestBundleActiveCoreDeInit(std::shared_ptr& bundleActiveCore) -{ - int64_t sleepTime = 1; - std::this_thread::sleep_for(std::chrono::seconds(sleepTime)); - bundleActiveCore->DeInit(); - if (bundleActiveCore->bundleGroupHandler_ && bundleActiveCore->bundleGroupHandler_->ffrtQueue_) { - auto handle = bundleActiveCore->bundleGroupHandler_->ffrtQueue_->submit_h([]() {}); - bundleActiveCore->bundleGroupHandler_->ffrtQueue_->wait(handle); - bundleActiveCore->bundleGroupHandler_->ffrtQueue_.reset(); - } -} - class TestServiceAppGroupChangeCallback : public AppGroupCallbackStub { public: ErrCode OnAppGroupChanged(const AppGroupCallbackInfo &appGroupCallbackInfo) override; @@ -138,7 +126,7 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_GetS * @tc.type: FUNC * @tc.require: issuesI5SOZY */ - HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_GetNameAndIndexForUid_001, +HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_GetNameAndIndexForUid_001, Function | MediumTest | Level0) { auto bundleActiveService = std::make_shared(); @@ -205,7 +193,6 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_dump args.clear(); args = {to_utf16("-D")}; bundleActiveService->Dump(-1, args); - TestBundleActiveCoreDeInit(bundleActiveService->bundleActiveCore_); } /* @@ -257,7 +244,6 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_AppG wptr remote = nullptr; bundleActiveService->bundleActiveCore_->OnObserverDied(remote); bundleActiveService->bundleActiveCore_->OnObserverDiedInner(remote); - TestBundleActiveCoreDeInit(bundleActiveService->bundleActiveCore_); } /* @@ -291,17 +277,16 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_OnUs Function | MediumTest | Level0) { int userId = 100; - auto coreObject = bundleActiveCore_; - coreObject->RestoreToDatabase(userId); - auto userService = std::make_shared(userId, *(coreObject.get()), false); - coreObject->userStatServices_[userId] = userService; + bundleActiveCore_->RestoreToDatabase(userId); + auto userService = std::make_shared(userId, *(bundleActiveCore_.get()), false); + bundleActiveCore_->userStatServices_[userId] = userService; BundleActiveEvent event; - coreObject->ReportEventToAllUserId(event); - coreObject->currentUsedUser_ = userId; - coreObject->OnUserRemoved(userId); - coreObject->OnUserSwitched(userId); - EXPECT_NE(coreObject, nullptr); + bundleActiveCore_->ReportEventToAllUserId(event); + bundleActiveCore_->currentUsedUser_ = userId; + bundleActiveCore_->OnUserRemoved(userId); + bundleActiveCore_->OnUserSwitched(userId); + EXPECT_NE(bundleActiveCore_, nullptr); } /* @@ -313,19 +298,18 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_OnUs HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_RestoreAllData_001, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; int userId = 100; - auto userService = std::make_shared(userId, *(coreObject.get()), false); + auto userService = std::make_shared(userId, *(bundleActiveCore_.get()), false); int64_t timeStamp = 20000000000000; userService->Init(timeStamp); - coreObject->userStatServices_[userId] = userService; + bundleActiveCore_->userStatServices_[userId] = userService; userId = 101; - coreObject->userStatServices_[userId] = nullptr; - coreObject->RestoreAllData(); + bundleActiveCore_->userStatServices_[userId] = nullptr; + bundleActiveCore_->RestoreAllData(); BundleActiveEvent event; - coreObject->ReportEventToAllUserId(event); - EXPECT_NE(coreObject, nullptr); + bundleActiveCore_->ReportEventToAllUserId(event); + EXPECT_NE(bundleActiveCore_, nullptr); } /* @@ -337,20 +321,19 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Rest HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_ObtainSystemEventName_001, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; BundleActiveEvent event; event.eventId_ = BundleActiveEvent::SYSTEM_LOCK; - coreObject->ObtainSystemEventName(event); + bundleActiveCore_->ObtainSystemEventName(event); event.eventId_ = BundleActiveEvent::SYSTEM_UNLOCK; - coreObject->ObtainSystemEventName(event); + bundleActiveCore_->ObtainSystemEventName(event); event.eventId_ = BundleActiveEvent::SYSTEM_SLEEP; - coreObject->ObtainSystemEventName(event); + bundleActiveCore_->ObtainSystemEventName(event); event.eventId_ = BundleActiveEvent::SYSTEM_WAKEUP; - coreObject->ObtainSystemEventName(event); - EXPECT_NE(coreObject, nullptr); + bundleActiveCore_->ObtainSystemEventName(event); + EXPECT_NE(bundleActiveCore_, nullptr); } /* @@ -736,7 +719,6 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Repo event.eventId_ = 16; EXPECT_EQ(bundleActiveCore->ReportEvent(event, userId), ERR_OK); - TestBundleActiveCoreDeInit(bundleActiveCore); } /* @@ -748,8 +730,7 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Repo HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_InitBundleGroupController_001, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; - coreObject->InitBundleGroupController(); + bundleActiveCore_->InitBundleGroupController(); } /* @@ -761,20 +742,18 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Init HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_ReportEventToAllUserId_001, Function | MediumTest | Level0) { - auto coreObject = std::make_shared(); int userId = 100; - auto userService = std::make_shared(userId, *(coreObject.get()), false); - coreObject->userStatServices_[userId] = userService; + auto userService = std::make_shared(userId, *(bundleActiveCore_.get()), false); + bundleActiveCore_->userStatServices_[userId] = userService; userId = 101; - coreObject->userStatServices_[userId] = nullptr; + bundleActiveCore_->userStatServices_[userId] = nullptr; BundleActiveEvent event; - coreObject->ReportEventToAllUserId(event); + bundleActiveCore_->ReportEventToAllUserId(event); - coreObject->Init(); - coreObject->InitBundleGroupController(); - coreObject->ReportEventToAllUserId(event); - EXPECT_NE(coreObject, nullptr); - TestBundleActiveCoreDeInit(coreObject); + bundleActiveCore_->Init(); + bundleActiveCore_->InitBundleGroupController(); + bundleActiveCore_->ReportEventToAllUserId(event); + EXPECT_NE(bundleActiveCore_, nullptr); } /* @@ -799,7 +778,6 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Rest userId = 101; coreObject->RestoreToDatabase(userId); EXPECT_NE(coreObject, nullptr); - TestBundleActiveCoreDeInit(coreObject); } /* @@ -811,13 +789,12 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Rest HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_001, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; int userId = 100; - auto userService = std::make_shared(userId, *(coreObject.get()), false); + auto userService = std::make_shared(userId, *(bundleActiveCore_.get()), false); int64_t timeStamp = 20000000000000; userService->Init(timeStamp); - coreObject->userStatServices_[userId] = userService; - coreObject->OnUserRemoved(userId); + bundleActiveCore_->userStatServices_[userId] = userService; + bundleActiveCore_->OnUserRemoved(userId); SUCCEED(); } @@ -830,13 +807,13 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_001, HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_002, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; int userId = 100; - auto userService = std::make_shared(userId, *(coreObject.get()), false); + auto userService = std::make_shared(userId, *(bundleActiveCore_.get()), false); int64_t timeStamp = 20000000000000; userService->Init(timeStamp); - coreObject->userStatServices_[userId] = userService; - coreObject->bundleGroupController_->OnUserSwitched(userId, userId); + bundleActiveCore_->userStatServices_[userId] = userService; + BundleActiveGroupController::GetInstance().Init(false); + BundleActiveGroupController::GetInstance().OnUserSwitched(userId, userId); SUCCEED(); } @@ -849,13 +826,12 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_002, HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_003, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; int userId = 100; - auto userService = std::make_shared(userId, *(coreObject.get()), false); + auto userService = std::make_shared(userId, *(bundleActiveCore_.get()), false); int64_t timeStamp = 20000000000000; userService->Init(timeStamp); - coreObject->userStatServices_[userId] = userService; - EXPECT_EQ(coreObject->bundleGroupController_->GetNewGroup("test", userId, timeStamp, 0), -1); + bundleActiveCore_->userStatServices_[userId] = userService; + EXPECT_EQ(BundleActiveGroupController::GetInstance().GetNewGroup("test", userId, timeStamp, 0), -1); } /* @@ -867,19 +843,18 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_003, HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_004, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; int userId = 100; BundleActiveEvent event; int64_t timeStamp = 20000000000000; - coreObject->bundleGroupController_->ReportEvent(event, timeStamp, userId); + BundleActiveGroupController::GetInstance().ReportEvent(event, timeStamp, userId); SUCCEED(); - coreObject->bundleGroupController_->ReportEvent(event, timeStamp, 19); + BundleActiveGroupController::GetInstance().ReportEvent(event, timeStamp, 19); SUCCEED(); - coreObject->bundleGroupController_->ReportEvent(event, timeStamp, 7); + BundleActiveGroupController::GetInstance().ReportEvent(event, timeStamp, 7); SUCCEED(); - coreObject->bundleGroupController_->bundleGroupEnable_ = false; + BundleActiveGroupController::GetInstance().bundleGroupEnable_ = false; SUCCEED(); - coreObject->bundleGroupController_->ReportEvent(event, timeStamp, userId); + BundleActiveGroupController::GetInstance().ReportEvent(event, timeStamp, userId); SUCCEED(); } @@ -892,10 +867,9 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_004, HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_005, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; int userId = 100; int64_t timeStamp = 20000000000000; - coreObject->bundleGroupController_->CheckAndUpdateGroup("test", userId, 0, timeStamp); + BundleActiveGroupController::GetInstance().CheckAndUpdateGroup("test", userId, 0, timeStamp); SUCCEED(); } @@ -908,10 +882,9 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_005, HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_006, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; int userId = 100; int64_t time = 20000000000000; - EXPECT_EQ(coreObject->bundleGroupController_->SetAppGroup("test", userId, 0, 0, time, true), + EXPECT_EQ(BundleActiveGroupController::GetInstance().SetAppGroup("test", userId, 0, 0, time, true), ERR_NO_APP_GROUP_INFO_IN_DATABASE); } @@ -924,9 +897,8 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_006, HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_007, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; int userId = 100; - EXPECT_EQ(coreObject->bundleGroupController_->IsBundleIdle("test", userId), -1); + EXPECT_EQ(BundleActiveGroupController::GetInstance().IsBundleIdle("test", userId), -1); } /* @@ -938,14 +910,11 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_007, HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_009, Function | MediumTest | Level0) { - auto coreObject = std::make_shared(); - coreObject->bundleGroupController_ = std::make_shared(true); - coreObject->InitBundleGroupController(); + bundleActiveCore_->InitBundleGroupController(); int userId = 100; - EXPECT_EQ(coreObject->bundleGroupController_->IsBundleInstalled("test", userId), false); - coreObject->bundleGroupController_->sptrBundleMgr_ = nullptr; - EXPECT_EQ(coreObject->bundleGroupController_->IsBundleInstalled("test", userId), false); - TestBundleActiveCoreDeInit(coreObject); + EXPECT_EQ(BundleActiveGroupController::GetInstance().IsBundleInstalled("test", userId), false); + BundleActiveGroupController::GetInstance().sptrBundleMgr_ = nullptr; + EXPECT_EQ(BundleActiveGroupController::GetInstance().IsBundleInstalled("test", userId), false); } /* @@ -957,10 +926,9 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_009, HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_010, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; int userId = 100; int64_t timeStamp = 20000000000000; - coreObject->bundleGroupController_->ShutDown(timeStamp, userId); + BundleActiveGroupController::GetInstance().ShutDown(timeStamp, userId); SUCCEED(); } @@ -975,7 +943,7 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_011, { bool isScreenOn = true; int64_t timeStamp = 0; - bundleActiveCore_->bundleGroupController_->OnScreenChanged(isScreenOn, timeStamp); + BundleActiveGroupController::GetInstance().OnScreenChanged(isScreenOn, timeStamp); SUCCEED(); } @@ -988,8 +956,8 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_011, HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_012, Function | MediumTest | Level0) { - bundleActiveCore_->bundleGroupController_->ShutDown(1, 10); - EXPECT_NE(bundleActiveCore_->bundleGroupController_->bundleUserHistory_, nullptr); + BundleActiveGroupController::GetInstance().ShutDown(1, 10); + EXPECT_NE(BundleActiveGroupController::GetInstance().bundleUserHistory_, nullptr); } /* @@ -1001,8 +969,8 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_011, HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_013, Function | MediumTest | Level0) { - bundleActiveCore_->bundleGroupController_->OnUserRemoved(10); - EXPECT_NE(bundleActiveCore_->bundleGroupController_->bundleUserHistory_, nullptr); + BundleActiveGroupController::GetInstance().OnUserRemoved(10); + EXPECT_NE(BundleActiveGroupController::GetInstance().bundleUserHistory_, nullptr); } /* @@ -1014,8 +982,8 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_011, HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveGroupControllerTest_014, Function | MediumTest | Level0) { - bundleActiveCore_->bundleGroupController_->OnUserSwitched(1, 10); - EXPECT_NE(bundleActiveCore_->bundleGroupController_->bundleUserHistory_, nullptr); + BundleActiveGroupController::GetInstance().OnUserSwitched(1, 10); + EXPECT_NE(BundleActiveGroupController::GetInstance().bundleUserHistory_, nullptr); } /* @@ -1119,9 +1087,8 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, BundleActiveUserHistoryTest_005, HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_ShutDown_001, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; - coreObject->ShutDown(); - EXPECT_NE(coreObject, nullptr); + bundleActiveCore_->ShutDown(); + EXPECT_NE(bundleActiveCore_, nullptr); } /* @@ -1134,15 +1101,14 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Chec Function | MediumTest | Level0) { int userId = 100; - auto coreObject = bundleActiveCore_; - coreObject->OnUserRemoved(100); - auto userService = std::make_shared(userId, *(coreObject.get()), false); + bundleActiveCore_->OnUserRemoved(100); + auto userService = std::make_shared(userId, *(bundleActiveCore_.get()), false); int64_t timeStamp = 20000000000000; userService->Init(timeStamp); - coreObject->userStatServices_[userId] = userService; - coreObject->CheckTimeChangeAndGetWallTime(userId); - coreObject->OnUserSwitched(userId); - EXPECT_NE(coreObject, nullptr); + bundleActiveCore_->userStatServices_[userId] = userService; + bundleActiveCore_->CheckTimeChangeAndGetWallTime(userId); + bundleActiveCore_->OnUserSwitched(userId); + EXPECT_NE(bundleActiveCore_, nullptr); } /* @@ -1154,15 +1120,14 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Chec HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_QueryAppGroup_001, Function | MediumTest | Level0) { - auto groupController = bundleActiveCore_->bundleGroupController_; int32_t appGroup = 10; std::string bundleName = ""; int32_t userId = 100; - EXPECT_NE(groupController->QueryAppGroup(appGroup, bundleName, userId), ERR_OK); + EXPECT_NE(BundleActiveGroupController::GetInstance().QueryAppGroup(appGroup, bundleName, userId), ERR_OK); - groupController->sptrBundleMgr_ = nullptr; + BundleActiveGroupController::GetInstance().sptrBundleMgr_ = nullptr; bundleName = "defaultBundleName"; - EXPECT_NE(groupController->QueryAppGroup(appGroup, bundleName, userId), ERR_OK); + EXPECT_NE(BundleActiveGroupController::GetInstance().QueryAppGroup(appGroup, bundleName, userId), ERR_OK); } /* @@ -1174,24 +1139,22 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Quer HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_ControllerReportEvent_001, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; - int64_t bootBasedTimeStamp = 20000000000000; BundleActiveEvent event; int32_t userId = 100; - coreObject->bundleGroupController_->bundleGroupEnable_ = false; - coreObject->bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId); + BundleActiveGroupController::GetInstance().bundleGroupEnable_ = false; + BundleActiveGroupController::GetInstance().ReportEvent(event, bootBasedTimeStamp, userId); - coreObject->bundleGroupController_->bundleGroupEnable_ = true; + BundleActiveGroupController::GetInstance().bundleGroupEnable_ = true; event.bundleName_ = "com.ohos.camera"; - coreObject->bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId); + BundleActiveGroupController::GetInstance().ReportEvent(event, bootBasedTimeStamp, userId); event.eventId_ = BundleActiveEvent::NOTIFICATION_SEEN; - coreObject->bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId); + BundleActiveGroupController::GetInstance().ReportEvent(event, bootBasedTimeStamp, userId); event.eventId_ = BundleActiveEvent::SYSTEM_INTERACTIVE; - coreObject->bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId); - EXPECT_NE(coreObject, nullptr); + BundleActiveGroupController::GetInstance().ReportEvent(event, bootBasedTimeStamp, userId); + EXPECT_NE(bundleActiveCore_, nullptr); } /* @@ -1203,8 +1166,6 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Cont HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_CheckAndUpdateGroup_001, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; - std::string bundleName = "com.ohos.camera"; int32_t userId = 100; int64_t bootBasedTimeStamp = 20000000000000; @@ -1213,16 +1174,18 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Chec bool isFlush = false; int32_t appGroup = 0; - coreObject->bundleGroupController_->QueryAppGroup(appGroup, bundleName, userId); + BundleActiveGroupController::GetInstance().QueryAppGroup(appGroup, bundleName, userId); - coreObject->bundleGroupController_->SetAppGroup(bundleName, userId, newGroup, reason, bootBasedTimeStamp, isFlush); - coreObject->bundleGroupController_->CheckAndUpdateGroup(bundleName, 0, userId, bootBasedTimeStamp); + BundleActiveGroupController::GetInstance().SetAppGroup(bundleName, userId, newGroup, reason, + bootBasedTimeStamp, isFlush); + BundleActiveGroupController::GetInstance().CheckAndUpdateGroup(bundleName, 0, userId, bootBasedTimeStamp); newGroup = 20; reason = GROUP_CONTROL_REASON_CALCULATED; - coreObject->bundleGroupController_->SetAppGroup(bundleName, userId, newGroup, reason, bootBasedTimeStamp, isFlush); - coreObject->bundleGroupController_->CheckAndUpdateGroup(bundleName, 0, userId, bootBasedTimeStamp); - EXPECT_NE(coreObject, nullptr); + BundleActiveGroupController::GetInstance().SetAppGroup(bundleName, userId, newGroup, reason, + bootBasedTimeStamp, isFlush); + BundleActiveGroupController::GetInstance().CheckAndUpdateGroup(bundleName, 0, userId, bootBasedTimeStamp); + EXPECT_NE(bundleActiveCore_, nullptr); } /* @@ -1234,11 +1197,9 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Chec HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_PreservePowerStateInfo_001, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; - int32_t eventId = BundleActiveEvent::ABILITY_FOREGROUND; - coreObject->PreservePowerStateInfo(eventId); - EXPECT_NE(coreObject, nullptr); + bundleActiveCore_->PreservePowerStateInfo(eventId); + EXPECT_NE(bundleActiveCore_, nullptr); } /* @@ -1428,8 +1389,10 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Repo { #ifdef BGTASKMGR_ENABLE auto bgtaskObserver = std::make_shared(); - auto continuousTaskCallbackInfo = std::shared_ptr(); + auto continuousTaskCallbackInfo = std::make_shared(); continuousTaskCallbackInfo->creatorUid_ = 20000000; + bgtaskObserver->OnContinuousTaskStart(continuousTaskCallbackInfo); + bgtaskObserver->OnContinuousTaskStop(continuousTaskCallbackInfo); bool isStart = false; bgtaskObserver->ReportContinuousTaskEvent(continuousTaskCallbackInfo, isStart); @@ -1489,9 +1452,8 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Upda HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_DeleteUninstalledBundleStats_001, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; int userId = 100; - auto userService = std::make_shared(userId, *(coreObject.get()), false); + auto userService = std::make_shared(userId, *(bundleActiveCore_.get()), false); int appIndex = 1; std::vector> curStats; std::shared_ptr stats = std::make_shared(); @@ -1516,9 +1478,8 @@ HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_Dele HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_DeleteUninstalledBundleStats_002, Function | MediumTest | Level0) { - auto coreObject = bundleActiveCore_; int userId = 100; - auto userService = std::make_shared(userId, *(coreObject.get()), false); + auto userService = std::make_shared(userId, *(bundleActiveCore_.get()), false); int appIndex = 1; std::vector> curStats; std::shared_ptr stats = std::make_shared(); diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 65a140a..580c4e5 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -33,6 +33,7 @@ #include "accesstoken_kit.h" #include "token_setproc.h" #include "nativetoken_kit.h" +#include "bundle_active_test_util.h" using namespace testing::ext; @@ -83,10 +84,12 @@ void DeviceUsageStatisticsTest::SetUpTestCase(void) tokenId = GetAccessTokenId(&infoInstance); SetSelfTokenID(tokenId); AccessTokenKit::ReloadNativeTokenInfo(); + BundleActiveTestUtil::TestInit(); } void DeviceUsageStatisticsTest::TearDownTestCase(void) { + BundleActiveTestUtil::TestDeInit(); } void DeviceUsageStatisticsTest::SetUp(void) diff --git a/test/unittest/package_usage_test.cpp b/test/unittest/package_usage_test.cpp index 8dd2783..345e6fd 100644 --- a/test/unittest/package_usage_test.cpp +++ b/test/unittest/package_usage_test.cpp @@ -32,6 +32,7 @@ #include "bundle_active_log.h" #include "bundle_active_group_controller.h" #include "bundle_active_event_list.h" +#include "bundle_active_test_util.h" using namespace testing::ext; @@ -50,14 +51,12 @@ std::shared_ptr PackageUsageTest::bundleActiveCore_ = nullptr; void PackageUsageTest::SetUpTestCase(void) { - bundleActiveCore_ = std::make_shared(); - bundleActiveCore_->Init(); - bundleActiveCore_->InitBundleGroupController(); + bundleActiveCore_ = BundleActiveTestUtil::TestInit(); } void PackageUsageTest::TearDownTestCase(void) { - bundleActiveCore_->bundleGroupHandler_->ffrtQueue_.reset(); + BundleActiveTestUtil::TestDeInit(); int64_t sleepTime = 3; std::this_thread::sleep_for(std::chrono::seconds(sleepTime)); } @@ -285,8 +284,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_BundleActiveEventStats_001, Function HWTEST_F(PackageUsageTest, PackageUsageTest_ReportForShutdown_001, Function | MediumTest | Level0) { int32_t userId = 100; - auto bundleActiveCore = bundleActiveCore_; - auto bundleUserService = std::make_shared(userId, *(bundleActiveCore.get()), false); + auto bundleUserService = std::make_shared(userId, *(bundleActiveCore_.get()), false); BundleActiveEvent event; event.eventId_ = BundleActiveEvent::ABILITY_FOREGROUND; bundleUserService->currentStats_[0] = std::make_shared(); @@ -309,8 +307,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_ReportForShutdown_001, Function | Me HWTEST_F(PackageUsageTest, PackageUsageTest_ReportFormEvent_001, Function | MediumTest | Level0) { int32_t userId = 100; - auto bundleActiveCore = bundleActiveCore_; - auto bundleUserService = std::make_shared(userId, *(bundleActiveCore.get()), true); + auto bundleUserService = std::make_shared(userId, *(bundleActiveCore_.get()), true); BundleActiveEvent event; event.bundleName_ = "defaultBundleName"; event.moduleName_ = "defaultModuleName"; @@ -331,8 +328,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_ReportFormEvent_001, Function | Medi HWTEST_F(PackageUsageTest, PackageUsageTest_PrintInMemFormStats_001, Function | MediumTest | Level0) { int32_t userId = 100; - auto bundleActiveCore = bundleActiveCore_; - auto bundleUserService = std::make_shared(userId, *(bundleActiveCore.get()), true); + auto bundleUserService = std::make_shared(userId, *(bundleActiveCore_.get()), true); BundleActiveEvent event; event.bundleName_ = "defaultBundleName"; event.moduleName_ = "defaultModuleName"; @@ -352,8 +348,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_PrintInMemFormStats_001, Function | HWTEST_F(PackageUsageTest, PackageUsageTest_QueryDeviceEventStats_001, Function | MediumTest | Level0) { int32_t userId = 100; - auto bundleActiveCore = bundleActiveCore_; - auto bundleUserService = std::make_shared(userId, *(bundleActiveCore.get()), true); + auto bundleUserService = std::make_shared(userId, *(bundleActiveCore_.get()), true); int64_t timeStamp = 20000000000000; bundleUserService->Init(timeStamp); @@ -383,8 +378,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_QueryDeviceEventStats_001, Function HWTEST_F(PackageUsageTest, PackageUsageTest_QueryNotificationEventStats_001, Function | MediumTest | Level0) { int32_t userId = 100; - auto bundleActiveCore = bundleActiveCore_; - auto bundleUserService = std::make_shared(userId, *(bundleActiveCore.get()), true); + auto bundleUserService = std::make_shared(userId, *(bundleActiveCore_.get()), true); int64_t timeStamp = 20000000000000; bundleUserService->Init(timeStamp); @@ -419,8 +413,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_QueryNotificationEventStats_001, Fun HWTEST_F(PackageUsageTest, PackageUsageTest_QueryBundleEvents_001, Function | MediumTest | Level0) { int32_t userId = 100; - auto bundleActiveCore = bundleActiveCore_; - auto bundleUserService = std::make_shared(userId, *(bundleActiveCore.get()), true); + auto bundleUserService = std::make_shared(userId, *(bundleActiveCore_.get()), true); int64_t timeStamp = 20000000000000; bundleUserService->Init(timeStamp); @@ -457,8 +450,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_QueryBundleEvents_001, Function | Me HWTEST_F(PackageUsageTest, PackageUsageTest_PrintInMemPackageStats_001, Function | MediumTest | Level0) { int32_t userId = 100; - auto bundleActiveCore = bundleActiveCore_; - auto bundleUserService = std::make_shared(userId, *(bundleActiveCore.get()), true); + auto bundleUserService = std::make_shared(userId, *(bundleActiveCore_.get()), true); int64_t timeStamp = 20000000000000; bundleUserService->Init(timeStamp); @@ -478,8 +470,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_PrintInMemPackageStats_001, Function HWTEST_F(PackageUsageTest, PackageUsageTest_QueryBundleStatsInfos_001, Function | MediumTest | Level0) { int32_t userId = 100; - auto bundleActiveCore = bundleActiveCore_; - auto bundleUserService = std::make_shared(userId, *(bundleActiveCore.get()), true); + auto bundleUserService = std::make_shared(userId, *(bundleActiveCore_.get()), true); int64_t timeStamp = 20000000000000; bundleUserService->Init(timeStamp); @@ -523,8 +514,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_QueryBundleStatsInfos_001, Function HWTEST_F(PackageUsageTest, PackageUsageTest_QueryBundleStatsInfos_002, Function | MediumTest | Level0) { int32_t userId = 100; - auto bundleActiveCore = bundleActiveCore_; - auto bundleUserService = std::make_shared(userId, *(bundleActiveCore.get()), true); + auto bundleUserService = std::make_shared(userId, *(bundleActiveCore_.get()), true); int64_t timeStamp = 20000000000000; bundleUserService->Init(timeStamp); int64_t beginTime = 0; @@ -577,8 +567,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_QueryBundleStatsInfos_002, Function HWTEST_F(PackageUsageTest, PackageUsageTest_RestoreStats_001, Function | MediumTest | Level0) { int32_t userId = 100; - auto bundleActiveCore = bundleActiveCore_; - auto bundleUserService = std::make_shared(userId, *(bundleActiveCore.get()), true); + auto bundleUserService = std::make_shared(userId, *(bundleActiveCore_.get()), true); int64_t timeStamp = 20000000000000; bundleUserService->Init(timeStamp); @@ -607,8 +596,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_RestoreStats_001, Function | MediumT HWTEST_F(PackageUsageTest, PackageUsageTest_LoadActiveStats_001, Function | MediumTest | Level0) { int32_t userId = 100; - auto bundleActiveCore = bundleActiveCore_; - auto bundleUserService = std::make_shared(userId, *(bundleActiveCore.get()), true); + auto bundleUserService = std::make_shared(userId, *(bundleActiveCore_.get()), true); int64_t timeStamp = 20000000000000; bundleUserService->Init(timeStamp); @@ -671,8 +659,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_combine_001, Function | MediumTest | HWTEST_F(PackageUsageTest, PackageUsageTest_ReportEvent_001, Function | MediumTest | Level0) { int32_t userId = 100; - auto bundleActiveCore = bundleActiveCore_; - auto bundleUserService = std::make_shared(userId, *(bundleActiveCore.get()), true); + auto bundleUserService = std::make_shared(userId, *(bundleActiveCore_.get()), true); int64_t timeStamp = 20000000000; bundleUserService->Init(timeStamp); @@ -708,8 +695,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_ReportEvent_001, Function | MediumTe HWTEST_F(PackageUsageTest, PackageUsageTest_RenewStatsInMemory_001, Function | MediumTest | Level0) { int32_t userId = 100; - auto bundleActiveCore = bundleActiveCore_; - auto bundleUserService = std::make_shared(userId, *(bundleActiveCore.get()), true); + auto bundleUserService = std::make_shared(userId, *(bundleActiveCore_.get()), true); int64_t timeStamp = 20000000000; bundleUserService->Init(timeStamp); @@ -737,7 +723,7 @@ HWTEST_F(PackageUsageTest, PackageUsageTest_RenewStatsInMemory_001, Function | M */ HWTEST_F(PackageUsageTest, BundleActiveGroupController_001, Function | MediumTest | Level0) { - auto groupController = std::make_shared(false); + BundleActiveGroupController::GetInstance().Init(false); auto userHistory = std::make_shared>>(); int32_t uid = 0; int32_t appIndex = 1; @@ -747,11 +733,11 @@ HWTEST_F(PackageUsageTest, BundleActiveGroupController_001, Function | MediumTes userHistory->emplace(bundleName + std::to_string(uid), std::make_shared()); uid = 200; userHistory->emplace(bundleName + std::to_string(uid), std::make_shared()); - groupController->DeleteUsageGroupCache(userHistory, bundleName, uid, appIndex); + BundleActiveGroupController::GetInstance().DeleteUsageGroupCache(userHistory, bundleName, uid, appIndex); auto it = userHistory->find(bundleName + std::to_string(uid)); EXPECT_EQ(it, userHistory->end()); appIndex = 0; - groupController->DeleteUsageGroupCache(userHistory, bundleName, uid, appIndex); + BundleActiveGroupController::GetInstance().DeleteUsageGroupCache(userHistory, bundleName, uid, appIndex); uid = 0; it = userHistory->find(bundleName + std::to_string(uid)); EXPECT_EQ(it, userHistory->end()); @@ -765,14 +751,13 @@ HWTEST_F(PackageUsageTest, BundleActiveGroupController_001, Function | MediumTes */ HWTEST_F(PackageUsageTest, BundleActiveGroupController_002, Function | MediumTest | Level0) { - auto groupController = std::make_shared(false); - auto coreObject = bundleActiveCore_; + BundleActiveGroupController::GetInstance().Init(false); int userId = 100; BundleActiveEvent event; event.eventId_ = BundleActiveEvent::SYSTEM_INTERACTIVE; int64_t timeStamp = 20000000000000; - coreObject->bundleGroupController_->ReportEvent(event, timeStamp, userId); - EXPECT_TRUE(coreObject->bundleGroupController_ != nullptr); + BundleActiveGroupController::GetInstance().ReportEvent(event, timeStamp, userId); + EXPECT_TRUE(BundleActiveGroupController::GetInstance().GetBundleGroupHandler() != nullptr); } /* @@ -928,7 +913,7 @@ HWTEST_F(PackageUsageTest, BundleActiveGroupHandler_002, Function | MediumTest | BundleActiveGroupHandlerObject tmpObject; auto handlerObject = std::make_shared(tmpObject); auto bundleActiveGroupHandler = std::make_shared(true); - bundleActiveGroupHandler->Init(bundleActiveCore_->bundleGroupController_); + bundleActiveGroupHandler->Init(); bundleActiveGroupHandler->SendEvent(0, handlerObject); bundleActiveGroupHandler->SendEvent(0, handlerObject, 10); EXPECT_NE(bundleActiveGroupHandler->taskHandlerMap_.size(), 0); @@ -951,7 +936,7 @@ HWTEST_F(PackageUsageTest, BundleActiveGroupHandler_003, Function | MediumTest | tmpObject.userId_ = 100; auto handlerObject = std::make_shared(tmpObject); auto bundleActiveGroupHandler = std::make_shared(true); - bundleActiveGroupHandler->Init(bundleActiveCore_->bundleGroupController_); + bundleActiveGroupHandler->Init(); bundleActiveGroupHandler->SendCheckBundleMsg(0, handlerObject); bundleActiveGroupHandler->SendCheckBundleMsg(0, handlerObject, 10); auto msgKey = bundleActiveGroupHandler->GetMsgKey(0, handlerObject, 10); @@ -1000,7 +985,7 @@ HWTEST_F(PackageUsageTest, BundleActiveGroupHandler_005, Function | MediumTest | bundleActiveGroupHandler->PostSyncTask([]() { SUCCEED(); }); - bundleActiveGroupHandler->Init(bundleActiveCore_->bundleGroupController_); + bundleActiveGroupHandler->Init(); EXPECT_TRUE(bundleActiveGroupHandler->isInited_); bundleActiveGroupHandler->PostTask([]() { SUCCEED(); @@ -1020,7 +1005,7 @@ HWTEST_F(PackageUsageTest, BundleActiveGroupHandler_006, Function | MediumTest | { auto bundleActiveGroupHandler = std::make_shared(true); - bundleActiveGroupHandler->Init(bundleActiveCore_->bundleGroupController_); + bundleActiveGroupHandler->Init(); int32_t eventId = 0; std::shared_ptr tmpObject = nullptr; bundleActiveGroupHandler->SendCheckBundleMsg(eventId, tmpObject, 0); @@ -1036,7 +1021,7 @@ HWTEST_F(PackageUsageTest, BundleActiveGroupHandler_006, Function | MediumTest | HWTEST_F(PackageUsageTest, BundleActiveGroupHandler_007, Function | MediumTest | Level0) { auto bundleActiveGroupHandler = std::make_shared(true); - bundleActiveGroupHandler->Init(nullptr); + bundleActiveGroupHandler->DeInit(); EXPECT_FALSE(bundleActiveGroupHandler->isInited_); } @@ -1063,10 +1048,11 @@ HWTEST_F(PackageUsageTest, BundleActiveGroupHandler_008, Function | MediumTest | HWTEST_F(PackageUsageTest, BundleActiveGroupHandler_009, Function | MediumTest | Level0) { auto bundleActiveGroupHandler = std::make_shared(true); + bundleActiveGroupHandler->Init(); int32_t eventId = 0; std::shared_ptr tmpObject = nullptr; bundleActiveGroupHandler->ProcessEvent(eventId, tmpObject); - EXPECT_TRUE(bundleActiveGroupHandler->bundleActiveGroupController_ == nullptr); + EXPECT_TRUE(bundleActiveGroupHandler->isInited_); } /* @@ -1078,7 +1064,7 @@ HWTEST_F(PackageUsageTest, BundleActiveGroupHandler_009, Function | MediumTest | HWTEST_F(PackageUsageTest, BundleActiveGroupHandler_010, Function | MediumTest | Level0) { auto bundleActiveGroupHandler = std::make_shared(true); - bundleActiveGroupHandler->Init(bundleActiveCore_->bundleGroupController_); + bundleActiveGroupHandler->Init(); int32_t eventId = 2; std::shared_ptr handlerObject = nullptr; bundleActiveGroupHandler->ProcessEvent(eventId, handlerObject); -- Gitee