diff --git a/BUILD.gn b/BUILD.gn index cf37d4bd1a33e1a6aee7b57d512f276d010cdd1d..6fb466c0e046217418bbca7257ae0112ac82b90f 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -34,7 +34,6 @@ ohos_shared_library("usagestatsinner") { ] external_deps = [ - "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", @@ -74,7 +73,6 @@ ohos_shared_library("bundlestate") { ] external_deps = [ - "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "napi:ace_napi", @@ -93,6 +91,7 @@ ohos_shared_library("usagestatservice") { "services/common/src/bundle_active_binary_search.cpp", "services/common/src/bundle_active_continuous_task_observer.cpp", "services/common/src/bundle_active_core.cpp", + "services/common/src/bundle_active_debug_mode.cpp", "services/common/src/bundle_active_log.cpp", "services/common/src/bundle_active_open_callback.cpp", "services/common/src/bundle_active_service.cpp", @@ -131,7 +130,6 @@ ohos_shared_library("usagestatservice") { "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", - "dmsfwk_standard:zuri", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", @@ -141,6 +139,7 @@ ohos_shared_library("usagestatservice") { "power_manager_native:powermgr_client", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", + "startup_l2:syspara", "time_native:time_service", "utils_base:utils", ] diff --git a/LICENSE b/LICENSE index 66a27ec5ff940d3a9652d2948746ebac4c9d0188..e454a52586f29b8ce8a6799163eac1f875e9ac01 100644 --- a/LICENSE +++ b/LICENSE @@ -1,3 +1,4 @@ + Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ diff --git a/OAT.xml b/OAT.xml index b11daf5274a1b8efb7d7851c97861d0d8bf5d059..b0ba076091130892ff11703bf30ac5cfd7b80de2 100644 --- a/OAT.xml +++ b/OAT.xml @@ -1,5 +1,5 @@ - device_usage_stats_service diff --git a/services/common/include/bundle_active_app_state_observer.h b/services/common/include/bundle_active_app_state_observer.h index afca43fb7887ce6b9e9682af4b619f63eb03c392..97131a78b589ad77b622d2675c18dafa7c21e6a9 100644 --- a/services/common/include/bundle_active_app_state_observer.h +++ b/services/common/include/bundle_active_app_state_observer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 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 @@ -32,12 +32,7 @@ using OHOS::AppExecFwk::ProcessData; class BundleActiveAppStateObserver : public ApplicationStateObserverStub { public: - void OnForegroundApplicationChanged(const AppStateData &appStateData) override; void OnAbilityStateChanged(const AbilityStateData &abilityStateData) override; - void OnExtensionStateChanged(const AbilityStateData &abilityStateData) override; - void OnProcessCreated(const ProcessData &processData) override; - void OnProcessDied(const ProcessData &processData) override; - void OnApplicationStateChanged(const AppStateData &appStateData) override; void Init(const std::shared_ptr& reportHandler); private: inline bool ValidateAppStateData(const AppStateData &appStateData) const @@ -61,6 +56,7 @@ private: } std::shared_ptr reportHandler_; }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_APP_STATE_OBSERVER_H + diff --git a/services/common/include/bundle_active_binary_search.h b/services/common/include/bundle_active_binary_search.h index 62bcfdc16007be2a7ac251c74db0a54203e0c603..c75e5693ec0274475a714215adf5d7a3238b5502 100644 --- a/services/common/include/bundle_active_binary_search.h +++ b/services/common/include/bundle_active_binary_search.h @@ -27,6 +27,7 @@ public: int32_t BinarySearch(const std::vector &tableNameArray, int64_t targetValue); DECLARE_DELAYED_SINGLETON(BundleActiveBinarySearch); }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_BINARY_SEARCH_H + diff --git a/services/common/include/bundle_active_common_event_subscriber.h b/services/common/include/bundle_active_common_event_subscriber.h index ffbf6e9224f00ad0a7119caad061bbd3a1723015..5ffc4030da50b5a03a1a85fb6c7a1a3c73641131 100644 --- a/services/common/include/bundle_active_common_event_subscriber.h +++ b/services/common/include/bundle_active_common_event_subscriber.h @@ -43,7 +43,7 @@ public: const std::weak_ptr bundleActiveReportHandler) : CommonEventSubscriber(subscriberInfo), activeGroupController_(activeGroupController), - bundleActiveReportHandler_(bundleActiveReportHandler) {}; + bundleActiveReportHandler_(bundleActiveReportHandler) {} ~BundleActiveCommonEventSubscriber() = default; void OnReceiveEvent(const CommonEventData &data) override; @@ -52,6 +52,7 @@ private: std::weak_ptr activeGroupController_; std::weak_ptr bundleActiveReportHandler_; }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_COMMON_EVENT_SUBSCRIBER_H + diff --git a/services/common/include/bundle_active_constant.h b/services/common/include/bundle_active_constant.h index 2e3bd8c1bfed63c7b52c341cefd83c765f409b31..77fd19118f20090345ee60ce64a615709c95ef28 100644 --- a/services/common/include/bundle_active_constant.h +++ b/services/common/include/bundle_active_constant.h @@ -59,7 +59,17 @@ const int BOOT_BASED_DURATION_COLUMN_INDEX = 0; const int SCREEN_ON_DURATION_COLUMN_INDEX = 1; const int DURATION_FLAG_COLUMN_INDEX = 2; const int TWO_SECONDS = 2 * 1000; -const int64_t SIX_DAY_IN_MILLIS_MAX = 1 * 6 * 10 * 60 * 1000; +const int64_t THIRTY_MINUTE = 30 * 60 * 1000; +const int64_t SIX_DAY_IN_MILLIS_MAX_DEBUG = (int64_t)6 * 1 * 10 * 60 * 1000; +const int64_t SIX_DAY_IN_MILLIS_MAX = (int64_t)6 * 24 * 60 * 60 * 1000; +const int64_t ONE_DAY_TIME_DEBUG = (int64_t)1 * 10 * 60 * 1000; +const int64_t ONE_DAY_TIME = (int64_t)1 * 24 * 60 * 60 * 1000; +const int64_t ONE_WEEK_TIME_DEBUG = (int64_t)1 * 20 * 60 * 1000; +const int64_t ONE_WEEK_TIME = (int64_t)7 * 24 * 60 * 60 * 1000; +const int64_t ONE_MONTH_TIME_DEBUG = (int64_t)1 * 30 * 60 * 1000; +const int64_t ONE_MONTH_TIME = (int64_t)30 * 24 * 60 * 60 * 1000; +const int64_t ONE_YEAR_TIME_DEBUG = (int64_t)1 * 40 * 60 * 1000; +const int64_t ONE_YEAR_TIME = (int64_t)365 * 24 * 60 * 60 * 1000; const int64_t LAST_TIME_IN_MILLIS_MIN = 0; const int64_t EVENT_TIME_IN_MILLIS_MIN = 0; const int64_t EVENT_BEGIN_TIME_INITIAL_VALUE = -1; @@ -92,10 +102,11 @@ const std::string BUNDLE_ACTIVE_DB_SCREEN_ON_DURATION = "screenOnDuration"; const std::string REFRESH_DATABASE_RUNNER_NAME = "RefreshDatabase"; const std::string BUNDLE_ACTIVE_DATABASE_DIR = "/data/system_ce/bundle_usage/"; const std::string BUNDLE_ACTIVE_VERSION_FILE = "/version"; -const std::string BUNDLE_ACTIVE_DATABASE_SUFFIX = ".db"; const std::string DATABASE_FILE_TABLE_NAME = "table"; const std::string SQLITE_MASTER_NAME = "name"; -const std::string DATABASE_TYPE[] = {"daily.db", "weekly.db", "monthly.db", "yearly.db", "event.db", "usageGroup.db"}; +const std::string DATABASE_TYPE[] = {"daily", "weekly", "monthly", "yearly", "event", "usageGroup"}; +const std::string SUFFIX_TYPE[] = {".db", ".db-shm", ".db-wal"}; } // namespace DeviceUsageStats } // namespace OHOS -#endif // BUNDLE_ACTIVE_CONSTANT_H \ No newline at end of file +#endif // BUNDLE_ACTIVE_CONSTANT_H + diff --git a/services/common/include/bundle_active_continuous_task_observer.h b/services/common/include/bundle_active_continuous_task_observer.h index e09815c0d3ff76bf33555b4d43b6bb9b4a98f173..3586b1fd54df3d06209440209772e6162f5f80ea 100644 --- a/services/common/include/bundle_active_continuous_task_observer.h +++ b/services/common/include/bundle_active_continuous_task_observer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 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 @@ -45,6 +45,7 @@ private: void ReportContinuousTaskEvent(const std::shared_ptr& continuousTaskCallbackInfo, const bool isStart); }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_CONTINUOUS_TASK_OBSERVER_H + diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 5464548fdc4cb98683a4719612120e3afe075c5f..e2037b1cc3611b3958ac4684c133339b4d613bfa 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -22,6 +22,7 @@ #include "os_account_manager.h" #include "ibundle_active_service.h" +#include "bundle_active_debug_mode.h" #include "bundle_active_stats_update_listener.h" #include "bundle_active_user_service.h" #include "bundle_active_group_controller.h" @@ -37,8 +38,9 @@ public: int userId_; std::string bundleName_; BundleActiveReportHandlerObject(); + BundleActiveReportHandlerObject(const int userId, const std::string bundleName); BundleActiveReportHandlerObject(const BundleActiveReportHandlerObject& orig); - ~BundleActiveReportHandlerObject() {}; + ~BundleActiveReportHandlerObject() {} }; class BundleActiveReportHandler; @@ -113,19 +115,21 @@ public: void ConvertToSystemTimeLocked(BundleActiveEvent& event); // get or create BundleActiveUserService object for specifice user. std::shared_ptr GetUserDataAndInitializeIfNeeded(const int userId, - const int64_t timeStamp); + const int64_t timeStamp, const bool debug); // when received a USER_REMOVED commen event, call it to remove data. void OnUserRemoved(const int userId); + void OnUserSwitched(const int userId); // force set app group. void SetBundleGroup(const std::string& bundleName, const int newGroup, const int userId); // get all user in device - void GetAllActiveUser(std::vector &osAccountInfos); + void GetAllActiveUser(std::vector& activatedOsAccountIds); // when service stop, call it to unregister commen event and shutdown call back. void UnRegisterSubscriber(); int64_t GetSystemTimeMs(); + int currentUsedUser_; private: - static const int64_t FLUSH_INTERVAL = TWO_MINUTE; + int64_t flushInterval_; static const int64_t TIME_CHANGE_THRESHOLD_MILLIS = TWO_SECONDS; const int DEFAULT_USER_ID = -1; std::map visibleActivities_; @@ -140,7 +144,9 @@ private: void RegisterSubscriber(); std::shared_ptr commonEventSubscriber_; void RestoreAllData(); + bool debugCore_; }; -} -} -#endif +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_CORE_H + diff --git a/services/common/include/bundle_active_debug_mode.h b/services/common/include/bundle_active_debug_mode.h new file mode 100644 index 0000000000000000000000000000000000000000..667113a42450d563286c3310f99006d402952599 --- /dev/null +++ b/services/common/include/bundle_active_debug_mode.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2022 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_DEBUG_MODE_H +#define BUNDLE_ACTIVE_DEBUG_MODE_H + +namespace OHOS { +namespace DeviceUsageStats { +extern const bool DEBUG_ON; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_DEBUG_MODE_H + diff --git a/services/common/include/bundle_active_log.h b/services/common/include/bundle_active_log.h index d4bc93a37ad4c9949d94b738d40bb8e5d4c225c7..0dae499429053ba09c28100bea212a8274618293 100644 --- a/services/common/include/bundle_active_log.h +++ b/services/common/include/bundle_active_log.h @@ -76,5 +76,5 @@ private: #define BUNDLE_ACTIVE_LOGF(fmt, ...) PRINT_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) } // namespace DeviceUsageStats } // namespace OHOS +#endif // BUNDLE_ACTIVE_LOG_H -#endif // BUNDLE_ACTIVE_LOG_H \ No newline at end of file diff --git a/services/common/include/bundle_active_open_callback.h b/services/common/include/bundle_active_open_callback.h index 235c8d488384df48fef11184e320c3a66bc33b10..7bd1a7d03965e35cd10380c3537ec34939f95d3b 100644 --- a/services/common/include/bundle_active_open_callback.h +++ b/services/common/include/bundle_active_open_callback.h @@ -30,6 +30,7 @@ public: int32_t OnCreate(NativeRdb::RdbStore &rdbStore) override; int32_t OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) override; }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_OPEN_CALLBACK_H + diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index c0ec21705dda6664982e55965135d2de37b46d7f..ff28fc2b0caadf26ced29958b6b2695ea014f740 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -40,8 +40,9 @@ public: const std::string& continuousTask, const int userId, const int eventId) override; bool IsBundleIdle(const std::string& bundleName) override; std::vector QueryPackageStats(const int intervalType, const int64_t beginTime, - const int64_t endTime) override; - std::vector QueryEvents(const int64_t beginTime, const int64_t endTime) override; + const int64_t endTime, int32_t& errCode) override; + std::vector QueryEvents(const int64_t beginTime, const int64_t endTime, + int32_t& errCode) override; void SetBundleGroup(const std::string& bundleName, int newGroup, int userId) override; std::vector QueryCurrentPackageStats(const int intervalType, const int64_t beginTime, const int64_t endTime) override; @@ -66,14 +67,16 @@ private: std::shared_ptr handler_; int ConvertIntervalType(const int intervalType); void InitNecessaryState(); + void InitService(); bool GetBundleMgrProxy(); - bool CheckBundleIsSystemAppAndHasPermission(const int uid, const int userId); + bool CheckBundleIsSystemAppAndHasPermission(const int uid, const int userId, int32_t& errCode); void InitAppStateSubscriber(const std::shared_ptr& reportHandler); void InitContinuousSubscriber(const std::shared_ptr& reportHandler); bool SubscribeAppState(); bool SubscribeContinuousTask(); OHOS::sptr GetAppManagerInstance(); }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_SERVICE_H + diff --git a/services/common/include/bundle_active_shutdown_callback_proxy.h b/services/common/include/bundle_active_shutdown_callback_proxy.h index b62c001ff1afe424cf02cda32595021ec94388bc..e53fe5e96768074c1993b14cf201075cc684a376 100644 --- a/services/common/include/bundle_active_shutdown_callback_proxy.h +++ b/services/common/include/bundle_active_shutdown_callback_proxy.h @@ -33,6 +33,7 @@ public: private: static inline BrokerDelegator delegator_; }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_SHUTDOWN_CALLBACK_PROXY_H + diff --git a/services/common/include/bundle_active_shutdown_callback_service.h b/services/common/include/bundle_active_shutdown_callback_service.h index b31387302c3d726e1ae338568439f6628f6cd094..95b3648a2a29ec43afaf0734409b6bd46e79dddb 100644 --- a/services/common/include/bundle_active_shutdown_callback_service.h +++ b/services/common/include/bundle_active_shutdown_callback_service.h @@ -24,11 +24,12 @@ namespace DeviceUsageStats { class BundleActiveShutdownCallbackService : public BundleActiveShutdownCallbackStub { public: BundleActiveShutdownCallbackService(std::shared_ptr bundleActiveCore); - virtual ~BundleActiveShutdownCallbackService() {}; + virtual ~BundleActiveShutdownCallbackService() {} void ShutdownCallback() override; private: std::shared_ptr bundleActiveCore_; }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_SHUTDOWN_CALLBACK_SERVICE_H + diff --git a/services/common/include/bundle_active_shutdown_callback_stub.h b/services/common/include/bundle_active_shutdown_callback_stub.h index e0c110fea242dd9f2b7a43fc94a837f4923424da..bef14c8870d6deb5fa2e6312a9e2f9574bad30b8 100644 --- a/services/common/include/bundle_active_shutdown_callback_stub.h +++ b/services/common/include/bundle_active_shutdown_callback_stub.h @@ -33,7 +33,7 @@ public: private: void ShutdownStub(); }; -} -} +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_SHUTDOWN_CALLBACK_STUB_H -#endif \ No newline at end of file diff --git a/services/common/include/bundle_active_stub.h b/services/common/include/bundle_active_stub.h index 596fb3cb1c95ee01b320fcfc5742c9abf551b800..51164a1e66d6b404c1211605961c769d7e2635aa 100644 --- a/services/common/include/bundle_active_stub.h +++ b/services/common/include/bundle_active_stub.h @@ -22,11 +22,12 @@ namespace OHOS { namespace DeviceUsageStats { class BundleActiveStub : public IRemoteStub { public: - virtual int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply, + int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply, MessageOption &option) override; - BundleActiveStub() {}; - ~BundleActiveStub() {}; + BundleActiveStub() {} + ~BundleActiveStub() {} }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_STUB_H + diff --git a/services/common/include/bundle_active_usage_database.h b/services/common/include/bundle_active_usage_database.h index f52a995c3d5046667ff34c34aa071c930d259774..d858749611d3d87efe46786615e50d39ed258cba 100644 --- a/services/common/include/bundle_active_usage_database.h +++ b/services/common/include/bundle_active_usage_database.h @@ -56,6 +56,7 @@ public: std::shared_ptr>> GetBundleHistoryData(int userId); void OnPackageUninstalled(const int userId, const std::string& bundleName); + void ChangeToDebug(); private: void CheckDatabaseVersion(); @@ -82,6 +83,7 @@ private: unsigned int databaseType); int32_t CreateDatabasePath(); int64_t GetSystemTimeMs(); + void CheckDatabaseFile(unsigned int databaseType); private: std::vector databaseFiles_; @@ -96,7 +98,9 @@ private: uint32_t currentVersion_; std::mutex databaseMutex_; std::int64_t eventBeginTime_; + bool debugDatabase_; }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_USAGE_DATABASE_H + diff --git a/services/common/include/ibundle_active_service.h b/services/common/include/ibundle_active_service.h index 147b0eee85342d26d83419cf6605cf41ad0f98ac..401584ea340ab07bfc9b57ef6ba98a4e9c2bb2f5 100644 --- a/services/common/include/ibundle_active_service.h +++ b/services/common/include/ibundle_active_service.h @@ -46,8 +46,9 @@ public: const std::string& continuousTask, const int userId, const int eventId) = 0; virtual bool IsBundleIdle(const std::string& bundleName) = 0; virtual std::vector QueryPackageStats(const int intervalType, const int64_t beginTime, - const int64_t endTime) = 0; - virtual std::vector QueryEvents(const int64_t beginTime, const int64_t endTime) = 0; + const int64_t endTime, int32_t& errCode) = 0; + virtual std::vector QueryEvents(const int64_t beginTime, const int64_t endTime, + int32_t& errCode) = 0; virtual std::vector QueryCurrentPackageStats(const int intervalType, const int64_t beginTime, const int64_t endTime) = 0; virtual std::vector QueryCurrentEvents(const int64_t beginTime, const int64_t endTime) = 0; @@ -68,6 +69,7 @@ public: public: DECLARE_INTERFACE_DESCRIPTOR(u"Resourceschedule.IBundleActiveService"); }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_ISERVICE_H + diff --git a/services/common/src/bundle_active_app_state_obsever.cpp b/services/common/src/bundle_active_app_state_obsever.cpp index 1bebdd57dac5cca5056e80ec05bfed8759e2b790..5f3a951fd46550b9475b0c7d51610666915154e4 100644 --- a/services/common/src/bundle_active_app_state_obsever.cpp +++ b/services/common/src/bundle_active_app_state_obsever.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 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 @@ -44,12 +44,11 @@ void BundleActiveAppStateObserver::OnAbilityStateChanged(const AbilityStateData std::stringstream stream; stream << abilityStateData.token.GetRefPtr(); std::string abilityId = stream.str(); - BundleActiveReportHandlerObject tmpHandlerObject; + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); tmpHandlerObject.event_.bundleName_ = abilityStateData.bundleName; tmpHandlerObject.event_.abilityName_ = abilityStateData.abilityName; tmpHandlerObject.event_.abilityId_ = abilityStateData.abilityName; tmpHandlerObject.event_.continuousTaskAbilityName_ = ""; - tmpHandlerObject.userId_ = userId; sptr timer = MiscServices::TimeServiceClient::GetInstance(); tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); switch (abilityStateData.abilityState) { @@ -82,25 +81,6 @@ void BundleActiveAppStateObserver::OnAbilityStateChanged(const AbilityStateData } return; } +} // namespace DeviceUsageStats +} // namespace OHOS -void BundleActiveAppStateObserver::OnForegroundApplicationChanged(const AppStateData &appStateData) -{ -} - -void BundleActiveAppStateObserver::OnExtensionStateChanged(const AbilityStateData &abilityStateData) -{ -} - -void BundleActiveAppStateObserver::OnProcessCreated(const ProcessData &processData) -{ -} - -void BundleActiveAppStateObserver::OnProcessDied(const ProcessData &processData) -{ -} - -void BundleActiveAppStateObserver::OnApplicationStateChanged(const AppStateData &appStateData) -{ -} -} -} \ No newline at end of file diff --git a/services/common/src/bundle_active_binary_search.cpp b/services/common/src/bundle_active_binary_search.cpp index f16cf9348a07a1511d11350ca056d0064d28dc03..b79b88586f79139f4d0ced7bb21c592e51b00cb5 100644 --- a/services/common/src/bundle_active_binary_search.cpp +++ b/services/common/src/bundle_active_binary_search.cpp @@ -30,8 +30,9 @@ int32_t BundleActiveBinarySearch::BinarySearch(const std::vector &table { int32_t low = 0; int32_t high = static_cast(tableNameArray.size() - 1); + int32_t divider = 2; while (low <= high) { - int32_t mid = (low + high) >> 1; + int32_t mid = (low + high) / divider; int64_t midValue = tableNameArray.at(mid); if (midValue < targetValue) { low = mid + 1; @@ -43,5 +44,6 @@ int32_t BundleActiveBinarySearch::BinarySearch(const std::vector &table } return -1; } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_continuous_task_observer.cpp b/services/common/src/bundle_active_continuous_task_observer.cpp index 459524f71a7aebecae2d4bbb9c9a7902f4dfdc28..5492acee143f5b71b9199e836b05a1e4c2b34c88 100644 --- a/services/common/src/bundle_active_continuous_task_observer.cpp +++ b/services/common/src/bundle_active_continuous_task_observer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 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 @@ -87,13 +87,11 @@ void BundleActiveContinuousTaskObserver::ReportContinuousTaskEvent( } OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); if (ret == ERR_OK && userId != -1 && !bundleName.empty()) { - std::stringstream stream; - BundleActiveReportHandlerObject tmpHandlerObject; + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); tmpHandlerObject.event_.bundleName_ = bundleName; tmpHandlerObject.event_.abilityName_ = ""; tmpHandlerObject.event_.abilityId_ = abilityId; tmpHandlerObject.event_.continuousTaskAbilityName_ = abiliytName; - tmpHandlerObject.userId_ = userId; sptr timer = MiscServices::TimeServiceClient::GetInstance(); tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); if (isStart) { @@ -116,5 +114,6 @@ void BundleActiveContinuousTaskObserver::ReportContinuousTaskEvent( } } } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 25fe675d5d0b703efff9a7c98c28dea84c847b6a..01f0293a7b73840af847325695285af9ad877be2 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -23,12 +23,19 @@ namespace OHOS { namespace DeviceUsageStats { +const std::string LAUNCHER_BUNDLE_NAME = "com.ohos.launcher"; BundleActiveReportHandlerObject::BundleActiveReportHandlerObject() { userId_ = -1; bundleName_ = ""; } +BundleActiveReportHandlerObject::BundleActiveReportHandlerObject(const int userId, const std::string bundleName) +{ + userId_ = userId; + bundleName_ = bundleName; +} + BundleActiveReportHandlerObject::BundleActiveReportHandlerObject(const BundleActiveReportHandlerObject& orig) { event_.bundleName_ = orig.event_.bundleName_; @@ -45,6 +52,14 @@ BundleActiveCore::BundleActiveCore() { systemTimeShot_ = -1; realTimeShot_ = -1; + currentUsedUser_ = -1; + if (DEBUG_ON) { + flushInterval_ = TWO_MINUTE; + debugCore_ = true; + } else { + flushInterval_ = THIRTY_MINUTE; + debugCore_ = false; + } } BundleActiveCore::~BundleActiveCore() @@ -56,7 +71,6 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da std::lock_guard lock(mutex_); std::string action = data.GetWant().GetAction(); BUNDLE_ACTIVE_LOGI("OnReceiveEvent action is %{public}s", action.c_str()); - auto want = data.GetWant(); if (action == CommonEventSupport::COMMON_EVENT_SCREEN_OFF || action == CommonEventSupport::COMMON_EVENT_SCREEN_ON) { if (!activeGroupController_.expired()) { @@ -70,19 +84,20 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da if (!bundleActiveReportHandler_.expired()) { int32_t userId = data.GetCode(); BUNDLE_ACTIVE_LOGI("remove user id %{public}d", userId); - BundleActiveReportHandlerObject tmpHandlerObject; - tmpHandlerObject.userId_ = userId; + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); std::shared_ptr handlerobjToPtr = std::make_shared(tmpHandlerObject); auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_REMOVE_USER, handlerobjToPtr); bundleActiveReportHandler_.lock()->SendEvent(event); } - } else if (action == CommonEventSupport::COMMON_EVENT_USER_ADDED) { + } else if (action == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { int32_t userId = data.GetCode(); - BUNDLE_ACTIVE_LOGI("OnReceiveEvent receive add user event, user id is %{public}d", userId); - if (!activeGroupController_.expired() && userId >= 0) { - activeGroupController_.lock()->PeriodCheckBundleState(userId); - } + 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 event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_SWITCH_USER, handlerobjToPtr); + bundleActiveReportHandler_.lock()->SendEvent(event); } else if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED || action == CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED) { int32_t userId = data.GetWant().GetIntParam("userId", 0); @@ -90,15 +105,12 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da 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; - tmpHandlerObject.bundleName_ = bundleName; - tmpHandlerObject.userId_ = userId; + BundleActiveReportHandlerObject tmpHandlerObject(userId, bundleName); std::shared_ptr handlerobjToPtr = std::make_shared(tmpHandlerObject); auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_BUNDLE_UNINSTALLED, handlerobjToPtr); - bundleActiveReportHandler_.lock()->SendEvent(BundleActiveReportHandler::MSG_BUNDLE_UNINSTALLED, - handlerobjToPtr); + bundleActiveReportHandler_.lock()->SendEvent(event); } } } @@ -109,7 +121,7 @@ void BundleActiveCore::RegisterSubscriber() matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_OFF); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_ON); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED); - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_ADDED); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); @@ -134,7 +146,7 @@ void BundleActiveCore::Init() } while (realTimeShot_ == -1 && systemTimeShot_ == -1); realTimeShot_ = timer->GetBootTimeMs(); systemTimeShot_ = GetSystemTimeMs(); - bundleGroupController_ = std::make_shared(); + bundleGroupController_ = std::make_shared(debugCore_); BUNDLE_ACTIVE_LOGI("system time shot is %{public}lld", systemTimeShot_); } @@ -147,7 +159,7 @@ void BundleActiveCore::InitBundleGroupController() BUNDLE_ACTIVE_LOGE("report handler is null"); return; } - bundleGroupHandler_ = std::make_shared(runner); + bundleGroupHandler_ = std::make_shared(runner, debugCore_); if (bundleGroupHandler_ == nullptr) { return; } @@ -155,13 +167,19 @@ void BundleActiveCore::InitBundleGroupController() bundleGroupHandler_->Init(bundleGroupController_); bundleGroupController_->SetHandlerAndCreateUserHistory(bundleGroupHandler_, realTimeShot_); BUNDLE_ACTIVE_LOGI("Init Set group controller and handler done"); + } else { + return; } RegisterSubscriber(); - std::vector osAccountInfos; - GetAllActiveUser(osAccountInfos); + std::vector activatedOsAccountIds; bundleGroupController_->bundleGroupEnable_ = true; - for (uint32_t i = 0; i < osAccountInfos.size(); i++) { - bundleGroupController_->PeriodCheckBundleState(osAccountInfos[i].GetLocalId()); + 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]); } } @@ -171,24 +189,25 @@ void BundleActiveCore::SetHandler(const std::shared_ptr BundleActiveCore::GetUserDataAndInitializeIfNeeded(const int userId, - const int64_t timeStamp) + const int64_t timeStamp, const bool debug) { BUNDLE_ACTIVE_LOGI("GetUserDataAndInitializeIfNeeded called"); std::map>::iterator it = userStatServices_.find(userId); if (it == userStatServices_.end()) { BUNDLE_ACTIVE_LOGI("first initialize user service"); - std::shared_ptr service = std::make_shared(userId, *this); - service->Init(timeStamp); - userStatServices_[userId] = service; + std::shared_ptr service = std::make_shared(userId, *this, + debug); if (service == nullptr) { - BUNDLE_ACTIVE_LOGE("service is null"); return nullptr; } + service->Init(timeStamp); + userStatServices_[userId] = service; BUNDLE_ACTIVE_LOGI("service is not null"); return service; } return it->second; } + void BundleActiveCore::OnBundleUninstalled(const int userId, const std::string& bundleName) { BUNDLE_ACTIVE_LOGI("OnBundleUninstalled CALLED"); @@ -197,7 +216,7 @@ void BundleActiveCore::OnBundleUninstalled(const int userId, const std::string& if (timeNow == -1) { return; } - auto service = GetUserDataAndInitializeIfNeeded(userId, timeNow); + auto service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_); if (service == nullptr) { return; } @@ -208,13 +227,15 @@ void BundleActiveCore::OnBundleUninstalled(const int userId, const std::string& void BundleActiveCore::OnStatsChanged(const int userId) { if (!handler_.expired()) { - BUNDLE_ACTIVE_LOGI("OnStatsChanged send flush to disk event"); BundleActiveReportHandlerObject tmpHandlerObject; tmpHandlerObject.userId_ = userId; std::shared_ptr handlerobjToPtr = std::make_shared(tmpHandlerObject); auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_FLUSH_TO_DISK, handlerobjToPtr); - handler_.lock()->SendEvent(event, FLUSH_INTERVAL); + if (handler_.lock()->HasInnerEvent(static_cast(userId)) == false) { + BUNDLE_ACTIVE_LOGI("OnStatsChanged send flush to disk event for user %{public}d", userId); + handler_.lock()->SendEvent(event, flushInterval_); + } } } @@ -225,6 +246,7 @@ void BundleActiveCore::RestoreAllData() std::shared_ptr service = it->second; if (service == nullptr) { BUNDLE_ACTIVE_LOGI("service in BundleActiveCore::RestoreToDatabaseLocked() is null"); + return; } BUNDLE_ACTIVE_LOGI("userid is %{public}d ", service->userId_); service->RestoreStats(true); @@ -236,7 +258,7 @@ void BundleActiveCore::RestoreAllData() bundleGroupController_->RestoreDurationToDatabase(); } if (!handler_.expired()) { - BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked remove flush to disk event"); + BUNDLE_ACTIVE_LOGI("RestoreAllData remove flush to disk event"); handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); } } @@ -280,7 +302,15 @@ void BundleActiveCore::ShutDown() int64_t timeStamp = timer->GetBootTimeMs(); BundleActiveEvent event(BundleActiveEvent::SHUTDOWN, timeStamp); event.bundleName_ = BundleActiveEvent::DEVICE_EVENT_PACKAGE_NAME; - bundleGroupController_->ShutDown(timeStamp); + std::vector activatedOsAccountIds; + 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_->ShutDown(timeStamp, activatedOsAccountIds[i]); + } ReportEventToAllUserId(event); RestoreAllData(); } @@ -322,7 +352,7 @@ int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime(int userId) it->second->RenewTableTime(expectedSystemTime, actualSystemTime); it->second->LoadActiveStats(actualSystemTime, true, true); if (!handler_.expired()) { - BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked remove flush to disk event"); + BUNDLE_ACTIVE_LOGI("CheckTimeChangeAndGetWallTime remove flush to disk event"); handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); } } @@ -352,23 +382,62 @@ void BundleActiveCore::OnUserRemoved(const int userId) bundleGroupController_->OnUserRemoved(userId); } +void BundleActiveCore::OnUserSwitched(const int userId) +{ + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + auto it = userStatServices_.find(currentUsedUser_); + if (it != userStatServices_.end()) { + BUNDLE_ACTIVE_LOGI("restore old user id %{public}d data when switch user", currentUsedUser_); + BundleActiveEvent event; + event.eventId_ = BundleActiveEvent::FLUSH; + int64_t actualRealTime = timer->GetBootTimeMs(); + event.timeStamp_ = (actualRealTime - realTimeShot_) + systemTimeShot_; + event.abilityId_ = ""; + it->second->ReportEvent(event); + it->second->RestoreStats(true); + } + std::vector activatedOsAccountIds; + 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++) { + BUNDLE_ACTIVE_LOGI("start to period check for userId %{public}d", activatedOsAccountIds[i]); + bundleGroupController_->OnUserSwitched(activatedOsAccountIds[i], currentUsedUser_); + } + currentUsedUser_ = userId; + OnStatsChanged(userId); +} + int BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int userId) { + BUNDLE_ACTIVE_LOGI("FLUSH interval is %{public}lld, debug is %{public}d", flushInterval_, debugCore_); std::lock_guard lock(mutex_); - if (userId == 0) { + if (userId == 0 || userId == -1) { return -1; } - BUNDLE_ACTIVE_LOGI("ReportEvent called"); + if (currentUsedUser_ == -1) { + currentUsedUser_ = userId; + BUNDLE_ACTIVE_LOGI("last used id change to %{public}d", currentUsedUser_); + } + + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + int64_t bootBasedTimeStamp = timer->GetBootTimeMs(); + if (event.bundleName_ == LAUNCHER_BUNDLE_NAME) { + BUNDLE_ACTIVE_LOGI("launcher event, only update app group"); + bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId); + return 0; + } + BUNDLE_ACTIVE_LOGI("report event called bundle name %{public}s time %{public}lld userId %{public}d, " "eventid %{public}d, in lock range", event.bundleName_.c_str(), event.timeStamp_, userId, event.eventId_); - sptr timer = MiscServices::TimeServiceClient::GetInstance(); int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); if (timeNow == -1) { return -1; } - int64_t bootBasedTimeStamp = timer->GetBootTimeMs(); ConvertToSystemTimeLocked(event); - std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow); + std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_); if (service == nullptr) { BUNDLE_ACTIVE_LOGE("get user data service failed!"); return -1; @@ -386,12 +455,13 @@ int BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event) return -1; } if (userStatServices_.empty()) { - std::shared_ptr service = GetUserDataAndInitializeIfNeeded(DEFAULT_USER_ID, timeNow); + return DEFAULT_USER_ID; } for (std::map>::iterator it = userStatServices_.begin(); it != userStatServices_.end(); it++) { ConvertToSystemTimeLocked(event); - std::shared_ptr service = GetUserDataAndInitializeIfNeeded(it->first, timeNow); + std::shared_ptr service = GetUserDataAndInitializeIfNeeded(it->first, timeNow, + debugCore_); if (service == nullptr) { BUNDLE_ACTIVE_LOGE("get user data service failed!"); return -1; @@ -420,7 +490,7 @@ std::vector BundleActiveCore::QueryPackageStats(const BUNDLE_ACTIVE_LOGI("QueryPackageStats time span illegal"); return result; } - std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow); + std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_); if (service == nullptr) { BUNDLE_ACTIVE_LOGI("QueryPackageStats service is null, failed"); return result; @@ -442,7 +512,7 @@ std::vector BundleActiveCore::QueryEvents(const int userId, c if (beginTime > timeNow || beginTime >= endTime) { return result; } - std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow); + std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_); if (service == nullptr) { return result; } @@ -468,14 +538,13 @@ int BundleActiveCore::IsBundleIdle(const std::string& bundleName, const int user return bundleGroupController_->IsBundleIdle(bundleName, userId); } -void BundleActiveCore::GetAllActiveUser(std::vector &osAccountInfos) +void BundleActiveCore::GetAllActiveUser(std::vector& activatedOsAccountIds) { - OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); - if (ret != ERR_OK) { - BUNDLE_ACTIVE_LOGI("GetAllActiveUser failed"); + if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(activatedOsAccountIds) != ERR_OK) { + BUNDLE_ACTIVE_LOGI("query activated account failed"); return; } - if (osAccountInfos.size() == 0) { + if (activatedOsAccountIds.size() == 0) { BUNDLE_ACTIVE_LOGI("GetAllActiveUser size is 0"); return; } @@ -498,5 +567,6 @@ int64_t BundleActiveCore::GetSystemTimeMs() } return static_cast(tarDate); } -} -} +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_debug_mode.cpp b/services/common/src/bundle_active_debug_mode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5863fc6766cb77858e0f16833ba913d459c7ebff --- /dev/null +++ b/services/common/src/bundle_active_debug_mode.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022 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 +#include + +#include "bundle_active_debug_mode.h" + +using OHOS::system::GetIntParameter; +using OHOS::system::GetParameter; + +namespace OHOS { +namespace DeviceUsageStats { +constexpr int DEBUG_ON_DEFAULT = false; +std::string DEBUG_MODE = "persist.sys.device_usage_debug_on"; +const bool DEBUG_ON = static_cast(GetIntParameter(DEBUG_MODE, DEBUG_ON_DEFAULT)); +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_log.cpp b/services/common/src/bundle_active_log.cpp index ddd88396ae277f3dc994e8192364ac3416ed1d05..2f875b4fb2297d6c92ae17f90a7aa0e9279be3d8 100644 --- a/services/common/src/bundle_active_log.cpp +++ b/services/common/src/bundle_active_log.cpp @@ -41,3 +41,4 @@ std::string BundleActiveLog::GetCurrFileName(const char *str) } } // namespace DeviceUsageStats } // namespace OHOS + diff --git a/services/common/src/bundle_active_open_callback.cpp b/services/common/src/bundle_active_open_callback.cpp index 6e1ce14b30b640c94487bf3ada4a49a4a7ea281b..c11410228e2b0e6ccb9d63c5c19658b1c8c012ac 100644 --- a/services/common/src/bundle_active_open_callback.cpp +++ b/services/common/src/bundle_active_open_callback.cpp @@ -35,8 +35,12 @@ int32_t BundleActiveOpenCallback::OnCreate(NativeRdb::RdbStore &rdbStore) int32_t BundleActiveOpenCallback::OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) { + (void)rdbStore; + (void)oldVersion; + (void)newVersion; BUNDLE_ACTIVE_LOGI("Upgrade success."); return NativeRdb::E_OK; }; } // namespace DeviceUsageStats -} // namespace OHOS \ No newline at end of file +} // namespace OHOS + diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 09eb93dc2f320b20b0c07cbba75066646051f830..f9170fa51f607e90adc10dc756c5f2de97c4d8fa 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -75,6 +75,23 @@ void BundleActiveService::InitNecessaryState() return; } + if (systemAbilityManager->GetSystemAbility(APP_MGR_SERVICE_ID) == nullptr + || systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) == nullptr + || systemAbilityManager->GetSystemAbility(POWER_MANAGER_SERVICE_ID) == nullptr + || systemAbilityManager->GetSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr + || systemAbilityManager->GetSystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID) == nullptr + || systemAbilityManager->GetSystemAbility(TIME_SERVICE_ID) == nullptr) { + BUNDLE_ACTIVE_LOGI("request system service object is not ready yet!"); + auto task = [this]() { this->InitNecessaryState(); }; + handler_->PostTask(task, DELAY_TIME); + return; + } + + InitService(); +} + +void BundleActiveService::InitService() +{ if (bundleActiveCore_ == nullptr) { bundleActiveCore_ = std::make_shared(); bundleActiveCore_->Init(); @@ -100,7 +117,7 @@ void BundleActiveService::InitNecessaryState() } try { shutdownCallback_ = new BundleActiveShutdownCallbackService(bundleActiveCore_); - } catch(const std::bad_alloc &e) { + } catch (const std::bad_alloc &e) { BUNDLE_ACTIVE_LOGE("Memory allocation failed"); return; } @@ -118,6 +135,9 @@ OHOS::sptr BundleActiveService::GetAppManagerInstance OHOS::sptr systemAbilityManager = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); OHOS::sptr object = systemAbilityManager->GetSystemAbility(OHOS::APP_MGR_SERVICE_ID); + if (!object) { + return nullptr; + } return OHOS::iface_cast(object); } @@ -141,7 +161,7 @@ bool BundleActiveService::SubscribeAppState() { BUNDLE_ACTIVE_LOGI("SubscribeAppState called"); sptr appManager = GetAppManagerInstance(); - if (appStateObserver_ == nullptr) { + if (appStateObserver_ == nullptr || appManager == nullptr) { BUNDLE_ACTIVE_LOGE("SubscribeAppState appstateobserver is null, return"); return false; } @@ -169,7 +189,6 @@ bool BundleActiveService::SubscribeContinuousTask() return true; } - void BundleActiveService::OnStop() { if (shutdownCallback_ != nullptr) { @@ -186,14 +205,12 @@ void BundleActiveService::OnStop() int BundleActiveService::ReportEvent(std::string& bundleName, std::string& abilityName, std::string abilityId, const std::string& continuousTask, const int userId, const int eventId) { - BUNDLE_ACTIVE_LOGI("report event called123123"); - BundleActiveReportHandlerObject tmpHandlerObject; + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); tmpHandlerObject.event_.bundleName_ = bundleName; tmpHandlerObject.event_.abilityName_ = abilityName; tmpHandlerObject.event_.abilityId_ = abilityId; tmpHandlerObject.event_.eventId_ = eventId; tmpHandlerObject.event_.continuousTaskAbilityName_ = continuousTask; - tmpHandlerObject.userId_ = userId; sptr timer = MiscServices::TimeServiceClient::GetInstance(); tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); std::shared_ptr handlerobjToPtr = @@ -214,15 +231,7 @@ bool BundleActiveService::IsBundleIdle(const std::string& bundleName) int result = -1; OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); if (ret == ERR_OK && userId != -1) { - BUNDLE_ACTIVE_LOGI("IsBundleIdle user id is %{public}d", userId); - if (!GetBundleMgrProxy()) { - BUNDLE_ACTIVE_LOGE("Get bundle manager proxy failed!"); - return true; - } - bool bundleIsSystemApp = sptrBundleMgr_->CheckIsSystemAppByUid(callingUid); - if (bundleIsSystemApp == true) { - result = bundleActiveCore_->IsBundleIdle(bundleName, userId); - } + result = bundleActiveCore_->IsBundleIdle(bundleName, userId); } if (result == 0) { return false; @@ -231,7 +240,7 @@ bool BundleActiveService::IsBundleIdle(const std::string& bundleName) } std::vector BundleActiveService::QueryPackageStats(const int intervalType, - const int64_t beginTime, const int64_t endTime) + const int64_t beginTime, const int64_t endTime, int32_t& errCode) { BUNDLE_ACTIVE_LOGI("QueryPackageStats stats called, intervaltype is %{public}d", intervalType); @@ -244,7 +253,7 @@ std::vector BundleActiveService::QueryPackageStats(con OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); if (ret == ERR_OK && userId != -1) { BUNDLE_ACTIVE_LOGI("QueryPackageStats user id is %{public}d", userId); - bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, userId); + bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, userId, errCode); if (isSystemAppAndHasPermission == true) { int convertedIntervalType = ConvertIntervalType(intervalType); result = bundleActiveCore_->QueryPackageStats(userId, convertedIntervalType, beginTime, endTime, ""); @@ -253,7 +262,8 @@ std::vector BundleActiveService::QueryPackageStats(con return result; } -std::vector BundleActiveService::QueryEvents(const int64_t beginTime, const int64_t endTime) +std::vector BundleActiveService::QueryEvents(const int64_t beginTime, + const int64_t endTime, int32_t& errCode) { BUNDLE_ACTIVE_LOGI("QueryEvents stats called"); std::vector result; @@ -265,7 +275,7 @@ std::vector BundleActiveService::QueryEvents(const int64_t be OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); if (ret == ERR_OK && userId != -1) { BUNDLE_ACTIVE_LOGI("QueryEvents userid is %{public}d", userId); - bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, userId); + bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, userId, errCode); if (isSystemAppAndHasPermission == true) { result = bundleActiveCore_->QueryEvents(userId, beginTime, endTime, ""); } @@ -297,8 +307,9 @@ std::vector BundleActiveService::QueryCurrentPackageSt return result; } std::string bundleName = ""; + int32_t errCode = 0; sptrBundleMgr_->GetBundleNameForUid(callingUid, bundleName); - bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, userId); + bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, userId, errCode); if (!bundleName.empty() && isSystemAppAndHasPermission == true) { int convertedIntervalType = ConvertIntervalType(intervalType); result = bundleActiveCore_->QueryPackageStats(userId, convertedIntervalType, beginTime, endTime, @@ -321,15 +332,9 @@ std::vector BundleActiveService::QueryCurrentEvents(const int int userId = -1; OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); if (ret == ERR_OK && userId != -1) { - BUNDLE_ACTIVE_LOGI("QueryCurrentEvents userid is %{public}d", userId); - if (!GetBundleMgrProxy()) { - BUNDLE_ACTIVE_LOGE("QueryCurrentEvents get bundle manager proxy failed!"); - return result; - } std::string bundleName = ""; sptrBundleMgr_->GetBundleNameForUid(callingUid, bundleName); - bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, userId); - if (!bundleName.empty() && isSystemAppAndHasPermission == true) { + if (!bundleName.empty()) { BUNDLE_ACTIVE_LOGI("QueryCurrentEvents buindle name is %{public}s", bundleName.c_str()); result = bundleActiveCore_->QueryEvents(userId, beginTime, endTime, bundleName); @@ -400,22 +405,30 @@ int BundleActiveService::ConvertIntervalType(const int intervalType) return -1; } -bool BundleActiveService::CheckBundleIsSystemAppAndHasPermission(const int uid, const int userId) +bool BundleActiveService::CheckBundleIsSystemAppAndHasPermission(const int uid, const int userId, int32_t& errCode) { if (!GetBundleMgrProxy()) { BUNDLE_ACTIVE_LOGE("Get bundle manager proxy failed!"); return false; - } - std::string bundleName = ""; - sptrBundleMgr_->GetBundleNameForUid(uid, bundleName); - bool bundleIsSystemApp = sptrBundleMgr_->CheckIsSystemAppByUid(uid); - int bundleHasPermission = sptrBundleMgr_->CheckPermissionByUid(bundleName, NEEDED_PERMISSION, userId); - BUNDLE_ACTIVE_LOGE(" %{public}s is system app %{public}d, " - "has permission %{public}d", bundleName.c_str(), bundleIsSystemApp, bundleHasPermission); - if (bundleIsSystemApp == true && bundleHasPermission == 0) { - return true; - } + } + std::string bundleName = ""; + sptrBundleMgr_->GetBundleNameForUid(uid, bundleName); + bool bundleIsSystemApp = sptrBundleMgr_->CheckIsSystemAppByUid(uid); + int bundleHasPermission = sptrBundleMgr_->CheckPermissionByUid(bundleName, NEEDED_PERMISSION, userId); + if (!bundleIsSystemApp) { + errCode = BUNDLE_ACTIVE_FAIL; + BUNDLE_ACTIVE_LOGE("%{public}s is not system app", bundleName.c_str()); return false; + } else if (bundleHasPermission != 0) { + errCode = bundleHasPermission; + BUNDLE_ACTIVE_LOGE("%{public}s hasn't permission", bundleName.c_str()); + return false; + } else { + BUNDLE_ACTIVE_LOGI(" %{public}s is system app %{public}d, " + "has permission %{public}d", bundleName.c_str(), bundleIsSystemApp, bundleHasPermission); + return true; + } } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_shutdown_callback_proxy.cpp b/services/common/src/bundle_active_shutdown_callback_proxy.cpp index 7ef9740adf25e1b4c3c9db89cd3cf97a027bd7c6..565e54e2bd72ef6673872bdec44cd4517b060df0 100644 --- a/services/common/src/bundle_active_shutdown_callback_proxy.cpp +++ b/services/common/src/bundle_active_shutdown_callback_proxy.cpp @@ -34,5 +34,6 @@ void BundleActiveShutdownCallbackProxy::ShutdownCallback() BUNDLE_ACTIVE_LOGE("BundleActiveShutdownCallbackProxy::ShutdownCallback failed!"); } } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_shutdown_callback_service.cpp b/services/common/src/bundle_active_shutdown_callback_service.cpp index 4832a465607e83636f58a0d9a6cdcf71e6096f44..3d9813ef3bf80695818e1e8ed56e86ee592b7fd4 100644 --- a/services/common/src/bundle_active_shutdown_callback_service.cpp +++ b/services/common/src/bundle_active_shutdown_callback_service.cpp @@ -29,5 +29,7 @@ void BundleActiveShutdownCallbackService::ShutdownCallback() { bundleActiveCore_->ShutDown(); } -} -} +} // namespace DeviceUsageStats +} // namespace OHOS + + diff --git a/services/common/src/bundle_active_shutdown_callback_stub.cpp b/services/common/src/bundle_active_shutdown_callback_stub.cpp index f4cac49b152fea8c7224262b318622dedf966e75..f4550d51293c812ae6346ae6bd761a2a3c0db785 100644 --- a/services/common/src/bundle_active_shutdown_callback_stub.cpp +++ b/services/common/src/bundle_active_shutdown_callback_stub.cpp @@ -40,5 +40,6 @@ void BundleActiveShutdownCallbackStub::ShutdownStub() { ShutdownCallback(); } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_stub.cpp b/services/common/src/bundle_active_stub.cpp index 02c5beb10e732d8a1e856251f69aa8180c1be86c..d22118718cfd9550617726b413797fe4dd6146ef 100644 --- a/services/common/src/bundle_active_stub.cpp +++ b/services/common/src/bundle_active_stub.cpp @@ -49,7 +49,9 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me intervalType); int64_t beginTime = data.ReadInt64(); int64_t endTime = data.ReadInt64(); - result = QueryPackageStats(intervalType, beginTime, endTime); + int32_t errCode = data.ReadInt32(); + result = QueryPackageStats(intervalType, beginTime, endTime, errCode); + reply.WriteInt32(errCode); size = static_cast(result.size()); BUNDLE_ACTIVE_LOGI("OnRemoteRequest QUERY_USAGE_STATS result size is %{public}d", size); reply.WriteInt32(size); @@ -66,8 +68,10 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me int size = 0; int64_t beginTime = data.ReadInt64(); int64_t endTime = data.ReadInt64(); - result = QueryEvents(beginTime, endTime); + int32_t errCode = data.ReadInt32(); + result = QueryEvents(beginTime, endTime, errCode); size = static_cast(result.size()); + reply.WriteInt32(errCode); reply.WriteInt32(size); for (int i = 0; i < size; i++) { bool tmp = result[i].Marshalling(reply); @@ -92,7 +96,7 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me "is %{public}d", intervalType); int64_t beginTime = data.ReadInt64(); int64_t endTime = data.ReadInt64(); - result = QueryPackageStats(intervalType, beginTime, endTime); + result = QueryCurrentPackageStats(intervalType, beginTime, endTime); size = static_cast(result.size()); BUNDLE_ACTIVE_LOGI("OnRemoteRequest QUERY_CURRENT_USAGE_STATS result size " "is %{public}d", size); @@ -130,5 +134,6 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp index 4175d250fc70ad5bcfd45789f20722d945253b52..729b7ffe7daa696fb4068964a3fdd4cfe495672f 100644 --- a/services/common/src/bundle_active_usage_database.cpp +++ b/services/common/src/bundle_active_usage_database.cpp @@ -45,7 +45,7 @@ BundleActiveUsageDatabase::BundleActiveUsageDatabase() currentVersion_ = BUNDLE_ACTIVE_CURRENT_VERSION; versionDirectoryPath_ = BUNDLE_ACTIVE_DATABASE_DIR + BUNDLE_ACTIVE_VERSION_FILE; for (uint32_t i = 0; i < sizeof(DATABASE_TYPE)/sizeof(DATABASE_TYPE[0]); i++) { - databaseFiles_.push_back(DATABASE_TYPE[i]); + databaseFiles_.push_back(DATABASE_TYPE[i] + SUFFIX_TYPE[0]); } eventTableName_ = UNKNOWN_TABLE_NAME; durationTableName_ = UNKNOWN_TABLE_NAME; @@ -53,6 +53,7 @@ BundleActiveUsageDatabase::BundleActiveUsageDatabase() sortedTableArray_ = vector>(SORTED_TABLE_ARRAY_NUMBER); calendar_ = make_shared(); eventBeginTime_ = EVENT_BEGIN_TIME_INITIAL_VALUE; + debugDatabase_ = false; } BundleActiveUsageDatabase::~BundleActiveUsageDatabase() @@ -60,6 +61,11 @@ BundleActiveUsageDatabase::~BundleActiveUsageDatabase() RdbHelper::ClearCache(); } +void BundleActiveUsageDatabase::ChangeToDebug() +{ + calendar_->ChangeToDebug(); + debugDatabase_ = true; +} void BundleActiveUsageDatabase::InitUsageGroupInfo(int32_t databaseType) { lock_guard lock(databaseMutex_); @@ -154,7 +160,7 @@ int32_t BundleActiveUsageDatabase::NearIndexOnOrAfterCurrentTime(int64_t current int64_t tableTime = -1; int32_t divisor = 2; while (low <= high) { - mid = (high - low) / divisor + low; + mid = (high + low) / divisor; tableTime = sortedTableArray.at(mid); if (currentTime > tableTime) { low = mid + 1; @@ -276,7 +282,12 @@ void BundleActiveUsageDatabase::DeleteExcessiveTableData(unsigned int databaseTy return; } int64_t eventTableTime = ParseStartTime(eventTableName_); - int64_t deleteTimePoint = eventBeginTime_ - SIX_DAY_IN_MILLIS_MAX - eventTableTime; + int64_t deleteTimePoint = 0; + if (debugDatabase_) { + deleteTimePoint = eventBeginTime_ - SIX_DAY_IN_MILLIS_MAX_DEBUG - eventTableTime; + } else { + deleteTimePoint = eventBeginTime_ - SIX_DAY_IN_MILLIS_MAX - eventTableTime; + } if (deleteTimePoint <= 0) { return; } @@ -294,7 +305,7 @@ void BundleActiveUsageDatabase::DeleteExcessiveTableData(unsigned int databaseTy } else if (databaseType == APP_GROUP_DATABASE_INDEX) { // 无数据删除 } else { - BUNDLE_ACTIVE_LOGE("databaseType is invalid, databaseType = %{public}d", databaseType); + BUNDLE_ACTIVE_LOGE("databaseType is invalid, databaseType = %{public}u", databaseType); } } @@ -302,8 +313,8 @@ std::unique_ptr> BundleActiveUsageDatabase::GetOverdueTable int64_t currentTimeMillis) { std::unique_ptr> overdueTableCreateTime = std::make_unique>(); - if (databaseType < 0 || databaseType >= sortedTableArray_.size()) { - BUNDLE_ACTIVE_LOGE("databaseType is invalid, databaseType = %{public}d", databaseType); + if (databaseType >= sortedTableArray_.size()) { + BUNDLE_ACTIVE_LOGE("databaseType is invalid, databaseType = %{public}u", databaseType); return nullptr; } string queryDatabaseTableNames = "select * from sqlite_master where type = ?"; @@ -364,8 +375,8 @@ int32_t BundleActiveUsageDatabase::DeleteInvalidTable(unsigned int databaseType, int64_t BundleActiveUsageDatabase::ParseStartTime(const string &tableName) { - int64_t invalidStartTime(BUNDLE_ACTIVE_FAIL); if (tableName.empty()) { + int64_t invalidStartTime(BUNDLE_ACTIVE_FAIL); return invalidStartTime; } string tableTime = tableName; @@ -415,6 +426,30 @@ shared_ptr BundleActiveUsageDatabase::GetBundleActiveRdbSto return rdbStore; } +void BundleActiveUsageDatabase::CheckDatabaseFile(unsigned int databaseType) +{ + std::string databaseFileName = databaseFiles_.at(databaseType); + std::string dbFile; + for (uint32_t i = 0; i < sizeof(SUFFIX_TYPE) / sizeof(SUFFIX_TYPE[0]); i++) { + dbFile = BUNDLE_ACTIVE_DATABASE_DIR + DATABASE_TYPE[databaseType] + SUFFIX_TYPE[i]; + if ((access(dbFile.c_str(), F_OK) != 0) + && (bundleActiveRdbStoreCache_.find(databaseFileName) != bundleActiveRdbStoreCache_.end())) { + bundleActiveRdbStoreCache_.erase(databaseFileName); + std::string rdbStorePath = BUNDLE_ACTIVE_DATABASE_DIR + DATABASE_TYPE[databaseType] + SUFFIX_TYPE[0]; + RdbHelper::DeleteRdbStore(rdbStorePath); + if (databaseType >= 0 && databaseType < sortedTableArray_.size()) { + sortedTableArray_.at(databaseType).clear(); + } else if (databaseType == EVENT_DATABASE_INDEX) { + eventTableName_ = UNKNOWN_TABLE_NAME; + } else if (databaseType == APP_GROUP_DATABASE_INDEX) { + durationTableName_ = UNKNOWN_TABLE_NAME; + bundleHistoryTableName_ = UNKNOWN_TABLE_NAME; + } + return; + } + } +} + int32_t BundleActiveUsageDatabase::CreateEventLogTable(unsigned int databaseType, int64_t currentTimeMillis) { shared_ptr rdbStore = GetBundleActiveRdbStore(databaseType); @@ -539,21 +574,24 @@ void BundleActiveUsageDatabase::PutBundleHistoryData(int userId, BUNDLE_ACTIVE_LOGE("userHistory is nullptr"); return; } - if (bundleHistoryTableName_ == UNKNOWN_TABLE_NAME) { - CreateBundleHistoryTable(APP_GROUP_DATABASE_INDEX); - bundleHistoryTableName_ = BUNDLE_HISTORY_LOG_TABLE; - } shared_ptr rdbStore = GetBundleActiveRdbStore(APP_GROUP_DATABASE_INDEX); if (rdbStore == nullptr) { - BUNDLE_ACTIVE_LOGE("rdbStore is nullptr"); return; } + CheckDatabaseFile(APP_GROUP_DATABASE_INDEX); + if (bundleHistoryTableName_ == UNKNOWN_TABLE_NAME) { + CreateBundleHistoryTable(APP_GROUP_DATABASE_INDEX); + bundleHistoryTableName_ = BUNDLE_HISTORY_LOG_TABLE; + } int32_t changeRow = BUNDLE_ACTIVE_FAIL; int64_t outRowId = BUNDLE_ACTIVE_FAIL; NativeRdb::ValuesBucket valuesBucket; vector queryCondition; + int updatedcount = 0; + int unupdatedcount = 0; for (auto iter = userHistory->begin(); iter != userHistory->end(); iter++) { - if (iter->second == nullptr) { + if (iter->second == nullptr || !iter->second->isChanged_) { + unupdatedcount++; continue; } queryCondition.push_back(to_string(userId)); @@ -576,7 +614,11 @@ void BundleActiveUsageDatabase::PutBundleHistoryData(int userId, } valuesBucket.Clear(); queryCondition.clear(); + iter->second->isChanged_ = false; + updatedcount++; } + BUNDLE_ACTIVE_LOGI("PutBundleHistoryData, update %{public}d bundles, keep %{public}d bundles group", + updatedcount, unupdatedcount); } shared_ptr>> BundleActiveUsageDatabase::GetBundleHistoryData( @@ -626,6 +668,7 @@ shared_ptr>> BundleActiveUsag void BundleActiveUsageDatabase::PutDurationData(int64_t bootBasedDuration, int64_t screenOnDuration) { lock_guard lock(databaseMutex_); + CheckDatabaseFile(APP_GROUP_DATABASE_INDEX); if (durationTableName_ == UNKNOWN_TABLE_NAME) { CreateDurationTable(APP_GROUP_DATABASE_INDEX); durationTableName_ = DURATION_LOG_TABLE; @@ -685,13 +728,12 @@ void BundleActiveUsageDatabase::FlushPackageInfo(unsigned int databaseType, cons queryCondition.push_back(to_string(stats.userId_)); queryCondition.push_back(iter->first); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_BUNDLE_STARTED_COUNT, iter->second->bundleStartedCount_); - valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME, (iter->second->lastTimeUsed_ - stats.beginTime_)); - if (iter->second->lastContiniousTaskUsed_ == -1) { - valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME_CONTINUOUS_TASK, (iter->second->lastContiniousTaskUsed_)); - } else { - valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME_CONTINUOUS_TASK, (iter->second->lastContiniousTaskUsed_ - - stats.beginTime_)); - } + int64_t lastTimeUsedAdjusted = iter->second->lastTimeUsed_ == -1 ? + iter->second->lastTimeUsed_ : iter->second->lastTimeUsed_ - stats.beginTime_; + valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME, lastTimeUsedAdjusted); + int64_t lastContinuousTaskUsedAdjusted = iter->second->lastContiniousTaskUsed_ == -1 ? + iter->second->lastContiniousTaskUsed_ : iter->second->lastContiniousTaskUsed_ - stats.beginTime_; + valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME_CONTINUOUS_TASK, lastContinuousTaskUsedAdjusted); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_TOTAL_TIME, iter->second->totalInFrontTime_); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_TOTAL_TIME_CONTINUOUS_TASK, iter->second->totalContiniousTaskUsedTime_); rdbStore->Update(changeRow, tableName, valuesBucket, "userId = ? and bundleName = ?", queryCondition); @@ -746,13 +788,11 @@ shared_ptr BundleActiveUsageDatabase::GetCurrentUsageDa bundleActiveResult->GetString(BUNDLE_NAME_COLUMN_INDEX, usageStats->bundleName_); bundleActiveResult->GetInt(BUNDLE_STARTED_COUNT_COLUMN_INDEX, usageStats->bundleStartedCount_); bundleActiveResult->GetLong(LAST_TIME_COLUMN_INDEX, relativeLastTimeUsed); - usageStats->lastTimeUsed_ = relativeLastTimeUsed + currentPackageTime; + usageStats->lastTimeUsed_ = relativeLastTimeUsed == -1 ? -1 : + relativeLastTimeUsed + currentPackageTime; bundleActiveResult->GetLong(LAST_TIME_CONTINUOUS_TASK_COLUMN_INDEX, relativeLastTimeFrontServiceUsed); - if (relativeLastTimeFrontServiceUsed == -1) { - usageStats->lastContiniousTaskUsed_ = -1; - } else { - usageStats->lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + currentPackageTime; - } + usageStats->lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed == -1 ? -1 : + relativeLastTimeFrontServiceUsed + currentPackageTime; bundleActiveResult->GetLong(TOTAL_TIME_COLUMN_INDEX, usageStats->totalInFrontTime_); bundleActiveResult->GetLong(TOTAL_TIME_CONTINUOUS_TASK_COLUMN_INDEX, usageStats->totalContiniousTaskUsedTime_); bundleStats.insert(pair>(usageStats->bundleName_, @@ -771,11 +811,15 @@ shared_ptr BundleActiveUsageDatabase::GetCurrentUsageDa void BundleActiveUsageDatabase::FlushEventInfo(unsigned int databaseType, BundleActivePeriodStats &stats) { + shared_ptr rdbStore = GetBundleActiveRdbStore(databaseType); + if (rdbStore == nullptr) { + BUNDLE_ACTIVE_LOGE("rdbStore is nullptr"); + return; + } if (eventTableName_ == UNKNOWN_TABLE_NAME) { CreateEventLogTable(databaseType, stats.beginTime_); } int64_t eventTableTime = ParseStartTime(eventTableName_); - shared_ptr rdbStore = GetBundleActiveRdbStore(databaseType); int64_t outRowId = BUNDLE_ACTIVE_FAIL; NativeRdb::ValuesBucket valuesBucket; for (int32_t i = 0; i < stats.events_.Size(); i++) { @@ -888,6 +932,7 @@ int32_t BundleActiveUsageDatabase::GetOptimalIntervalType(int64_t beginTime, int } } } + BUNDLE_ACTIVE_LOGI("optimalIntervalType is %{public}d", optimalIntervalType); return optimalIntervalType; } @@ -939,7 +984,6 @@ void BundleActiveUsageDatabase::RemoveOldData(int64_t currentTime) void BundleActiveUsageDatabase::RenewTableTime(int64_t changedTime) { lock_guard lock(databaseMutex_); - string logInfo; for (unsigned int i = 0; i < sortedTableArray_.size(); i++) { if (sortedTableArray_.at(i).empty()) { continue; @@ -982,8 +1026,10 @@ void BundleActiveUsageDatabase::UpdateUsageData(int32_t databaseType, BundleActi BUNDLE_ACTIVE_LOGE("databaseType is invalid : %{public}d", databaseType); return; } + CheckDatabaseFile(databaseType); if (databaseType == DAILY_DATABASE_INDEX) { if (stats.events_.Size() != 0) { + CheckDatabaseFile(EVENT_DATABASE_INDEX); FlushEventInfo(EVENT_DATABASE_INDEX, stats); } } @@ -1082,13 +1128,11 @@ vector BundleActiveUsageDatabase::QueryDatabaseUsageSt bundleActiveResult->GetInt(BUNDLE_STARTED_COUNT_COLUMN_INDEX, usageStats.bundleStartedCount_); bundleActiveResult->GetLong(LAST_TIME_COLUMN_INDEX, usageStats.lastTimeUsed_); bundleActiveResult->GetLong(LAST_TIME_COLUMN_INDEX, relativeLastTimeUsed); - usageStats.lastTimeUsed_ = relativeLastTimeUsed + packageTableTime; + usageStats.lastTimeUsed_ = relativeLastTimeUsed == -1 ? -1 : + relativeLastTimeUsed + packageTableTime; bundleActiveResult->GetLong(LAST_TIME_CONTINUOUS_TASK_COLUMN_INDEX, relativeLastTimeFrontServiceUsed); - if (relativeLastTimeFrontServiceUsed == -1) { - usageStats.lastContiniousTaskUsed_ = -1; - } else { - usageStats.lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + packageTableTime; - } + usageStats.lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed == -1 ? -1 : + relativeLastTimeFrontServiceUsed + packageTableTime; bundleActiveResult->GetLong(TOTAL_TIME_COLUMN_INDEX, usageStats.totalInFrontTime_); bundleActiveResult->GetLong(TOTAL_TIME_CONTINUOUS_TASK_COLUMN_INDEX, usageStats.totalContiniousTaskUsedTime_); @@ -1142,7 +1186,6 @@ vector BundleActiveUsageDatabase::QueryDatabaseEvents(int64_t int32_t tableRowNumber; bundleActiveResult->GetRowCount(tableRowNumber); BundleActiveEvent event; - string timeStamp; string relativeTimeStamp; for (int32_t i = 0; i < tableRowNumber; i++) { bundleActiveResult->GoToRow(i); @@ -1212,5 +1255,6 @@ int64_t BundleActiveUsageDatabase::GetSystemTimeMs() } return static_cast(tarDate); } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/packagegroup/include/bundle_active_group_common.h b/services/packagegroup/include/bundle_active_group_common.h index d3fdef4bd2c1294f99c2c08d19bf01d02dd56e9e..48208acfc275c9ad26be21334ac6423fa7e6f3f4 100644 --- a/services/packagegroup/include/bundle_active_group_common.h +++ b/services/packagegroup/include/bundle_active_group_common.h @@ -59,7 +59,9 @@ const uint32_t GROUP_EVENT_REASON_BACKGROUND = 0x0005; const uint32_t GROUP_EVENT_REASON_ALIVE_TIMEOUT = 0x0006; const uint32_t GROUP_EVENT_REASON_LONG_TIME_TASK_STARTTED = 0x0007; const uint32_t GROUP_EVENT_REASON_CALCULATED_RESTORED = 0x0008; +const uint32_t GROUP_EVENT_REASON_ALIVE_NOT_TIMEOUT = 0x0009; } -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_GROUP_COMMON_H + diff --git a/services/packagegroup/include/bundle_active_group_controller.h b/services/packagegroup/include/bundle_active_group_controller.h index 1de660fc0c4a8a0f29a6fd540407a3ec577e894a..4bfb845c82c3eb4deeeeaf55ab44ca54fab785b0 100644 --- a/services/packagegroup/include/bundle_active_group_controller.h +++ b/services/packagegroup/include/bundle_active_group_controller.h @@ -43,27 +43,16 @@ public: using ApplicationFlag = OHOS::AppExecFwk::ApplicationFlag; OHOS::AppExecFwk::ApplicationFlag flag = OHOS::AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO; bool bundleGroupEnable_ = true; - bool debug_ = true; const int LEVEL_GROUP[4] = { ACTIVE_GROUP_ALIVE, ACTIVE_GROUP_DAILY, ACTIVE_GROUP_FIXED, ACTIVE_GROUP_RARE }; - const int64_t SCREEN_TIME_LEVEL[4] = { - 0, - 0, - debug_ ? TWO_MINUTE : ONE_HOUR, - debug_ ? FOUR_MINUTE : TWO_HOUR - }; - const int64_t BOOT_TIME_LEVEL[4] = { - 0, - debug_ ? TWO_MINUTE : TWELVE_HOUR, - debug_ ? FOUR_MINUTE : TWENTY_FOUR_HOUR, - debug_ ? SIXTEEN_MINUTE : FOURTY_EIGHT_HOUR - }; - BundleActiveGroupController() {}; - ~BundleActiveGroupController() {}; + 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, const int64_t bootFromTimeStamp); @@ -83,23 +72,24 @@ public: bool IsScreenOn(); int IsBundleIdle(const std::string& bundleName, const int userId); int QueryPackageGroup(const int userId, const std::string& bundleName); - void ShutDown(const int64_t bootBasedTimeStamp); + void ShutDown(const int64_t bootBasedTimeStamp, const int userId); + void OnUserSwitched(const int userId, const int currentUsedUser); private: std::mutex mutex_; bool GetBundleMgrProxy(); std::weak_ptr activeGroupHandler_; uint32_t EventToGroupReason(const int eventId); - int64_t timeoutForDirectlyUse_ = debug_ ? THREE_MINUTE : ONE_HOUR; - int64_t timeoutForNotifySeen_ = debug_ ? ONE_MINUTE : TWELVE_HOUR; - int64_t timeoutForSystemInteraction_ = debug_ ? ONE_MINUTE : TEN_MINUTE; - int64_t timeoutCalculated_; + int64_t timeoutForDirectlyUse_; + int64_t timeoutForNotifySeen_; + int64_t timeoutForSystemInteraction_; + int64_t timeoutCalculated_ = 0; sptr sptrBundleMgr_; bool calculationTimeOut(const std::shared_ptr& oneBundleHistory, const int64_t bootBasedTimeStamp); int GetNewGroup(const std::string& bundleName, const int userId, const int64_t bootBasedTimeStamp); }; -} -} +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_GROUP_CONTROLLER_H -#endif \ No newline at end of file diff --git a/services/packagegroup/include/bundle_active_group_handler.h b/services/packagegroup/include/bundle_active_group_handler.h index f498c65773227982a51b42a1ec4e026f89079212..cea2d1764b7172d3cf3dd81da3a886cbe6c0c84b 100644 --- a/services/packagegroup/include/bundle_active_group_handler.h +++ b/services/packagegroup/include/bundle_active_group_handler.h @@ -31,12 +31,12 @@ public: int userId_; BundleActiveGroupHandlerObject(); BundleActiveGroupHandlerObject(const BundleActiveGroupHandlerObject& orig); - ~BundleActiveGroupHandlerObject() {}; + ~BundleActiveGroupHandlerObject() {} }; class BundleActiveGroupHandler : public AppExecFwk::EventHandler { public: - explicit BundleActiveGroupHandler(const std::shared_ptr &runner); + explicit BundleActiveGroupHandler(const std::shared_ptr &runner, const bool debug); ~BundleActiveGroupHandler() = default; /** * Process the event. Developers should override this method. @@ -48,11 +48,12 @@ public: static const int MSG_CHECK_BUNDLE_STATE = 0; static const int MSG_ONE_TIME_CHECK_BUNDLE_STATE = 1; static const int MSG_CHECK_IDLE_STATE = 2; - static const int CHECK_IDLE_INTERVAL = ONE_MINUTE; + int64_t checkIdleInterval_; private: std::shared_ptr bundleActiveGroupController_; }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_GROUP_HANDLER_H + diff --git a/services/packagegroup/include/bundle_active_package_history.h b/services/packagegroup/include/bundle_active_package_history.h index ff25c7ab9e91bb052944f4f20fb0952802229060..3a1af0d34853e167e064e2867bf1fb52755453a1 100644 --- a/services/packagegroup/include/bundle_active_package_history.h +++ b/services/packagegroup/include/bundle_active_package_history.h @@ -30,9 +30,11 @@ public: uint32_t reasonInGroup_; int64_t bundleAliveTimeoutTimeStamp_; int64_t bundleDailyTimeoutTimeStamp_; + bool isChanged_; BundleActivePackageHistory(); - ~BundleActivePackageHistory() {}; + ~BundleActivePackageHistory() {} }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_USAGE_HISTORY_H + diff --git a/services/packagegroup/include/bundle_active_user_history.h b/services/packagegroup/include/bundle_active_user_history.h index 5449c0f6f77133e4b77f4bace27a66f995744788..4b9e3c3aad24700968e4da1f5521b813375acf7f 100644 --- a/services/packagegroup/include/bundle_active_user_history.h +++ b/services/packagegroup/include/bundle_active_user_history.h @@ -52,7 +52,7 @@ public: void SetBundleGroup(const std::string& bundleName, const int userId, const int64_t bootBasedTimeStamp, int newGroup, uint32_t groupReason, const bool& resetTimeout); int GetLevelIndex(const std::string& bundleName, const int userId, const int64_t bootBasedTimeStamp, - const int64_t screenTimeLevel[4], const int64_t bootFromTimeLevel[4]); + const std::vector screenTimeLeve, const std::vector bootFromTimeLevel); void WriteDeviceDuration(); void WriteBundleUsage(const int userId); void printdata(int userId); @@ -61,6 +61,7 @@ public: private: bool isScreenOn_; }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_USER_HISTORY_H + diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index f89d4bf08a94e3bfd1a4e55ec13d40f18c4b9515..e11ec5d80bd19e7b4cb6dfe5717bf7364818b7b2 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -29,6 +29,17 @@ BundleActiveGroupHandlerObject::BundleActiveGroupHandlerObject() userId_ = -1; } + +BundleActiveGroupController::BundleActiveGroupController(const bool debug) +{ + timeoutForDirectlyUse_ = debug ? THREE_MINUTE : ONE_HOUR; + timeoutForNotifySeen_ = debug ? ONE_MINUTE : TWELVE_HOUR; + timeoutForSystemInteraction_ = debug ? ONE_MINUTE : TEN_MINUTE; + screenTimeLevel_ = {0, 0, debug ? TWO_MINUTE : ONE_HOUR, debug ? FOUR_MINUTE : TWO_HOUR}; + bootTimeLevel_ = {0, debug ? TWO_MINUTE : TWELVE_HOUR, debug ? FOUR_MINUTE : TWENTY_FOUR_HOUR, + debug ? SIXTEEN_MINUTE : FOURTY_EIGHT_HOUR}; +} + void BundleActiveGroupController::RestoreDurationToDatabase() { std::lock_guard lock(mutex_); @@ -45,6 +56,21 @@ void BundleActiveGroupController::OnUserRemoved(const int userId) { std::lock_guard lock(mutex_); bundleUserHistory_->userHistory_.erase(userId); + if (!activeGroupHandler_.expired()) { + activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE); + } +} + +void BundleActiveGroupController::OnUserSwitched(const int userId, const int currentUsedUser) +{ + BUNDLE_ACTIVE_LOGI("last time check for user %{public}d", currentUsedUser); + CheckEachBundleState(currentUsedUser); + bundleUserHistory_->WriteBundleUsage(currentUsedUser); + std::lock_guard lock(mutex_); + if (!activeGroupHandler_.expired()) { + activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE); + } + PeriodCheckBundleState(userId); } void BundleActiveGroupController::OnScreenChanged(const bool& isScreenOn, const int64_t bootFromTimeStamp) @@ -146,8 +172,8 @@ void BundleActiveGroupController::CheckIdleStatsOneTime() int BundleActiveGroupController::GetNewGroup(const std::string& bundleName, const int userId, const int64_t bootBasedTimeStamp) { - int groupIndex = bundleUserHistory_->GetLevelIndex(bundleName, userId, bootBasedTimeStamp, SCREEN_TIME_LEVEL, - BOOT_TIME_LEVEL); + int groupIndex = bundleUserHistory_->GetLevelIndex(bundleName, userId, bootBasedTimeStamp, screenTimeLevel_, + bootTimeLevel_); if (groupIndex < 0) { return -1; } @@ -209,7 +235,7 @@ void BundleActiveGroupController::ReportEvent(const BundleActiveEvent& event, co return; } int64_t timeUntilNextCheck; - int eventReason = EventToGroupReason(eventId); + uint32_t eventReason = EventToGroupReason(eventId); switch (eventId) { case BundleActiveEvent::NOTIFICATION_SEEN: bundleUserHistory_->ReportUsage(bundleUsageHistory, event.bundleName_, ACTIVE_GROUP_DAILY, @@ -265,17 +291,20 @@ void BundleActiveGroupController::CheckAndUpdateGroup(const std::string& bundleN groupReason = GROUP_CONTROL_REASON_TIMEOUT; } int64_t bootBasedTimeStampAdjusted = bundleUserHistory_->GetBootBasedTimeStamp(bootBasedTimeStamp); + bool notTimeout = false; if (newGroup >= ACTIVE_GROUP_ALIVE && oneBundleHistory->bundleAliveTimeoutTimeStamp_ > bootBasedTimeStampAdjusted) { newGroup = ACTIVE_GROUP_ALIVE; groupReason = oneBundleHistory->reasonInGroup_; + groupReason = GROUP_CONTROL_REASON_USAGE | GROUP_EVENT_REASON_ALIVE_NOT_TIMEOUT; + notTimeout = true; } else if (newGroup >= ACTIVE_GROUP_DAILY && oneBundleHistory->bundleDailyTimeoutTimeStamp_ > bootBasedTimeStampAdjusted) { newGroup = ACTIVE_GROUP_DAILY; - groupReason = (newGroup == oldGroup) ? oneBundleHistory->reasonInGroup_ : GROUP_CONTROL_REASON_USAGE | - GROUP_EVENT_REASON_ALIVE_TIMEOUT; + groupReason = GROUP_CONTROL_REASON_USAGE | GROUP_EVENT_REASON_ALIVE_TIMEOUT; + notTimeout = true; } - if (oldGroup < newGroup) { + if (oldGroup < newGroup || notTimeout) { BUNDLE_ACTIVE_LOGI("CheckAndUpdateGroup called SetBundleGroup"); bundleUserHistory_->SetBundleGroup(bundleName, userId, bootBasedTimeStamp, newGroup, groupReason, false); } @@ -362,9 +391,10 @@ bool BundleActiveGroupController::IsBundleInstalled(const std::string& bundleNam return true; } -void BundleActiveGroupController::ShutDown(const int64_t bootBasedTimeStamp) +void BundleActiveGroupController::ShutDown(const int64_t bootBasedTimeStamp, const int userId) { BUNDLE_ACTIVE_LOGI("ShutDown called"); + CheckEachBundleState(userId); bundleUserHistory_->UpdateBootBasedAndScreenTime(false, bootBasedTimeStamp, true); } @@ -374,5 +404,6 @@ bool BundleActiveGroupController::IsScreenOn() BUNDLE_ACTIVE_LOGI("IsScreenOn() is %{public}d", result); return result; } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/packagegroup/src/bundle_active_group_handler.cpp b/services/packagegroup/src/bundle_active_group_handler.cpp index ff45231868fdf2db32b783bbc47f0aaf3623e08a..b6040242eb8eb95395d78f5c64fafb6f4e1053d0 100644 --- a/services/packagegroup/src/bundle_active_group_handler.cpp +++ b/services/packagegroup/src/bundle_active_group_handler.cpp @@ -27,8 +27,13 @@ BundleActiveGroupHandlerObject::BundleActiveGroupHandlerObject(const BundleActiv } BundleActiveGroupHandler::BundleActiveGroupHandler - (const std::shared_ptr &runner) : AppExecFwk::EventHandler(runner) + (const std::shared_ptr &runner, const bool debug) : AppExecFwk::EventHandler(runner) { + if (debug) { + checkIdleInterval_ = ONE_MINUTE; + } else { + checkIdleInterval_ = THREE_HOUR; + } } void BundleActiveGroupHandler::Init(const std::shared_ptr& bundleActiveController) @@ -36,12 +41,16 @@ void BundleActiveGroupHandler::Init(const std::shared_ptrGetInnerEventId()) { case MSG_CHECK_BUNDLE_STATE: { auto ptrToHandlerobj = event->GetSharedObject(); @@ -54,19 +63,17 @@ void BundleActiveGroupHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointe break; } case MSG_ONE_TIME_CHECK_BUNDLE_STATE: { - std::vector osAccountInfos; - OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); - if (ret != ERR_OK) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::GetAllActiveUser failed"); + std::vector activatedOsAccountIds; + if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(activatedOsAccountIds) != ERR_OK) { + BUNDLE_ACTIVE_LOGI("query activated account failed"); return; } - if (osAccountInfos.size() == 0) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::GetAllActiveUser size is 0"); + if (activatedOsAccountIds.size() == 0) { return; } - for (uint32_t i = 0; i < osAccountInfos.size(); i++) { - bundleActiveGroupController_->CheckEachBundleState(osAccountInfos[i].GetLocalId()); - bundleActiveGroupController_->RestoreToDatabase(osAccountInfos[i].GetLocalId()); + for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) { + bundleActiveGroupController_->CheckEachBundleState(activatedOsAccountIds[i]); + bundleActiveGroupController_->RestoreToDatabase(activatedOsAccountIds[i]); } RemoveEvent(MSG_ONE_TIME_CHECK_BUNDLE_STATE); break; @@ -83,7 +90,7 @@ void BundleActiveGroupHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointe auto handlerEvent = AppExecFwk::InnerEvent::Get(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE, handlerobjToPtr); bundleActiveGroupController_->RestoreToDatabase(GroupHandlerObj.userId_); - SendEvent(handlerEvent, CHECK_IDLE_INTERVAL); + SendEvent(handlerEvent, checkIdleInterval_); } break; } @@ -92,5 +99,6 @@ void BundleActiveGroupHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointe } } } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/packagegroup/src/bundle_active_user_history.cpp b/services/packagegroup/src/bundle_active_user_history.cpp index 5179f8fec2590dc021ce82c4e28b6f5572643ddf..b06c8bc6c608b3f81c18e0c00a56c6ad10a1eabf 100644 --- a/services/packagegroup/src/bundle_active_user_history.cpp +++ b/services/packagegroup/src/bundle_active_user_history.cpp @@ -31,6 +31,8 @@ BundleActivePackageHistory::BundleActivePackageHistory() reasonInGroup_ = DeviceUsageStatsGroupConst::GROUP_CONTROL_REASON_DEFAULT; bundleAliveTimeoutTimeStamp_ = 0; bundleDailyTimeoutTimeStamp_ = 0; + lastCalculatedGroup_ = ACTIVE_GROUP_NEVER; + isChanged_ = false; }; void BundleActiveUserHistory::WriteDeviceDuration() @@ -61,7 +63,8 @@ BundleActiveUserHistory::BundleActiveUserHistory(const int64_t bootBasedTimeStam } int BundleActiveUserHistory::GetLevelIndex(const string& bundleName, const int userId, - const int64_t bootBasedTimeStamp, const int64_t screenTimeLevel[4], const int64_t bootFromTimeLevel[4]) + const int64_t bootBasedTimeStamp, const std::vector screenTimeLevel, + const std::vector bootFromTimeLevel) { auto oneUserHistory = GetUserHistory(userId, false); if (oneUserHistory == nullptr) { @@ -177,6 +180,7 @@ void BundleActiveUserHistory::ReportUsage(shared_ptr oneBundleUsageHistory->currentGroup_ = newGroup; } oneBundleUsageHistory->reasonInGroup_ = GROUP_CONTROL_REASON_USAGE | groupReason; + oneBundleUsageHistory->isChanged_ = true; } void BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int userId, @@ -194,6 +198,10 @@ void BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int if (oneBundleHistory == nullptr) { return; } + if (oneBundleHistory->currentGroup_ == newGroup || oneBundleHistory->reasonInGroup_ == groupReason) { + BUNDLE_ACTIVE_LOGI("%{public}s group and reason is same as before, not update", bundleName.c_str()); + return; + } oneBundleHistory->currentGroup_ = newGroup; oneBundleHistory->reasonInGroup_ = groupReason; int64_t setTimeStamp = GetBootBasedTimeStamp(bootBasedTimeStamp); @@ -201,6 +209,7 @@ void BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int oneBundleHistory->bundleAliveTimeoutTimeStamp_ = setTimeStamp; oneBundleHistory->bundleDailyTimeoutTimeStamp_ = setTimeStamp; } + oneBundleHistory->isChanged_ = true; } void BundleActiveUserHistory::UpdateBootBasedAndScreenTime(const bool& isScreenOn, const int64_t bootBasedTimeStamp, @@ -236,5 +245,6 @@ void BundleActiveUserHistory::printdata(int userId) oneBundleUsage.second->bundleDailyTimeoutTimeStamp_, oneBundleUsage.second->bundleAliveTimeoutTimeStamp_); } } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/packageusage/include/bundle_active_calendar.h b/services/packageusage/include/bundle_active_calendar.h index 2e7a2f4e57d002bcb980e07a1d497afc0df07654..4bde454babe42e332a0710d7a196bc20ecc810be 100644 --- a/services/packageusage/include/bundle_active_calendar.h +++ b/services/packageusage/include/bundle_active_calendar.h @@ -18,20 +18,27 @@ #include +#include "bundle_active_constant.h" + namespace OHOS { namespace DeviceUsageStats { class BundleActiveCalendar { public: static const int64_t ONE_SECOND_MILLISECONDS = 1000; - static const int64_t DAY_MILLISECONDS = (int64_t)1 * 1 * 10 * 60 * 1000; - static const int64_t WEEK_MILLISECONDS = (int64_t)1 * 1 * 20 * 60 * 1000; - static const int64_t MONTH_MILLISECONDS = (int64_t)1 * 1 * 30 * 60 * 1000; - static const int64_t YEAR_MILLISECONDS = (int64_t)1 * 1 * 40 * 60 * 1000; + int64_t dayMilliseconds_; + int64_t weekMilliseconds_; + int64_t monthMilliseconds_; + int64_t yearMilliseconds_; BundleActiveCalendar(const int64_t timeStamp); BundleActiveCalendar() { time_ = 0; + dayMilliseconds_ = ONE_DAY_TIME; + weekMilliseconds_ = ONE_WEEK_TIME; + monthMilliseconds_ = ONE_MONTH_TIME; + yearMilliseconds_ = ONE_YEAR_TIME; } + void ChangeToDebug(); void TruncateToDay(); void TruncateToWeek(); void TruncateToMonth(); @@ -47,6 +54,7 @@ public: private: int64_t time_; }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_CALENDER_H + diff --git a/services/packageusage/include/bundle_active_event.h b/services/packageusage/include/bundle_active_event.h index 4e66b230df12a8d0f2fafab7375dae3fdd46bcd7..dc26307bc7d5f3ab602bfeadbc5dc80485cebe58 100644 --- a/services/packageusage/include/bundle_active_event.h +++ b/services/packageusage/include/bundle_active_event.h @@ -60,6 +60,7 @@ public: virtual bool Marshalling(Parcel &parcel) const override; std::shared_ptr Unmarshalling(Parcel &parcel); }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_EVENT_H + diff --git a/services/packageusage/include/bundle_active_event_list.h b/services/packageusage/include/bundle_active_event_list.h index 7fff6f6270d39924509f0b45da264b3729329152..4a0a02dcfe4f4a3eded5a507939b4988dd67d038 100644 --- a/services/packageusage/include/bundle_active_event_list.h +++ b/services/packageusage/include/bundle_active_event_list.h @@ -24,7 +24,7 @@ namespace DeviceUsageStats { class BundleActiveEventList { public: BundleActiveEventList(); - ~BundleActiveEventList() {}; + ~BundleActiveEventList() {} int Size(); void Clear(); void Insert(BundleActiveEvent event); @@ -32,6 +32,7 @@ public: void Merge(const BundleActiveEventList& right); std::vector events_; }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_EVENT_LIST_H + diff --git a/services/packageusage/include/bundle_active_event_stats.h b/services/packageusage/include/bundle_active_event_stats.h index 77d9e2daaf32fa49342bfac0f33717572cecae3a..b15af31f9f7c9c6d35b943ea6f6f3b43a4494b2d 100644 --- a/services/packageusage/include/bundle_active_event_stats.h +++ b/services/packageusage/include/bundle_active_event_stats.h @@ -38,6 +38,7 @@ public: int GetCount(); void add(const BundleActiveEventStats& right); }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_EVENT_STATS_H + diff --git a/services/packageusage/include/bundle_active_event_tracker.h b/services/packageusage/include/bundle_active_event_tracker.h index 26d13a070c562a332eef2650973026ad186ba9b3..7e8757b08b4bcbd13c0737c3dd3f43e3d0c137bb 100644 --- a/services/packageusage/include/bundle_active_event_tracker.h +++ b/services/packageusage/include/bundle_active_event_tracker.h @@ -33,6 +33,7 @@ public: int64_t endTime); BundleActiveEventTracker(); }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_EVENT_TRACKER_H + diff --git a/services/packageusage/include/bundle_active_package_stats.h b/services/packageusage/include/bundle_active_package_stats.h index 6fe6926985a1558c1a7ce79d5828a8ab55d1a089..6e648a8d915b2a923049928730751bac0d7e3825 100644 --- a/services/packageusage/include/bundle_active_package_stats.h +++ b/services/packageusage/include/bundle_active_package_stats.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BUNDLE_ACTIVE_USAGE_STATS_H -#define BUNDLE_ACTIVE_USAGE_STATS_H +#ifndef BUNDLE_ACTIVE_PACKAGE_STATS_H +#define BUNDLE_ACTIVE_PACKAGE_STATS_H #include "ibundle_active_service.h" #include "bundle_active_event.h" @@ -35,10 +35,10 @@ public: int lastEvent_; // key is abilityId, value is the last event of this ability. Restore all abilities' last event of bundle. std::map abilities_; - // key is name of continous task, value is last event of this last continous task. + // key is name of continuous task, value is last event of this last continuous task. std::map longTimeTasks_; BundleActivePackageStats(); - ~BundleActivePackageStats() {}; + ~BundleActivePackageStats() {} BundleActivePackageStats(const BundleActivePackageStats& orig); std::string GetBundleName(); int64_t GetBeginTimeStamp(); @@ -64,6 +64,7 @@ private: void UpdateAbility(const int64_t timeStamp, const int eventId, const std::string& abilityId); void UpdateLongTimeTask(const std::string& longTimeTaskName, const int64_t timeStamp, const int eventId); }; -} -} -#endif +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_PACKAGE_STATS_H + diff --git a/services/packageusage/include/bundle_active_period_stats.h b/services/packageusage/include/bundle_active_period_stats.h index 1c7106161a07b2686bbe5b34a54ce1fa60de0c44..3a7a31781da04611fb95bc50e4ec7075b2c7b47e 100644 --- a/services/packageusage/include/bundle_active_period_stats.h +++ b/services/packageusage/include/bundle_active_period_stats.h @@ -60,6 +60,7 @@ public: void AddEventStatsTo(std::vector& eventStatsList); std::string GetCachedString(std::string str); }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_PERIOD_STATS_H + diff --git a/services/packageusage/include/bundle_active_report_handler.h b/services/packageusage/include/bundle_active_report_handler.h index bc9ea44107018c56147b28fc1a0706073fd5393a..dd44984378683db0ce4225cc5818d4ef6c705652 100644 --- a/services/packageusage/include/bundle_active_report_handler.h +++ b/services/packageusage/include/bundle_active_report_handler.h @@ -36,15 +36,15 @@ public: void ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) override; void Init(const std::shared_ptr& bundleActiveCore); static const int MSG_REPORT_EVENT = 0; - static const int MSG_REPORT_EVENT_TO_ALL_USER = 1; - static const int MSG_FLUSH_TO_DISK = 2; - static const int MSG_REMOVE_USER = 3; - static const int MSG_DEVICE_SHUTDOWN = 4; - static const int MSG_BUNDLE_UNINSTALLED = 5; + static const int MSG_FLUSH_TO_DISK = 1; + static const int MSG_REMOVE_USER = 2; + static const int MSG_BUNDLE_UNINSTALLED = 3; + static const int MSG_SWITCH_USER = 4; private: std::shared_ptr bundleActiveCore_; }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_REPORT_HANDLER_H + diff --git a/services/packageusage/include/bundle_active_stats_combiner.h b/services/packageusage/include/bundle_active_stats_combiner.h index 710abc52a0db6736dbfb1fb4ca4ebf3d0e6bd3d8..1299cb01cc900c53646e75a2250d6d50d692f55a 100644 --- a/services/packageusage/include/bundle_active_stats_combiner.h +++ b/services/packageusage/include/bundle_active_stats_combiner.h @@ -40,6 +40,7 @@ public: void combine(const std::shared_ptr& stats, std::vector& accumulatedResult, int64_t beginTime = 0); }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_STATS_COMBINER_H + diff --git a/services/packageusage/include/bundle_active_stats_update_listener.h b/services/packageusage/include/bundle_active_stats_update_listener.h index 6968b6cec6be60fe586a735c89c9d913e93d2365..b5de8d2382a30cf3666b1d5dd9e2b26211594ddb 100644 --- a/services/packageusage/include/bundle_active_stats_update_listener.h +++ b/services/packageusage/include/bundle_active_stats_update_listener.h @@ -23,6 +23,7 @@ class BundleActiveStatsUpdateListener { virtual void OnStatsReload() = 0; virtual void OnSystemUpdate(int userId) = 0; }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_STATS_UPDATE_LISTENER_H + diff --git a/services/packageusage/include/bundle_active_user_service.h b/services/packageusage/include/bundle_active_user_service.h index 6aa13e79464ec01e237502bc8d9580eb69d15800..dffb022dc029faa403c1d9824f1961268b9f4826 100644 --- a/services/packageusage/include/bundle_active_user_service.h +++ b/services/packageusage/include/bundle_active_user_service.h @@ -25,6 +25,7 @@ #include "bundle_active_calendar.h" #include "bundle_active_stats_combiner.h" #include "bundle_active_usage_database.h" +#include "bundle_active_constant.h" namespace OHOS { namespace DeviceUsageStats { @@ -33,7 +34,7 @@ class BundleActiveCore; class BundleActiveUserService { public: BundleActiveUserService() = delete; - BundleActiveUserService(const int userId, BundleActiveCore& listener):listener_(listener) + BundleActiveUserService(const int userId, BundleActiveCore& listener, const bool debug):listener_(listener) { for (int i = 0; i < BundleActivePeriodStats::PERIOD_COUNT; i++) { currentStats_.push_back(nullptr); @@ -41,9 +42,18 @@ public: userId_ = userId; dailyExpiryDate_.SetMilliseconds(0); statsChanged_ = false; + if (debug) { + dailyExpiryDate_.ChangeToDebug(); + database_.ChangeToDebug(); + debugUserService_ = true; + periodLength_ = {ONE_DAY_TIME_DEBUG, ONE_WEEK_TIME_DEBUG, ONE_MONTH_TIME_DEBUG, ONE_YEAR_TIME_DEBUG}; + } else { + debugUserService_ = false; + periodLength_ = {ONE_DAY_TIME, ONE_WEEK_TIME, ONE_MONTH_TIME, ONE_YEAR_TIME}; + } } void Init(const int64_t timeStamp); - ~BundleActiveUserService() {}; + ~BundleActiveUserService() {} void ReportForShutdown(const BundleActiveEvent& event); void ReportEvent(const BundleActiveEvent& event); void RestoreStats(bool forced); @@ -64,15 +74,16 @@ private: BundleActiveUsageDatabase database_; std::vector> currentStats_; bool statsChanged_; + bool debugUserService_; std::string lastBackgroundBundle_; BundleActiveCore& listener_; - inline static const std::vector PERIOD_LENGTH = {BundleActiveCalendar::DAY_MILLISECONDS, - BundleActiveCalendar::WEEK_MILLISECONDS, BundleActiveCalendar::MONTH_MILLISECONDS, - BundleActiveCalendar::YEAR_MILLISECONDS}; + std::vector periodLength_ = {0, 0, 0, 0}; void NotifyStatsChanged(); void NotifyNewUpdate(); - void printstat(); + void PrintInMemPackageStats(const int idx); + void PrintInMemEventStats(); }; -} -} -#endif \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_USER_SERVICE_H + diff --git a/services/packageusage/src/bundle_active_calendar.cpp b/services/packageusage/src/bundle_active_calendar.cpp index 1806fac73256eb392d0e423b10cebf2d451e98e3..270742ac41d59fcf3ef1258c40261f6074ea9421 100644 --- a/services/packageusage/src/bundle_active_calendar.cpp +++ b/services/packageusage/src/bundle_active_calendar.cpp @@ -21,46 +21,50 @@ namespace DeviceUsageStats { BundleActiveCalendar::BundleActiveCalendar(const int64_t timeStamp) { time_ = timeStamp; + dayMilliseconds_ = ONE_DAY_TIME; + weekMilliseconds_ = ONE_WEEK_TIME; + monthMilliseconds_ = ONE_MONTH_TIME; + yearMilliseconds_ = ONE_YEAR_TIME; } void BundleActiveCalendar::TruncateToDay() { - time_ -= time_ % DAY_MILLISECONDS; + time_ -= time_ % dayMilliseconds_; } void BundleActiveCalendar::TruncateToWeek() { - time_ -= time_ % WEEK_MILLISECONDS; + time_ -= time_ % weekMilliseconds_; } void BundleActiveCalendar::TruncateToMonth() { - time_ -= time_ % MONTH_MILLISECONDS; + time_ -= time_ % monthMilliseconds_; } void BundleActiveCalendar::TruncateToYear() { - time_ -= time_ % YEAR_MILLISECONDS; + time_ -= time_ % yearMilliseconds_; } void BundleActiveCalendar::IncreaseDays(const int val) { - time_ += val * DAY_MILLISECONDS; + time_ += val * dayMilliseconds_; } void BundleActiveCalendar::IncreaseWeeks(const int val) { - time_ += val* WEEK_MILLISECONDS; + time_ += val* weekMilliseconds_; } void BundleActiveCalendar::IncreaseMonths(const int val) { - time_ += val * MONTH_MILLISECONDS; + time_ += val * monthMilliseconds_; } void BundleActiveCalendar::IncreaseYears(const int val) { - time_ += val * YEAR_MILLISECONDS; + time_ += val * yearMilliseconds_; } void BundleActiveCalendar::SetMilliseconds(const int64_t timeStamp) @@ -73,6 +77,14 @@ int64_t BundleActiveCalendar::GetMilliseconds() return time_; } +void BundleActiveCalendar::ChangeToDebug() +{ + dayMilliseconds_ = ONE_DAY_TIME_DEBUG; + weekMilliseconds_ = ONE_WEEK_TIME_DEBUG; + monthMilliseconds_ = ONE_MONTH_TIME_DEBUG; + yearMilliseconds_ = ONE_YEAR_TIME_DEBUG; +} + void BundleActiveCalendar::TruncateTo(int intervalType) { switch (intervalType) { @@ -92,5 +104,6 @@ void BundleActiveCalendar::TruncateTo(int intervalType) break; } } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/packageusage/src/bundle_active_event.cpp b/services/packageusage/src/bundle_active_event.cpp index bc6c81ffbf1675aaef844fe1d002d8a69f04ae93..e07abd48aea4f2a8435d6b64b938677ceb543cc5 100644 --- a/services/packageusage/src/bundle_active_event.cpp +++ b/services/packageusage/src/bundle_active_event.cpp @@ -88,5 +88,6 @@ std::shared_ptr BundleActiveEvent::Unmarshalling(Parcel &parc result->timeStamp_ = parcel.ReadInt64(); return result; } -} -} +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/packageusage/src/bundle_active_event_list.cpp b/services/packageusage/src/bundle_active_event_list.cpp index 51c081b3aa94bcdde9aaa21620948ee76b094ad3..66d47e3f79517a0c8adadf660fb7dd05b29f43a0 100644 --- a/services/packageusage/src/bundle_active_event_list.cpp +++ b/services/packageusage/src/bundle_active_event_list.cpp @@ -68,5 +68,6 @@ void BundleActiveEventList::Merge(const BundleActiveEventList& right) Insert(right.events_[i]); } } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/packageusage/src/bundle_active_event_stats.cpp b/services/packageusage/src/bundle_active_event_stats.cpp index 4dfa187ada9a155923a4604cf46893cf64c21095..988c09b8d2224bd91e35b144e4812991335b5a1c 100644 --- a/services/packageusage/src/bundle_active_event_stats.cpp +++ b/services/packageusage/src/bundle_active_event_stats.cpp @@ -19,6 +19,7 @@ namespace OHOS { namespace DeviceUsageStats { BundleActiveEventStats::BundleActiveEventStats() { + eventId_ = 0; beginTimeStamp_ = 0; endTimeStamp_ = 0; lastEventTime_ = 0; @@ -80,5 +81,6 @@ void BundleActiveEventStats::add(const BundleActiveEventStats& right) totalTime_ += right.totalTime_; count_ += right.count_; } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/packageusage/src/bundle_active_event_tracker.cpp b/services/packageusage/src/bundle_active_event_tracker.cpp index caea54dd95861f0c6cab241d415119f6950f993d..a1165bde860384f646275f874427bc80a58bfe00 100644 --- a/services/packageusage/src/bundle_active_event_tracker.cpp +++ b/services/packageusage/src/bundle_active_event_tracker.cpp @@ -57,5 +57,6 @@ void BundleActiveEventTracker::AddToEventStats(std::vector BundleActivePackageStats::Unmarshallin result->totalContiniousTaskUsedTime_ = parcel.ReadInt64(); return result; } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/packageusage/src/bundle_active_period_stats.cpp b/services/packageusage/src/bundle_active_period_stats.cpp index e9f0b71438341d108b880aa82ee92f659dea36fc..22f1eee996a80312e477313e1c8d76a8ecbcd176 100644 --- a/services/packageusage/src/bundle_active_period_stats.cpp +++ b/services/packageusage/src/bundle_active_period_stats.cpp @@ -137,5 +137,6 @@ std::string BundleActivePeriodStats::GetCachedString(std::string str) } return *it; } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/packageusage/src/bundle_active_report_handler.cpp b/services/packageusage/src/bundle_active_report_handler.cpp index d02a40d18cdee7cbb6443cd1c4810529c6789aa5..40b90fceff958950b93e7304a1e1f93db814fea5 100644 --- a/services/packageusage/src/bundle_active_report_handler.cpp +++ b/services/packageusage/src/bundle_active_report_handler.cpp @@ -42,16 +42,16 @@ void BundleActiveReportHandler::ProcessEvent(const AppExecFwk::InnerEvent::Point bundleActiveCore_->ReportEvent(tmpHandlerobj.event_, tmpHandlerobj.userId_); break; } - case MSG_REPORT_EVENT_TO_ALL_USER: { - auto ptrToHandlerobj = event->GetSharedObject(); - BundleActiveReportHandlerObject tmpHandlerobj = *ptrToHandlerobj; - bundleActiveCore_->ReportEventToAllUserId(tmpHandlerobj.event_); - break; - } case MSG_FLUSH_TO_DISK: { BUNDLE_ACTIVE_LOGI("FLUSH TO DISK HANDLE"); auto ptrToHandlerobj = event->GetSharedObject(); BundleActiveReportHandlerObject tmpHandlerobj = *ptrToHandlerobj; + if (tmpHandlerobj.userId_ != bundleActiveCore_->currentUsedUser_) { + BUNDLE_ACTIVE_LOGE("flush user is %{public}d, not last user %{public}d, return", + tmpHandlerobj.userId_, bundleActiveCore_->currentUsedUser_); + RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK, tmpHandlerobj.userId_); + return; + } bundleActiveCore_->RestoreToDatabase(tmpHandlerobj.userId_); break; } @@ -61,10 +61,6 @@ void BundleActiveReportHandler::ProcessEvent(const AppExecFwk::InnerEvent::Point bundleActiveCore_->OnUserRemoved(tmpHandlerobj.userId_); break; } - case MSG_DEVICE_SHUTDOWN: { - bundleActiveCore_->ShutDown(); - break; - } case MSG_BUNDLE_UNINSTALLED: { BUNDLE_ACTIVE_LOGI("MSG_BUNDLE_UNINSTALLED CALLED"); auto ptrToHandlerobj = event->GetSharedObject(); @@ -72,10 +68,17 @@ void BundleActiveReportHandler::ProcessEvent(const AppExecFwk::InnerEvent::Point bundleActiveCore_->OnBundleUninstalled(tmpHandlerobj.userId_, tmpHandlerobj.bundleName_); break; } + case MSG_SWITCH_USER: { + BUNDLE_ACTIVE_LOGI("MSG_SWITCH_USER CALLED"); + auto ptrToHandlerobj = event->GetSharedObject(); + BundleActiveReportHandlerObject tmpHandlerobj = *ptrToHandlerobj; + bundleActiveCore_->OnUserSwitched(tmpHandlerobj.userId_); + } default: { break; } } } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/packageusage/src/bundle_active_stats_combiner.cpp b/services/packageusage/src/bundle_active_stats_combiner.cpp index 4e63f90e1c87a6937cef850ca976d091f16d0f71..e704baf139326ad81eed4c0c48cee2adb8db1e8a 100644 --- a/services/packageusage/src/bundle_active_stats_combiner.cpp +++ b/services/packageusage/src/bundle_active_stats_combiner.cpp @@ -40,5 +40,6 @@ void BundleActiveStatsCombiner::combine(const std::shared_ptr accumulatedResult.push_back(stats->events_.events_[i]); } } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index 4686d761c353be675076c5f65eec21066476da10..cf60faeeaaf7eefb3a026a304957327379756f82 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -71,6 +71,7 @@ void BundleActiveUserService::RenewTableTime(int64_t oldTime, int64_t newTime) void BundleActiveUserService::NotifyStatsChanged() { + BUNDLE_ACTIVE_LOGI("NotifyStatsChanged stat change is %{public}d, user is %{public}d", statsChanged_, userId_); if (!statsChanged_) { BUNDLE_ACTIVE_LOGI("NotifyStatsChanged() set stats changed to true"); statsChanged_ = true; @@ -85,8 +86,9 @@ void BundleActiveUserService::NotifyNewUpdate() void BundleActiveUserService::ReportEvent(const BundleActiveEvent& event) { - BUNDLE_ACTIVE_LOGI("ReportEvent, B time is %{public}lld, E time is %{public}lld", - currentStats_[0]->beginTime_, dailyExpiryDate_.GetMilliseconds()); + BUNDLE_ACTIVE_LOGI("ReportEvent, B time is %{public}lld, E time is %{public}lld, userId is %{public}d," + "event is %{public}d", + currentStats_[0]->beginTime_, dailyExpiryDate_.GetMilliseconds(), userId_, event.eventId_); if (event.timeStamp_ >= dailyExpiryDate_.GetMilliseconds()) { BUNDLE_ACTIVE_LOGI("ReportEvent later than daily expire, renew data in memory"); RenewStatsInMemory(event.timeStamp_); @@ -131,7 +133,9 @@ void BundleActiveUserService::ReportEvent(const BundleActiveEvent& event) break; } } - NotifyStatsChanged(); + if (event.eventId_ != BundleActiveEvent::FLUSH) { + NotifyStatsChanged(); + } } void BundleActiveUserService::ReportForShutdown(const BundleActiveEvent& event) @@ -161,16 +165,16 @@ void BundleActiveUserService::RestoreStats(bool forced) if (statsChanged_ || forced) { BUNDLE_ACTIVE_LOGI("RestoreStats() stat changed is true"); for (uint32_t i = 0; i < currentStats_.size(); i++) { - if (currentStats_[i] != nullptr) { + if (currentStats_[i]) { + if (currentStats_[i]->bundleStats_.empty() && currentStats_[i]->events_.events_.empty()) { + continue; + } database_.UpdateUsageData(i, *(currentStats_[i])); } - if (i == 0) { - BUNDLE_ACTIVE_LOGI("RESOTRE EVENT SIZE IS %{public}d, USER ID IS %{public}d", - currentStats_[i]->events_.Size(), userId_); - } } currentStats_[BundleActivePeriodStats::PERIOD_DAILY]->events_.Clear(); statsChanged_ = false; + BUNDLE_ACTIVE_LOGI("change statsChanged_ to %{public}d user is %{public}d", statsChanged_, userId_); } } @@ -178,9 +182,12 @@ void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const boo { BUNDLE_ACTIVE_LOGI("LoadActiveStats called"); BundleActiveCalendar tmpCalendar(0); + if (debugUserService_ == true) { + tmpCalendar.ChangeToDebug(); + } tmpCalendar.SetMilliseconds(timeStamp); tmpCalendar.TruncateTo(BundleActivePeriodStats::PERIOD_DAILY); - for (uint32_t intervalType = 0; intervalType < PERIOD_LENGTH.size(); intervalType++) { + for (uint32_t intervalType = 0; intervalType < periodLength_.size(); intervalType++) { if (!force && currentStats_[intervalType] != nullptr && currentStats_[intervalType]->beginTime_ == tmpCalendar.GetMilliseconds()) { continue; @@ -193,8 +200,8 @@ void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const boo // 如果当前时间在stats的统计时间范围内,则可以从数据库加载数据 BUNDLE_ACTIVE_LOGI("interval type is %{public}d, database stat BEGIN time is %{public}lld, " "timestamp is %{public}lld, expect end is %{public}lld", - intervalType, stats->beginTime_, timeStamp, stats->beginTime_ + PERIOD_LENGTH[intervalType]); - if (timeStamp > stats->beginTime_ && timeStamp < stats->beginTime_ + PERIOD_LENGTH[intervalType]) { + intervalType, stats->beginTime_, timeStamp, stats->beginTime_ + periodLength_[intervalType]); + if (timeStamp > stats->beginTime_ && timeStamp < stats->beginTime_ + periodLength_[intervalType]) { currentStats_[intervalType] = stats; } } @@ -234,6 +241,9 @@ void BundleActiveUserService::RenewStatsInMemory(const int64_t timeStamp) continue; } for (auto bundleUsageStatsPair : (*it)->bundleStats_) { + if (bundleUsageStatsPair.second == nullptr) { + continue; + } BundleActivePackageStats bundleUsageStats(*(bundleUsageStatsPair.second)); if (!bundleUsageStats.abilities_.empty()) { continueAbilities[bundleUsageStats.bundleName_] = bundleUsageStats.abilities_; @@ -241,8 +251,6 @@ void BundleActiveUserService::RenewStatsInMemory(const int64_t timeStamp) if (!bundleUsageStats.longTimeTasks_.empty()) { continueServices[bundleUsageStats.bundleName_] = bundleUsageStats.longTimeTasks_; } - if (*it == nullptr) { - } (*it)->Update(bundleUsageStats.bundleName_, "", dailyExpiryDate_.GetMilliseconds() - 1, BundleActiveEvent::END_OF_THE_DAY, ""); @@ -261,6 +269,9 @@ void BundleActiveUserService::RenewStatsInMemory(const int64_t timeStamp) if (continueAbilities.find(continueBundleName) != continueAbilities.end()) { for (std::map::iterator it = continueAbilities[continueBundleName].begin(); it != continueAbilities[continueBundleName].end(); it++) { + if (it->second == BundleActiveEvent::ABILITY_BACKGROUND) { + continue; + } (*itInterval)->Update(continueBundleName, "", beginTime, it->second, it->first); } } @@ -294,7 +305,7 @@ std::vector BundleActiveUserService::QueryPackageStats return result; } if (currentStats->endTime_ == 0) { - if (beginTime > currentStats->beginTime_ + PERIOD_LENGTH[intervalType]) { + if (beginTime > currentStats->beginTime_ + periodLength_[intervalType]) { return result; } else { result = database_.QueryDatabaseUsageStats(intervalType, beginTime, endTime, userId); @@ -304,7 +315,12 @@ std::vector BundleActiveUserService::QueryPackageStats return result; } int64_t truncatedEndTime = std::min(currentStats->beginTime_, endTime); + BUNDLE_ACTIVE_LOGI("Query package data in db from %{public}lld to %{public}lld, current begin %{public}lld", + beginTime, truncatedEndTime, currentStats->beginTime_); result = database_.QueryDatabaseUsageStats(intervalType, beginTime, truncatedEndTime, userId); + BUNDLE_ACTIVE_LOGI("Query package data in db result size is %{public}d", + static_cast(result.size())); + PrintInMemPackageStats(intervalType); // if we need a in-memory stats, combine current stats with result from database. if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { BUNDLE_ACTIVE_LOGI("QueryPackageStats need in memory stats"); @@ -339,9 +355,10 @@ std::vector BundleActiveUserService::QueryEvents(const int64_ if (beginTime >= currentStats->endTime_) { return result; } - BUNDLE_ACTIVE_LOGI("QueryEvents bundle name is %{public}s", bundleName.c_str()); + BUNDLE_ACTIVE_LOGI("Query event bundle name is %{public}s", bundleName.c_str()); result = database_.QueryDatabaseEvents(beginTime, endTime, userId, bundleName); - BUNDLE_ACTIVE_LOGI("event database query size is %{public}d", result.size()); + BUNDLE_ACTIVE_LOGI("Query event data in db result size is %{public}d", result.size()); + PrintInMemEventStats(); // if we need a in-memory stats, combine current stats with result from database. if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { BUNDLE_ACTIVE_LOGI("QueryEvents need in memory stats"); @@ -358,17 +375,25 @@ std::vector BundleActiveUserService::QueryEvents(const int64_ return result; } -void BundleActiveUserService::printstat() +void BundleActiveUserService::PrintInMemPackageStats(const int idx) { - BUNDLE_ACTIVE_LOGI("printstat called"); - int idx = 0; + BUNDLE_ACTIVE_LOGI("PrintInMemPackageStats called"); for (auto it : currentStats_[idx]->bundleStats_) { - BUNDLE_ACTIVE_LOGI("bundle name is %{public}s", it.first.c_str()); - int64_t lasttimeused = it.second->lastTimeUsed_; - int64_t totalusedtime = it.second->totalInFrontTime_; - BUNDLE_ACTIVE_LOGI("event stat is, totaltime is %{public}lld, lasttimeused is %{public}lld", - totalusedtime, lasttimeused); + BUNDLE_ACTIVE_LOGI("In mem, bundle name is %{public}s", it.first.c_str()); + int64_t lastTimeUsed = it.second->lastTimeUsed_; + int64_t totalUsedTime = it.second->totalInFrontTime_; + int64_t lastTimeContinuousTaskUsed = it.second->lastContiniousTaskUsed_; + int64_t totalTimeContinuousTaskUsed = it.second->totalContiniousTaskUsedTime_; + BUNDLE_ACTIVE_LOGI("bundle stat is, totaltime is %{public}lld, lastTimeUsed is %{public}lld" + "total continuous task is %{public}lld, lastTimeContinuousTaskUsed is %{public}lld", + totalUsedTime, lastTimeUsed, totalTimeContinuousTaskUsed, lastTimeContinuousTaskUsed); } +} + +void BundleActiveUserService::PrintInMemEventStats() +{ + BUNDLE_ACTIVE_LOGI("PrintInMemEventStats called"); + int idx = 0; int size = static_cast(currentStats_[idx]->events_.events_.size()); for (int i = 0; i < size; i++) { std::string abilityId = currentStats_[idx]->events_.events_[i].abilityId_; @@ -376,10 +401,11 @@ void BundleActiveUserService::printstat() std::string bundlename = currentStats_[idx]->events_.events_[i].bundleName_; int eventid = currentStats_[idx]->events_.events_[i].eventId_; int64_t timestamp = currentStats_[idx]->events_.events_[i].timeStamp_; - BUNDLE_ACTIVE_LOGI("event stat is, abilityid is %{public}s, abilityname is %{public}s, " + BUNDLE_ACTIVE_LOGI("In mem, event stat is, abilityid is %{public}s, abilityname is %{public}s, " "bundlename is %{public}s, eventid is %{public}d, timestamp is %{public}lld", abilityId.c_str(), abilityname.c_str(), bundlename.c_str(), eventid, timestamp); } } -} -} \ No newline at end of file +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 693799dbc2f117931522c17521e5fa035e11a034..bade74218609c68293f97c8f157d7a2e9654e920 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -34,7 +34,7 @@ static std::string DEFAULT_BUNDLENAME = "com.ohos.camera"; static std::string DEFAULT_ABILITYID = "1234"; static std::string DEFAULT_ABILITYNAME = "testability"; static int DEFAULT_USERID = 0; -static int LARGE_NUM = LARGE_NUM; +static int64_t LARGE_NUM = 20000000000000; class DeviceUsageStatisticsTest : public testing::Test { public: @@ -101,7 +101,8 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_ReportEvent_001, F */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryEvents_001, Function | MediumTest | Level0) { - std::vector result = BundleActiveClient::GetInstance().QueryEvents(0, LARGE_NUM); + int32_t errCode = 0; + std::vector result = BundleActiveClient::GetInstance().QueryEvents(0, LARGE_NUM, errCode); EXPECT_EQ(result.size(), 0); } @@ -125,8 +126,9 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryCurrentEvents */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackagesStats_001, Function | MediumTest | Level0) { + int32_t errCode = 0; std::vector result = BundleActiveClient::GetInstance().QueryPackageStats(4, 0, - LARGE_NUM); + LARGE_NUM, errCode); EXPECT_EQ(result.size(), 0); } @@ -153,5 +155,6 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackageGroup_ int result = BundleActiveClient::GetInstance().QueryPackageGroup(); EXPECT_EQ(result, -1); } -} -} +} // namespace DeviceUsageStats +} // namespace OHOS +