From 9732ec4fce3644d19bba5fba22f1569efdb35374 Mon Sep 17 00:00:00 2001
From: houdisheng
Date: Mon, 28 Feb 2022 22:42:50 +0800
Subject: [PATCH 01/32] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E9=97=AE=E9=A2=98?=
=?UTF-8?q?=E4=BF=AE=E6=94=B9=EF=BC=8C=E4=BF=AE=E5=A4=8D=E9=95=BF=E6=97=B6?=
=?UTF-8?q?=E4=BB=BB=E5=8A=A1=E6=97=B6=E9=97=B4=E8=AE=B0=E5=BD=95=E9=94=99?=
=?UTF-8?q?=E8=AF=AF=E9=97=AE=E9=A2=98=EF=BC=8C=E9=95=BF=E6=97=B6=E4=BB=BB?=
=?UTF-8?q?=E5=8A=A1=E6=96=B0=E4=B8=80=E5=A4=A9=E8=BF=9B=E7=A8=8B=E5=B4=A9?=
=?UTF-8?q?=E6=BA=83=E9=97=AE=E9=A2=98=EF=BC=8Cdatabase=E5=88=86=E7=BB=84?=
=?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=88=A0=E9=99=A4=E4=B8=8D=E5=85=A8=E9=97=AE?=
=?UTF-8?q?=E9=A2=98?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Signed-off-by: houdisheng
---
.../common/src/bundle_active_app_state_obsever.cpp | 2 +-
.../src/bundle_active_continuous_task_observer.cpp | 2 +-
services/common/src/bundle_active_core.cpp | 2 ++
services/common/src/bundle_active_service.cpp | 2 +-
.../include/bundle_active_group_controller.h | 1 +
.../include/bundle_active_group_handler.h | 2 +-
.../src/bundle_active_group_controller.cpp | 11 +++++++++++
services/packageusage/include/bundle_active_event.h | 2 +-
.../packageusage/src/bundle_active_package_stats.cpp | 2 +-
.../packageusage/src/bundle_active_period_stats.cpp | 6 +++---
.../packageusage/src/bundle_active_user_service.cpp | 6 +++---
11 files changed, 26 insertions(+), 12 deletions(-)
diff --git a/services/common/src/bundle_active_app_state_obsever.cpp b/services/common/src/bundle_active_app_state_obsever.cpp
index 2e458c1..cf613c6 100644
--- a/services/common/src/bundle_active_app_state_obsever.cpp
+++ b/services/common/src/bundle_active_app_state_obsever.cpp
@@ -48,7 +48,7 @@ void BundleActiveAppStateObserver::OnAbilityStateChanged(const AbilityStateData
tmpHandlerObject.event_.bundleName_ = abilityStateData.bundleName;
tmpHandlerObject.event_.abilityName_ = abilityStateData.abilityName;
tmpHandlerObject.event_.abilityId_ = abilityStateData.abilityName;
- tmpHandlerObject.event_.ContinuousTaskAbilityName_ = "";
+ tmpHandlerObject.event_.continuousTaskAbilityName_ = "";
tmpHandlerObject.userId_ = userId;
sptr timer = MiscServices::TimeServiceClient::GetInstance();
tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs();
diff --git a/services/common/src/bundle_active_continuous_task_observer.cpp b/services/common/src/bundle_active_continuous_task_observer.cpp
index 4db0837..459524f 100644
--- a/services/common/src/bundle_active_continuous_task_observer.cpp
+++ b/services/common/src/bundle_active_continuous_task_observer.cpp
@@ -92,7 +92,7 @@ void BundleActiveContinuousTaskObserver::ReportContinuousTaskEvent(
tmpHandlerObject.event_.bundleName_ = bundleName;
tmpHandlerObject.event_.abilityName_ = "";
tmpHandlerObject.event_.abilityId_ = abilityId;
- tmpHandlerObject.event_.ContinuousTaskAbilityName_ = abiliytName;
+ tmpHandlerObject.event_.continuousTaskAbilityName_ = abiliytName;
tmpHandlerObject.userId_ = userId;
sptr timer = MiscServices::TimeServiceClient::GetInstance();
tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs();
diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp
index d0f7505..5f09345 100644
--- a/services/common/src/bundle_active_core.cpp
+++ b/services/common/src/bundle_active_core.cpp
@@ -31,6 +31,7 @@ BundleActiveReportHandlerObject::BundleActiveReportHandlerObject(const BundleAct
event_.timeStamp_ = orig.event_.timeStamp_;
event_.eventId_ = orig.event_.eventId_;
event_.isidle_ = orig.event_.isidle_;
+ event_.continuousTaskAbilityName_ = orig.event_.continuousTaskAbilityName_;
userId_ = orig.userId_;
bundleName_ = orig.bundleName_;
}
@@ -195,6 +196,7 @@ void BundleActiveCore::OnBundleUninstalled(const int userId, const std::string&
return;
}
service->DeleteUninstalledBundleStats(bundleName);
+ bundleGroupController_->OnBundleUninstalled(userId, bundleName);
}
void BundleActiveCore::OnStatsChanged()
diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp
index 9d7728a..556c5d1 100644
--- a/services/common/src/bundle_active_service.cpp
+++ b/services/common/src/bundle_active_service.cpp
@@ -181,7 +181,7 @@ int BundleActiveService::ReportEvent(std::string& bundleName, std::string& abili
tmpHandlerObject.event_.abilityName_ = abilityName;
tmpHandlerObject.event_.abilityId_ = abilityId;
tmpHandlerObject.event_.eventId_ = eventId;
- tmpHandlerObject.event_.ContinuousTaskAbilityName_ = continuousTask;
+ tmpHandlerObject.event_.continuousTaskAbilityName_ = continuousTask;
tmpHandlerObject.userId_ = userId;
sptr timer = MiscServices::TimeServiceClient::GetInstance();
tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs();
diff --git a/services/packagegroup/include/bundle_active_group_controller.h b/services/packagegroup/include/bundle_active_group_controller.h
index a8a2ec1..c0589b7 100644
--- a/services/packagegroup/include/bundle_active_group_controller.h
+++ b/services/packagegroup/include/bundle_active_group_controller.h
@@ -73,6 +73,7 @@ public:
void CheckIdleStatsOneTime();
void PeriodCheckBundleState(const int userId);
void OnUserRemoved(const int userId);
+ void OnBundleUninstalled(const int userId, const std::string bundleName);
void OnScreenChanged(const bool& isScreenOn, const int64_t bootFromTimeStamp);
void SetBundleGroup(const std::string& bundleName, const int userId, int newGroup, int reason,
const int64_t bootBasedTimeStamp, const bool& resetTimeout);
diff --git a/services/packagegroup/include/bundle_active_group_handler.h b/services/packagegroup/include/bundle_active_group_handler.h
index 2bf694b..cb9ec0d 100644
--- a/services/packagegroup/include/bundle_active_group_handler.h
+++ b/services/packagegroup/include/bundle_active_group_handler.h
@@ -48,7 +48,7 @@ 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 = THREE_HOUR;
+ static const int CHECK_IDLE_INTERVAL = TEN_MINUTE;
private:
std::shared_ptr bundleActiveGroupController_;
diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp
index 9a4ed7c..ca79fea 100644
--- a/services/packagegroup/src/bundle_active_group_controller.cpp
+++ b/services/packagegroup/src/bundle_active_group_controller.cpp
@@ -60,6 +60,17 @@ void BundleActiveGroupController::SetHandlerAndCreateUserHistory(
activeGroupHandler_ = groupHandler;
}
+void BundleActiveGroupController::OnBundleUninstalled(const int userId, const std::string bundleName)
+{
+ std::lock_guard lock(mutex_);
+ auto oneUserHistory = bundleUserHistory_->GetUserHistory(userId, false);
+ if (oneUserHistory == nullptr) {
+ return;
+ }
+ oneUserHistory->erase(bundleName);
+ bundleUserHistory_->WriteBundleUsage(userId);
+}
+
bool BundleActiveGroupController::GetBundleMgrProxy()
{
if (!sptrBundleMgr_) {
diff --git a/services/packageusage/include/bundle_active_event.h b/services/packageusage/include/bundle_active_event.h
index e0d6a8f..d438384 100644
--- a/services/packageusage/include/bundle_active_event.h
+++ b/services/packageusage/include/bundle_active_event.h
@@ -42,7 +42,7 @@ public:
static const int NOTIFICATION_SEEN = 17;
inline static const std::string DEVICE_EVENT_PACKAGE_NAME = "openharmony";
std::string bundleName_;
- std::string ContinuousTaskAbilityName_;
+ std::string continuousTaskAbilityName_;
std::string abilityName_;
std::string abilityId_;
int64_t timeStamp_;
diff --git a/services/packageusage/src/bundle_active_package_stats.cpp b/services/packageusage/src/bundle_active_package_stats.cpp
index b081c3d..01048a2 100644
--- a/services/packageusage/src/bundle_active_package_stats.cpp
+++ b/services/packageusage/src/bundle_active_package_stats.cpp
@@ -189,7 +189,7 @@ void BundleActivePackageStats::UpdateLongTimeTask(const std::string& longTimeTas
switch (eventId) {
case BundleActiveEvent::LONG_TIME_TASK_STARTTED:
- if (AnyLongTimeTaskStarted()) {
+ if (!AnyLongTimeTaskStarted()) {
lastContiniousTaskUsed_ = timeStamp;
}
longTimeTasks_[longTimeTaskName] = eventId;
diff --git a/services/packageusage/src/bundle_active_period_stats.cpp b/services/packageusage/src/bundle_active_period_stats.cpp
index a3eb481..e9f0b71 100644
--- a/services/packageusage/src/bundle_active_period_stats.cpp
+++ b/services/packageusage/src/bundle_active_period_stats.cpp
@@ -47,7 +47,7 @@ BundleActiveEvent BundleActivePeriodStats::BuildEvent(std::string bundleName, st
BundleActiveEvent newEvent;
newEvent.bundleName_ = bundleName;
if (!timeTaskName.empty()) {
- newEvent.ContinuousTaskAbilityName_ = timeTaskName;
+ newEvent.continuousTaskAbilityName_ = timeTaskName;
}
return newEvent;
}
@@ -75,8 +75,8 @@ void BundleActivePeriodStats::Update(const std::string bundleName, const std::st
void BundleActivePeriodStats::AddEvent(BundleActiveEvent event)
{
event.bundleName_ = GetCachedString(event.bundleName_);
- if (!event.ContinuousTaskAbilityName_.empty()) {
- event.ContinuousTaskAbilityName_ = GetCachedString(event.ContinuousTaskAbilityName_);
+ if (!event.continuousTaskAbilityName_.empty()) {
+ event.continuousTaskAbilityName_ = GetCachedString(event.continuousTaskAbilityName_);
}
events_.Insert(event);
if (event.timeStamp_ > endTime_) {
diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp
index 7e4efcf..cdc1639 100644
--- a/services/packageusage/src/bundle_active_user_service.cpp
+++ b/services/packageusage/src/bundle_active_user_service.cpp
@@ -123,7 +123,7 @@ void BundleActiveUserService::ReportEvent(const BundleActiveEvent& event)
it->UpdateKeyguardHidden(event.timeStamp_);
break;
default:
- it->Update(event.bundleName_, event.ContinuousTaskAbilityName_, event.timeStamp_, event.eventId_,
+ it->Update(event.bundleName_, event.continuousTaskAbilityName_, event.timeStamp_, event.eventId_,
event.abilityId_);
if (incrementBundleLaunch) {
BUNDLE_ACTIVE_LOGI(" BundleActiveUserService::ReportEvent increase bundle started count");
@@ -150,7 +150,7 @@ void BundleActiveUserService::ReportForFlushAndShutdown(const BundleActiveEvent&
RenewStatsInMemory(event.timeStamp_);
}
for (auto it : currentStats_) {
- it->Update(event.bundleName_, event.ContinuousTaskAbilityName_, event.timeStamp_, event.eventId_,
+ it->Update(event.bundleName_, event.continuousTaskAbilityName_, event.timeStamp_, event.eventId_,
event.abilityId_);
}
BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportForFlushAndShutdown called notify");
@@ -257,7 +257,7 @@ void BundleActiveUserService::RenewStatsInMemory(const int64_t timeStamp)
if (continueServices.find(continueBundleName) != continueServices.end()) {
for (std::map::iterator it = continueServices[continueBundleName].begin();
it != continueServices[continueBundleName].end(); it++) {
- (*itInterval)->Update(continueBundleName, it->first, beginTime, it->second, 0);
+ (*itInterval)->Update(continueBundleName, it->first, beginTime, it->second, "");
}
}
NotifyStatsChanged();
--
Gitee
From 78fb8ef6f3621a481d9822be9899b8d47574e49e Mon Sep 17 00:00:00 2001
From: houdisheng
Date: Tue, 1 Mar 2022 14:31:07 +0800
Subject: [PATCH 02/32] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dcontroller=E5=88=9D?=
=?UTF-8?q?=E5=A7=8B=E5=8C=96=E5=AF=BC=E8=87=B4core=E9=97=AE=E9=A2=98?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Signed-off-by: houdisheng
---
services/common/src/bundle_active_service.cpp | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp
index 556c5d1..06b2f63 100644
--- a/services/common/src/bundle_active_service.cpp
+++ b/services/common/src/bundle_active_service.cpp
@@ -81,6 +81,7 @@ void BundleActiveService::OnAddSystemAbility(int32_t systemAbilityId, const std:
powerManagerClient.RegisterShutdownCallback(shutdownCallback_);
InitAppStateSubscriber(reportHandler_);
InitContinuousSubscriber(reportHandler_);
+ bundleActiveCore_->InitBundleGroupController();
}
if (systemAbilityId == APP_MGR_SERVICE_ID) {
if (reportHandler_ != nullptr) {
@@ -92,9 +93,6 @@ void BundleActiveService::OnAddSystemAbility(int32_t systemAbilityId, const std:
SubscribeContinuousTask();
}
}
- if (systemAbilityId == BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) {
- bundleActiveCore_->InitBundleGroupController();
- }
}
--
Gitee
From 19bcdeaf650ab481d5646e9590fe17044165156e Mon Sep 17 00:00:00 2001
From: houdisheng
Date: Tue, 1 Mar 2022 15:37:00 +0800
Subject: [PATCH 03/32] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=97=A5=E5=BF=97?=
=?UTF-8?q?=E6=89=93=E5=8D=B0=E5=9C=B0=E5=9D=80?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Signed-off-by: houdisheng
---
services/common/include/bundle_active_log.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/services/common/include/bundle_active_log.h b/services/common/include/bundle_active_log.h
index d2056ed..3a24733 100644
--- a/services/common/include/bundle_active_log.h
+++ b/services/common/include/bundle_active_log.h
@@ -19,7 +19,7 @@
#include "hilog/log.h"
#define LOG_TAG_BUNDLE_ACTIVE "BUNDLE_ACTIVE"
-#define LOG_TAG_DOMAIN_ID_BUNDLE_ACTIVE 0xD001700
+#define LOG_TAG_DOMAIN_ID_BUNDLE_ACTIVE 0xD001701
static constexpr OHOS::HiviewDFX::HiLogLabel BUNDLE_ACTIVE_LOG_LABEL = {
LOG_CORE,
--
Gitee
From db407344859eeef72aa08034dad89de1f4b6e27f Mon Sep 17 00:00:00 2001
From: houdisheng
Date: Tue, 1 Mar 2022 16:20:43 +0800
Subject: [PATCH 04/32] =?UTF-8?q?=E4=BF=AE=E6=94=B9isldiebundle=E6=8E=A5?=
=?UTF-8?q?=E5=8F=A3=E6=9D=83=E9=99=90=E6=A0=A1=E9=AA=8C=E9=80=BB=E8=BE=91?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Signed-off-by: houdisheng
---
services/common/src/bundle_active_service.cpp | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp
index 06b2f63..f4d2960 100644
--- a/services/common/src/bundle_active_service.cpp
+++ b/services/common/src/bundle_active_service.cpp
@@ -202,8 +202,12 @@ bool BundleActiveService::IsBundleIdle(const std::string& bundleName)
OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId);
if (ret == ERR_OK && userId != -1) {
BUNDLE_ACTIVE_LOGI("BundleActiveService::IsBundleIdle user id is %{public}d", userId);
- bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, userId);
- if (isSystemAppAndHasPermission == true) {
+ 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);
}
}
--
Gitee
From 98319fa9bca9a5f63bbdd1c2e52bdfab9f296a56 Mon Sep 17 00:00:00 2001
From: houdisheng
Date: Tue, 1 Mar 2022 18:47:48 +0800
Subject: [PATCH 05/32] =?UTF-8?q?=E4=BF=AE=E6=94=B9sa=E5=90=AF=E5=8A=A8?=
=?UTF-8?q?=E9=80=BB=E8=BE=91?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Signed-off-by: houdisheng
---
.../common/include/bundle_active_service.h | 5 +-
services/common/src/bundle_active_service.cpp | 100 ++++++++++--------
2 files changed, 57 insertions(+), 48 deletions(-)
diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h
index 3b5ee1b..c0ec217 100644
--- a/services/common/include/bundle_active_service.h
+++ b/services/common/include/bundle_active_service.h
@@ -54,8 +54,6 @@ public:
protected:
void OnStart() override;
void OnStop() override;
- void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override;
- void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override;
private:
std::shared_ptr bundleActiveCore_;
@@ -64,7 +62,10 @@ private:
std::shared_ptr continuousTaskObserver_;
sptr sptrBundleMgr_;
sptr shutdownCallback_;
+ std::shared_ptr runner_;
+ std::shared_ptr handler_;
int ConvertIntervalType(const int intervalType);
+ void InitNecessaryState();
bool GetBundleMgrProxy();
bool CheckBundleIsSystemAppAndHasPermission(const int uid, const int userId);
void InitAppStateSubscriber(const std::shared_ptr& reportHandler);
diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp
index f4d2960..be942f2 100644
--- a/services/common/src/bundle_active_service.cpp
+++ b/services/common/src/bundle_active_service.cpp
@@ -28,6 +28,7 @@ namespace DeviceUsageStats {
static const int PERIOD_BEST_JS = 0;
static const int PERIOD_YEARLY_JS = 4;
static const int PERIOD_BEST_SERVICE = 4;
+static const int DELAY_TIME = 2000;
REGISTER_SYSTEM_ABILITY_BY_ID(BundleActiveService, DEVICE_USAGE_STATISTICS_SYS_ABILITY_ID, true);
using namespace OHOS::Security::AccessToken;
using AccessTokenKit = OHOS::Security::AccessToken::AccessTokenKit;
@@ -36,66 +37,77 @@ const std::string NEEDED_PERMISSION = "ohos.permission.BUNDLE_ACTIVE_INFO";
void BundleActiveService::OnStart()
{
BUNDLE_ACTIVE_LOGI("BundleActiveService::OnStart() called");
+ runner_ = AppExecFwk::EventRunner::Create("device_usage_stats_init_handler");
+ if (runner_ == nullptr) {
+ BUNDLE_ACTIVE_LOGI("BundleActiveService runner create failed!");
+ return;
+ }
+ handler_ = std::make_shared(runner_);
+ if (handler_ == nullptr) {
+ BUNDLE_ACTIVE_LOGI("BundleActiveService handler create failed!");
+ return;
+ }
+
+ InitNecessaryState();
int ret = Publish(this);
if (!ret) {
BUNDLE_ACTIVE_LOGE("[Server] OnStart, Register SystemAbility[1907] FAIL.");
return;
}
- AddSystemAbilityListener(POWER_MANAGER_SERVICE_ID);
- AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
- AddSystemAbilityListener(APP_MGR_SERVICE_ID);
- AddSystemAbilityListener(BACKGROUND_TASK_MANAGER_SERVICE_ID);
BUNDLE_ACTIVE_LOGI("[Server] OnStart, Register SystemAbility[1907] SUCCESS.");
return;
}
-void BundleActiveService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
+void BundleActiveService::InitNecessaryState()
{
- BUNDLE_ACTIVE_LOGI("BundleActiveService::OnAddSystemAbility called, SAID is %{public}d", systemAbilityId);
- if (systemAbilityId == POWER_MANAGER_SERVICE_ID) {
- if (bundleActiveCore_ == nullptr) {
- bundleActiveCore_ = std::make_shared();
- bundleActiveCore_->Init();
+ sptr systemAbilityManager
+ = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
+ if (systemAbilityManager == nullptr
+ || systemAbilityManager->CheckSystemAbility(APP_MGR_SERVICE_ID) == nullptr
+ || systemAbilityManager->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) == nullptr
+ || systemAbilityManager->CheckSystemAbility(POWER_MANAGER_SERVICE_ID) == nullptr
+ || systemAbilityManager->CheckSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr
+ || systemAbilityManager->CheckSystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID) == nullptr
+ || systemAbilityManager->CheckSystemAbiligy(TIME_SERVICE_ID) == nullptr) {
+ BUNDLE_ACTIVE_LOGI("request system service is not ready yet!");
+ auto task = [this]() { this->InitNecessaryState(); };
+ handler_->PostTask(task, DELAY_TIME);
+ return;
+ }
+
+ if (bundleActiveCore_ == nullptr) {
+ bundleActiveCore_ = std::make_shared();
+ bundleActiveCore_->Init();
+ }
+ if (reportHandler_ == nullptr) {
+ std::string threadName = "bundle_active_report_handler";
+ auto runner = AppExecFwk::EventRunner::Create(threadName);
+ if (runner == nullptr) {
+ BUNDLE_ACTIVE_LOGE("report handler is null");
+ return;
}
+ reportHandler_ = std::make_shared(runner);
if (reportHandler_ == nullptr) {
- std::string threadName = "bundle_active_report_handler";
- auto runner = AppExecFwk::EventRunner::Create(threadName);
- if (runner == nullptr) {
- BUNDLE_ACTIVE_LOGE("report handler is null");
- return;
- }
- reportHandler_ = std::make_shared(runner);
- if (reportHandler_ == nullptr) {
- return;
- }
- reportHandler_->Init(bundleActiveCore_);
- }
- if (reportHandler_ != nullptr && bundleActiveCore_ != nullptr) {
- BUNDLE_ACTIVE_LOGI("core and handler is not null");
- bundleActiveCore_->SetHandler(reportHandler_);
- } else {
return;
}
- shutdownCallback_ = new BundleActiveShutdownCallbackService(bundleActiveCore_);
- auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
- powerManagerClient.RegisterShutdownCallback(shutdownCallback_);
- InitAppStateSubscriber(reportHandler_);
- InitContinuousSubscriber(reportHandler_);
- bundleActiveCore_->InitBundleGroupController();
- }
- if (systemAbilityId == APP_MGR_SERVICE_ID) {
- if (reportHandler_ != nullptr) {
- SubscribeAppState();
- }
+ reportHandler_->Init(bundleActiveCore_);
}
- if (systemAbilityId == BACKGROUND_TASK_MANAGER_SERVICE_ID) {
- if (reportHandler_ != nullptr) {
- SubscribeContinuousTask();
- }
+ if (reportHandler_ != nullptr && bundleActiveCore_ != nullptr) {
+ BUNDLE_ACTIVE_LOGI("core and handler is not null");
+ bundleActiveCore_->SetHandler(reportHandler_);
+ } else {
+ return;
}
+ shutdownCallback_ = new BundleActiveShutdownCallbackService(bundleActiveCore_);
+ auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
+ powerManagerClient.RegisterShutdownCallback(shutdownCallback_);
+ InitAppStateSubscriber(reportHandler_);
+ InitContinuousSubscriber(reportHandler_);
+ bundleActiveCore_->InitBundleGroupController();
+ SubscribeAppState();
+ SubscribeContinuousTask();
}
-
OHOS::sptr BundleActiveService::GetAppManagerInstance()
{
OHOS::sptr systemAbilityManager =
@@ -152,10 +164,6 @@ bool BundleActiveService::SubscribeContinuousTask()
return true;
}
-void BundleActiveService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
-{
-}
-
void BundleActiveService::OnStop()
{
if (shutdownCallback_ != nullptr) {
--
Gitee
From 517e9678061c8bb7a119f81905fd3baa4ba83a0d Mon Sep 17 00:00:00 2001
From: houdisheng
Date: Tue, 1 Mar 2022 19:30:53 +0800
Subject: [PATCH 06/32] =?UTF-8?q?=E4=BF=AE=E6=94=B9sa=E5=90=AF=E5=8A=A8?=
=?UTF-8?q?=E9=80=BB=E8=BE=91?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Signed-off-by: houdisheng
---
services/common/src/bundle_active_service.cpp | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp
index be942f2..9b7bfd2 100644
--- a/services/common/src/bundle_active_service.cpp
+++ b/services/common/src/bundle_active_service.cpp
@@ -68,7 +68,7 @@ void BundleActiveService::InitNecessaryState()
|| systemAbilityManager->CheckSystemAbility(POWER_MANAGER_SERVICE_ID) == nullptr
|| systemAbilityManager->CheckSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr
|| systemAbilityManager->CheckSystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID) == nullptr
- || systemAbilityManager->CheckSystemAbiligy(TIME_SERVICE_ID) == nullptr) {
+ || systemAbilityManager->CheckSystemAbility(TIME_SERVICE_ID) == nullptr) {
BUNDLE_ACTIVE_LOGI("request system service is not ready yet!");
auto task = [this]() { this->InitNecessaryState(); };
handler_->PostTask(task, DELAY_TIME);
--
Gitee
From b0cd85f53919b62424ae30704a1428627b5021bb Mon Sep 17 00:00:00 2001
From: wyuanchao
Date: Wed, 2 Mar 2022 15:17:19 +0800
Subject: [PATCH 07/32] modify bundleState.d.ts
Signed-off-by: wyuanchao
---
BUILD.gn | 2 +-
bundle.json | 2 +-
.../bundlestats/js/@ohos.bundleState.d.ts | 66 ++++++++++++-------
.../napi/include/bundle_state_init.h | 2 +-
4 files changed, 47 insertions(+), 25 deletions(-)
diff --git a/BUILD.gn b/BUILD.gn
index 5a54201..7a44408 100644
--- a/BUILD.gn
+++ b/BUILD.gn
@@ -52,7 +52,7 @@ ohos_prebuilt_etc("device_usage_statistics_service_init") {
subsystem_name = "resourceschedule"
}
-ohos_shared_library("usagestatskit") {
+ohos_shared_library("bundlestate") {
sources = [
"frameworks/src/bundle_state_common.cpp",
"frameworks/src/bundle_state_init.cpp",
diff --git a/bundle.json b/bundle.json
index 1dcaacc..014b937 100644
--- a/bundle.json
+++ b/bundle.json
@@ -52,7 +52,7 @@
"//foundation/resourceschedule/device_usage_statistics:usagestatservice",
"//foundation/resourceschedule/device_usage_statistics:device_usage_statistics_sa_profile",
"//foundation/resourceschedule/device_usage_statistics:device_usage_statistics_service_init",
- "//foundation/resourceschedule/device_usage_statistics:usagestatskit"
+ "//foundation/resourceschedule/device_usage_statistics:bundlestate"
],
"inner_kits": [
{
diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts
index e28bf6c..9a5f353 100644
--- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts
+++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts
@@ -31,8 +31,10 @@ declare namespace bundleState {
/**
* @since 7
- * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App
- * @devices phone, tablet, tv, wearable, car
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
+ * @devices phone, tablet, tv, wearable, car.
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO.
+ * @systemapi Hide this for inner system use.
*/
interface BundleStateInfo {
/**
@@ -83,8 +85,10 @@ declare namespace bundleState {
* The bundle name of both objects must be the same.
*
* @since 7
- * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App
- * @devices phone, tablet, tv, wearable, car
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
+ * @devices phone, tablet, tv, wearable, car.
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO.
+ * @systemapi Hide this for inner system use.
* @param toMerge Indicates the {@link BundleActiveInfo} object to merge.
* if the bundle names of the two {@link BundleActiveInfo} objects are different.
*/
@@ -93,8 +97,10 @@ declare namespace bundleState {
/**
* @since 7
- * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App
- * @devices phone, tablet, tv, wearable, car
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
+ * @devices phone, tablet, tv, wearable, car.
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO.
+ * @systemapi Hide this for inner system use.
*/
interface BundleActiveState {
/**
@@ -127,8 +133,10 @@ declare namespace bundleState {
* Checks whether the application with a specified bundle name is in the idle state.
*
* @since 7
- * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
- * @devices phone, tablet, tv, wearable, car
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup.
+ * @devices phone, tablet, tv, wearable, car.
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO.
+ * @systemapi Hide this for inner system use.
* @param bundleName Indicates the bundle name of the application to query.
* @return Returns {@code true} if the application is idle in a particular period;
* returns {@code false} otherwise. The time range of the particular period is defined by the system,
@@ -144,8 +152,10 @@ declare namespace bundleState {
* for example, restricting the running of background tasks.
*
* @since 7
- * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
- * @devices phone, tablet, tv, wearable, car
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup.
+ * @devices phone, tablet, tv, wearable, car.
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO.
+ * @systemapi Hide this for inner system use.
* @return Returns the usage priority group of the calling application.
*/
function queryAppUsagePriorityGroup(callback: AsyncCallback): void;
@@ -153,8 +163,10 @@ declare namespace bundleState {
/**
* @since 7
- * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App
- * @devices phone, tablet, tv, wearable, car
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
+ * @devices phone, tablet, tv, wearable, car.
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO.
+ * @systemapi Hide this for inner system use.
*/
interface BundleActiveInfoResponse {
[key: string]: BundleStateInfo;
@@ -166,8 +178,10 @@ declare namespace bundleState {
* This method queries usage information at the {@link #BY_OPTIMIZED} interval by default.
*
* @since 7
- * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App
- * @devices phone, tablet, tv, wearable, car
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
+ * @devices phone, tablet, tv, wearable, car.
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO.
+ * @systemapi Hide this for inner system use.
* @param begin Indicates the start time of the query period, in milliseconds.
* @param end Indicates the end time of the query period, in milliseconds.
* @return Returns the {@link BundleActiveInfoResponse} objects containing the usage information about each bundle.
@@ -179,8 +193,10 @@ declare namespace bundleState {
* Declares interval type.
*
* @since 7
- * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App
- * @devices phone, tablet, tv, wearable, car
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
+ * @devices phone, tablet, tv, wearable, car.
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO.
+ * @systemapi Hide this for inner system use.
*/
export enum IntervalType {
/**
@@ -213,8 +229,10 @@ declare namespace bundleState {
* Queries usage information about each bundle within a specified period at a specified interval.
*
* @since 7
- * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App
- * @devices phone, tablet, tv, wearable, car
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
+ * @devices phone, tablet, tv, wearable, car.
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO.
+ * @systemapi Hide this for inner system use.
* @param byInterval Indicates the interval at which the usage statistics are queried.
* The value can be {@link #BY_OPTIMIZED}, {@link #BY_DAILY},
* {@link #BY_WEEKLY}, {@link #BY_MONTHLY}, or {@link #BY_ANNUALLY}.
@@ -229,8 +247,10 @@ declare namespace bundleState {
* Queries state data of all bundles within a specified period identified by the start and end time.
*
* @since 7
- * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App
- * @devices phone, tablet, tv, wearable, car
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
+ * @devices phone, tablet, tv, wearable, car.
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO.
+ * @systemapi Hide this for inner system use.
* @param begin Indicates the start time of the query period, in milliseconds.
* @param end Indicates the end time of the query period, in milliseconds.
* @return Returns the list of {@link BundleActiveState} objects containing the state data of all bundles.
@@ -242,8 +262,10 @@ declare namespace bundleState {
* Queries state data of the current bundle within a specified period.
*
* @since 7
- * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App
- * @devices phone, tablet, tv, wearable, car
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
+ * @devices phone, tablet, tv, wearable, car.
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO.
+ * @systemapi Hide this for inner system use.
* @param begin Indicates the start time of the query period, in milliseconds.
* @param end Indicates the end time of the query period, in milliseconds.
* @return Returns the {@link BundleActiveState} object Array containing the state data of the current bundle.
diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_init.h b/interfaces/kits/bundlestats/napi/include/bundle_state_init.h
index 045d7bb..c05c8f5 100644
--- a/interfaces/kits/bundlestats/napi/include/bundle_state_init.h
+++ b/interfaces/kits/bundlestats/napi/include/bundle_state_init.h
@@ -40,7 +40,7 @@ napi_module _module = {
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = BundleStateInit,
- .nm_modname = "usagestatskit",
+ .nm_modname = "bundlestate",
.nm_priv = ((void *)0),
.reserved = {0}
};
--
Gitee
From 9c7ff8caf1f534b549f63ad5fec0d1e5b660d59e Mon Sep 17 00:00:00 2001
From: wyuanchao
Date: Wed, 2 Mar 2022 17:46:04 +0800
Subject: [PATCH 08/32] modify @devices
Signed-off-by: wyuanchao
---
.../kits/bundlestats/js/@ohos.bundleState.d.ts | 12 ------------
1 file changed, 12 deletions(-)
diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts
index 9a5f353..eb724fd 100644
--- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts
+++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts
@@ -25,14 +25,12 @@ import { AsyncCallback } from './basic';
* then returns it to you.
*
* @since 7
- * @devices phone, tablet, tv, wearable, car
*/
declare namespace bundleState {
/**
* @since 7
* @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
- * @devices phone, tablet, tv, wearable, car.
* @permission ohos.permission.BUNDLE_ACTIVE_INFO.
* @systemapi Hide this for inner system use.
*/
@@ -86,7 +84,6 @@ declare namespace bundleState {
*
* @since 7
* @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
- * @devices phone, tablet, tv, wearable, car.
* @permission ohos.permission.BUNDLE_ACTIVE_INFO.
* @systemapi Hide this for inner system use.
* @param toMerge Indicates the {@link BundleActiveInfo} object to merge.
@@ -98,7 +95,6 @@ declare namespace bundleState {
/**
* @since 7
* @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
- * @devices phone, tablet, tv, wearable, car.
* @permission ohos.permission.BUNDLE_ACTIVE_INFO.
* @systemapi Hide this for inner system use.
*/
@@ -134,7 +130,6 @@ declare namespace bundleState {
*
* @since 7
* @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup.
- * @devices phone, tablet, tv, wearable, car.
* @permission ohos.permission.BUNDLE_ACTIVE_INFO.
* @systemapi Hide this for inner system use.
* @param bundleName Indicates the bundle name of the application to query.
@@ -153,7 +148,6 @@ declare namespace bundleState {
*
* @since 7
* @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup.
- * @devices phone, tablet, tv, wearable, car.
* @permission ohos.permission.BUNDLE_ACTIVE_INFO.
* @systemapi Hide this for inner system use.
* @return Returns the usage priority group of the calling application.
@@ -164,7 +158,6 @@ declare namespace bundleState {
/**
* @since 7
* @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
- * @devices phone, tablet, tv, wearable, car.
* @permission ohos.permission.BUNDLE_ACTIVE_INFO.
* @systemapi Hide this for inner system use.
*/
@@ -179,7 +172,6 @@ declare namespace bundleState {
*
* @since 7
* @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
- * @devices phone, tablet, tv, wearable, car.
* @permission ohos.permission.BUNDLE_ACTIVE_INFO.
* @systemapi Hide this for inner system use.
* @param begin Indicates the start time of the query period, in milliseconds.
@@ -194,7 +186,6 @@ declare namespace bundleState {
*
* @since 7
* @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
- * @devices phone, tablet, tv, wearable, car.
* @permission ohos.permission.BUNDLE_ACTIVE_INFO.
* @systemapi Hide this for inner system use.
*/
@@ -230,7 +221,6 @@ declare namespace bundleState {
*
* @since 7
* @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
- * @devices phone, tablet, tv, wearable, car.
* @permission ohos.permission.BUNDLE_ACTIVE_INFO.
* @systemapi Hide this for inner system use.
* @param byInterval Indicates the interval at which the usage statistics are queried.
@@ -248,7 +238,6 @@ declare namespace bundleState {
*
* @since 7
* @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
- * @devices phone, tablet, tv, wearable, car.
* @permission ohos.permission.BUNDLE_ACTIVE_INFO.
* @systemapi Hide this for inner system use.
* @param begin Indicates the start time of the query period, in milliseconds.
@@ -263,7 +252,6 @@ declare namespace bundleState {
*
* @since 7
* @syscap SystemCapability.ResourceSchedule.UsageStatistics.App.
- * @devices phone, tablet, tv, wearable, car.
* @permission ohos.permission.BUNDLE_ACTIVE_INFO.
* @systemapi Hide this for inner system use.
* @param begin Indicates the start time of the query period, in milliseconds.
--
Gitee
From cd97c8d7ea22ce0e824eb8a656c80a968d8e23ff Mon Sep 17 00:00:00 2001
From: wyuanchao
Date: Thu, 3 Mar 2022 09:13:49 +0800
Subject: [PATCH 09/32] modify bundle_state_init.h
Signed-off-by: wyuanchao
---
interfaces/kits/bundlestats/napi/include/bundle_state_init.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_init.h b/interfaces/kits/bundlestats/napi/include/bundle_state_init.h
index c05c8f5..7547c2a 100644
--- a/interfaces/kits/bundlestats/napi/include/bundle_state_init.h
+++ b/interfaces/kits/bundlestats/napi/include/bundle_state_init.h
@@ -40,7 +40,7 @@ napi_module _module = {
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = BundleStateInit,
- .nm_modname = "bundlestate",
+ .nm_modname = "bundleState",
.nm_priv = ((void *)0),
.reserved = {0}
};
--
Gitee
From 1a2a7367eaf1acffcfad09e63d97edaedf90011b Mon Sep 17 00:00:00 2001
From: houdisheng
Date: Thu, 3 Mar 2022 21:29:20 +0800
Subject: [PATCH 10/32] =?UTF-8?q?=E8=BD=AC=E6=B5=8B=E5=85=B3=E9=94=AE?=
=?UTF-8?q?=E9=97=AE=E9=A2=98=E4=BF=AE=E6=94=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Signed-off-by: houdisheng
---
.../common/include/bundle_active_constant.h | 2 +-
services/common/include/bundle_active_core.h | 14 +-
.../include/bundle_active_usage_database.h | 1 +
services/common/src/bundle_active_core.cpp | 133 +++++++++++++-----
.../src/bundle_active_usage_database.cpp | 43 +++++-
.../include/bundle_active_group_handler.h | 2 +-
.../bundle_active_stats_update_listener.h | 2 +-
.../include/bundle_active_user_service.h | 6 +-
.../src/bundle_active_package_stats.cpp | 2 +-
.../src/bundle_active_report_handler.cpp | 4 +-
.../src/bundle_active_user_service.cpp | 33 +++--
11 files changed, 172 insertions(+), 70 deletions(-)
diff --git a/services/common/include/bundle_active_constant.h b/services/common/include/bundle_active_constant.h
index d3caa42..e77268b 100644
--- a/services/common/include/bundle_active_constant.h
+++ b/services/common/include/bundle_active_constant.h
@@ -59,7 +59,7 @@ 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 = 6 * 24 * 60 * 60 * 1000;
+const int64_t SIX_DAY_IN_MILLIS_MAX = 1 * 6 * 30 * 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;
diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h
index 1956dc5..a9b6868 100644
--- a/services/common/include/bundle_active_core.h
+++ b/services/common/include/bundle_active_core.h
@@ -60,7 +60,7 @@ public:
/*
* function: OnStatsChanged, report flush to disk, end_of_day event to service.
*/
- void OnStatsChanged() override;
+ void OnStatsChanged(const int userId) override;
/*
* function: OnStatsChanged, when device reboot after more than one day, BundleActiveUserService
* will use it to flush group info.
@@ -91,10 +91,10 @@ public:
* function: SetHandler, BundleActiveService call it to set event report handler
*/
void SetHandler(const std::shared_ptr& reportHandler);
- // flush database.
- void RestoreToDatabase();
- // flush database
- void RestoreToDatabaseLocked();
+ // flush database for one user data
+ void RestoreToDatabase(const int userId);
+ // flush database for one user data
+ void RestoreToDatabaseLocked(const int userId);
// called when device shutdown, update the in-memory stat and flush the database.
void ShutDown();
// query the package stat for calling user.
@@ -108,7 +108,7 @@ public:
// query the app group for calling app.
int QueryPackageGroup(const int userId, const std::string bundleName);
// get the wall time and check if the wall time is changed.
- int64_t CheckTimeChangeAndGetWallTime();
+ int64_t CheckTimeChangeAndGetWallTime(int userId = 0);
// convert event timestamp from boot based time to wall time.
void ConvertToSystemTimeLocked(BundleActiveEvent& event);
// get or create BundleActiveUserService object for specifice user.
@@ -122,6 +122,7 @@ public:
void GetAllActiveUser(std::vector &osAccountInfos);
// when service stop, call it to unregister commen event and shutdown call back.
void UnRegisterSubscriber();
+ int64_t GetSystemTimeMs();
private:
static const int64_t FLUSH_INTERVAL = TWO_MINUTE;
@@ -138,6 +139,7 @@ private:
std::map> userStatServices_;
void RegisterSubscriber();
std::shared_ptr commonEventSubscriber_;
+ void RestoreAllData();
};
}
}
diff --git a/services/common/include/bundle_active_usage_database.h b/services/common/include/bundle_active_usage_database.h
index 345a247..f52a995 100644
--- a/services/common/include/bundle_active_usage_database.h
+++ b/services/common/include/bundle_active_usage_database.h
@@ -81,6 +81,7 @@ private:
void DeleteUninstalledInfo(const int userId, const std::string& bundleName, const std::string& tableName,
unsigned int databaseType);
int32_t CreateDatabasePath();
+ int64_t GetSystemTimeMs();
private:
std::vector databaseFiles_;
diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp
index 5f09345..60fe6d3 100644
--- a/services/common/src/bundle_active_core.cpp
+++ b/services/common/src/bundle_active_core.cpp
@@ -13,6 +13,9 @@
* limitations under the License.
*/
+#include
+#include
+
#include "time_service_client.h"
#include "bundle_active_event.h"
@@ -127,10 +130,10 @@ void BundleActiveCore::Init()
sptr timer = MiscServices::TimeServiceClient::GetInstance();
do {
realTimeShot_ = timer->GetBootTimeMs();
- systemTimeShot_ = timer->GetWallTimeMs();
+ systemTimeShot_ = GetSystemTimeMs();
} while (realTimeShot_ == -1 && systemTimeShot_ == -1);
realTimeShot_ = timer->GetBootTimeMs();
- systemTimeShot_ = timer->GetWallTimeMs();
+ systemTimeShot_ = GetSystemTimeMs();
bundleGroupController_ = std::make_shared();
BUNDLE_ACTIVE_LOGI("system time shot is %{public}lld", systemTimeShot_);
}
@@ -190,7 +193,7 @@ void BundleActiveCore::OnBundleUninstalled(const int userId, const std::string&
{
BUNDLE_ACTIVE_LOGI("BundleActiveCore::OnBundleUninstalled CALLED");
std::lock_guard lock(mutex_);
- int64_t timeNow = CheckTimeChangeAndGetWallTime();
+ int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
auto service = GetUserDataAndInitializeIfNeeded(userId, timeNow);
if (service == nullptr) {
return;
@@ -199,31 +202,20 @@ void BundleActiveCore::OnBundleUninstalled(const int userId, const std::string&
bundleGroupController_->OnBundleUninstalled(userId, bundleName);
}
-void BundleActiveCore::OnStatsChanged()
+void BundleActiveCore::OnStatsChanged(const int userId)
{
- auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_FLUSH_TO_DISK);
if (!handler_.expired()) {
BUNDLE_ACTIVE_LOGI("BundleActiveCore::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);
}
}
-void BundleActiveCore::RestoreToDatabase()
-{
- BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabase called");
- std::lock_guard lock(mutex_);
- sptr timer = MiscServices::TimeServiceClient::GetInstance();
- BundleActiveEvent event;
- event.eventId_ = BundleActiveEvent::FLUSH;
- event.timeStamp_ = timer->GetBootTimeMs();
- event.abilityId_ = "";
- ReportEventToAllUserId(event);
- RestoreToDatabaseLocked();
-}
-
-void BundleActiveCore::RestoreToDatabaseLocked()
-{
- BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabaseLocked called");
+void BundleActiveCore::RestoreAllData() {
for (std::map>::iterator it = userStatServices_.begin();
it != userStatServices_.end(); it++) {
std::shared_ptr service = it->second;
@@ -231,7 +223,7 @@ void BundleActiveCore::RestoreToDatabaseLocked()
BUNDLE_ACTIVE_LOGI("service in BundleActiveCore::RestoreToDatabaseLocked() is null");
}
BUNDLE_ACTIVE_LOGI("userid is %{public}d ", service->userId_);
- service->RestoreStats();
+ service->RestoreStats(true);
if (bundleGroupController_ != nullptr && bundleGroupController_->bundleUserHistory_ != nullptr) {
bundleGroupController_->RestoreToDatabase(it->first);
}
@@ -245,6 +237,44 @@ void BundleActiveCore::RestoreToDatabaseLocked()
}
}
+void BundleActiveCore::RestoreToDatabase(const int userId)
+{
+ BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabase called");
+ sptr timer = MiscServices::TimeServiceClient::GetInstance();
+ BundleActiveEvent event;
+ event.eventId_ = BundleActiveEvent::FLUSH;
+ event.timeStamp_ = GetSystemTimeMs();
+ event.abilityId_ = "";
+ auto it = userStatServices_.find(userId);
+ if (it != userStatServices_.end()) {
+ it->second->ReportEvent(event);
+ }
+ if (bundleGroupController_ != nullptr) {
+ bundleGroupController_->RestoreDurationToDatabase();
+ }
+ RestoreToDatabaseLocked(userId);
+}
+
+void BundleActiveCore::RestoreToDatabaseLocked(const int userId)
+{
+ BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabaseLocked called");
+ auto it = userStatServices_.find(userId);
+ if (it != userStatServices_.end()) {
+ it->second->RestoreStats(false);
+ }
+ if (bundleGroupController_ != nullptr) {
+ bundleGroupController_->RestoreDurationToDatabase();
+ }
+ if (!handler_.expired()) {
+ BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabaseLocked remove flush to disk event");
+ handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK);
+ }
+ if (!handler_.expired()) {
+ BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabaseLocked remove flush to disk event");
+ handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK);
+ }
+}
+
void BundleActiveCore::ShutDown()
{
BUNDLE_ACTIVE_LOGI("BundleActiveCore::ShutDown called");
@@ -255,7 +285,7 @@ void BundleActiveCore::ShutDown()
event.bundleName_ = BundleActiveEvent::DEVICE_EVENT_PACKAGE_NAME;
bundleGroupController_->ShutDown(timeStamp);
ReportEventToAllUserId(event);
- RestoreToDatabaseLocked();
+ RestoreAllData();
}
void BundleActiveCore::OnStatsReload()
@@ -268,26 +298,36 @@ void BundleActiveCore::OnSystemUpdate(int userId)
{
}
-int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime()
+int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime(int userId)
{
- BUNDLE_ACTIVE_LOGI("BundleActiveCore::CheckTimeChangeAndGetWallTime called");
+ BUNDLE_ACTIVE_LOGI("BundleActiveCore::CheckTimeChangeAndGetWallTime called, userId is %{public}d", userId);
sptr timer = MiscServices::TimeServiceClient::GetInstance();
- int64_t actualSystemTime = timer->GetWallTimeMs();
+ int64_t actualSystemTime = GetSystemTimeMs();
int64_t actualRealTime = timer->GetBootTimeMs();
int64_t expectedSystemTime = (actualRealTime - realTimeShot_) + systemTimeShot_;
int64_t diffSystemTime = actualSystemTime - expectedSystemTime;
+ BUNDLE_ACTIVE_LOGI("asystime is %{public}lld, artime is %{public}lld, esystime is %{public}lld, "
+ "diff is %{public}lld", actualSystemTime, actualRealTime, expectedSystemTime, diffSystemTime);
if (std::abs(diffSystemTime) > TIME_CHANGE_THRESHOLD_MILLIS) {
// 时区变换逻辑
- BUNDLE_ACTIVE_LOGI("time changed!");
- for (std::map>::iterator it = userStatServices_.begin();
- it != userStatServices_.end(); it++) {
- BUNDLE_ACTIVE_LOGI("BundleActiveCore::CheckTimeChangeAndGetWallTime in update time loop");
- std::shared_ptr service = it->second;
- service->RenewTableTime(expectedSystemTime, actualSystemTime);
+ auto it = userStatServices_.find(userId);
+ if (it != userStatServices_.end()) {
+ BundleActiveEvent event;
+ event.eventId_ = BundleActiveEvent::FLUSH;
+ event.timeStamp_ = GetSystemTimeMs();
+ event.abilityId_ = "";
+ it->second->ReportEvent(event);
+ it->second->RestoreStats(true);
+ it->second->RenewTableTime(expectedSystemTime, actualSystemTime);
+ it->second->LoadActiveStats(actualSystemTime, false);
}
realTimeShot_ = actualRealTime;
systemTimeShot_ = actualSystemTime;
}
+ if (!handler_.expired()) {
+ BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabaseLocked remove flush to disk event");
+ handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK);
+ }
return actualSystemTime;
}
@@ -314,11 +354,14 @@ void BundleActiveCore::OnUserRemoved(const int userId)
int BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int userId)
{
std::lock_guard lock(mutex_);
+ if (userId == 0) {
+ return -1;
+ }
BUNDLE_ACTIVE_LOGI("BundleActiveCore::ReportEvent called");
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();
+ int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
int64_t bootBasedTimeStamp = timer->GetBootTimeMs();
ConvertToSystemTimeLocked(event);
std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow);
@@ -348,7 +391,7 @@ int BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event)
}
BUNDLE_ACTIVE_LOGI("BundleActiveCore::ReportEventToAllUserId SERVICE user ID IS userId %{public}d",
service->userId_);
- service->ReportForFlushAndShutdown(event);
+ service->ReportForShutdown(event);
return 0;
}
return 0;
@@ -360,7 +403,7 @@ std::vector BundleActiveCore::QueryPackageStats(const
BUNDLE_ACTIVE_LOGI("BundleActiveCore::QueryPackageStats called");
std::lock_guard lock(mutex_);
std::vector result;
- int64_t timeNow = CheckTimeChangeAndGetWallTime();
+ int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
BUNDLE_ACTIVE_LOGI("BundleActiveCore::QueryPackageStats begin time is %{public}lld, end time is %{public}lld, "
"intervaltype is %{public}d", beginTime, endTime, intervalType);
if (beginTime > timeNow || beginTime >= endTime) {
@@ -382,7 +425,7 @@ std::vector BundleActiveCore::QueryEvents(const int userId, c
BUNDLE_ACTIVE_LOGI("BundleActiveCore::QueryEvents called");
std::vector result;
std::lock_guard lock(mutex_);
- int64_t timeNow = CheckTimeChangeAndGetWallTime();
+ int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
if (beginTime > timeNow || beginTime >= endTime) {
return result;
}
@@ -424,5 +467,23 @@ void BundleActiveCore::GetAllActiveUser(std::vector(now) < 0) {
+ BUNDLE_ACTIVE_LOGE("Get now time error");
+ return 0;
+ }
+ auto tarEndTimePoint = std::chrono::system_clock::from_time_t(now);
+ auto tarDuration = std::chrono::duration_cast(tarEndTimePoint.time_since_epoch());
+ int64_t tarDate = tarDuration.count();
+ if (tarDate < 0) {
+ BUNDLE_ACTIVE_LOGE("tarDuration is less than 0.");
+ return -1;
+ }
+ return static_cast(tarDate);
+}
}
}
\ No newline at end of file
diff --git a/services/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp
index 9a378e5..f6cd89c 100644
--- a/services/common/src/bundle_active_usage_database.cpp
+++ b/services/common/src/bundle_active_usage_database.cpp
@@ -683,8 +683,12 @@ void BundleActiveUsageDatabase::FlushPackageInfo(unsigned int databaseType, cons
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_));
- valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME_CONTINUOUS_TASK, (iter->second->lastContiniousTaskUsed_ -
- 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_));
+ }
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);
@@ -741,7 +745,11 @@ shared_ptr BundleActiveUsageDatabase::GetCurrentUsageDa
bundleActiveResult->GetLong(LAST_TIME_COLUMN_INDEX, relativeLastTimeUsed);
usageStats->lastTimeUsed_ = relativeLastTimeUsed + currentPackageTime;
bundleActiveResult->GetLong(LAST_TIME_CONTINUOUS_TASK_COLUMN_INDEX, relativeLastTimeFrontServiceUsed);
- usageStats->lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + currentPackageTime;
+ if (relativeLastTimeFrontServiceUsed == -1) {
+ usageStats->lastContiniousTaskUsed_ = -1;
+ } else {
+ usageStats->lastContiniousTaskUsed_ = 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_,
@@ -753,7 +761,7 @@ shared_ptr BundleActiveUsageDatabase::GetCurrentUsageDa
eventBeginTime_ = currentPackageTime;
}
sptr timer = MiscServices::TimeServiceClient::GetInstance();
- int64_t systemTime = timer->GetWallTimeMs();
+ int64_t systemTime = GetSystemTimeMs();
intervalStats->lastTimeSaved_ = systemTime;
return intervalStats;
}
@@ -936,6 +944,7 @@ void BundleActiveUsageDatabase::RenewTableTime(int64_t changedTime)
vector tableArray = sortedTableArray_.at(i);
for (unsigned int j = 0; j < tableArray.size(); j++) {
int64_t newTime = tableArray.at(j) + changedTime;
+ BUNDLE_ACTIVE_LOGI("new table time is %{public}lld", newTime);
if (newTime < 0) {
DeleteInvalidTable(i, tableArray.at(j));
} else {
@@ -990,7 +999,7 @@ void BundleActiveUsageDatabase::UpdateUsageData(int32_t databaseType, BundleActi
}
FlushPackageInfo(databaseType, stats);
sptr timer = MiscServices::TimeServiceClient::GetInstance();
- int64_t systemTime = timer->GetWallTimeMs();
+ int64_t systemTime = GetSystemTimeMs();
stats.lastTimeSaved_ = systemTime;
}
@@ -1073,7 +1082,11 @@ vector BundleActiveUsageDatabase::QueryDatabaseUsageSt
bundleActiveResult->GetLong(LAST_TIME_COLUMN_INDEX, relativeLastTimeUsed);
usageStats.lastTimeUsed_ = relativeLastTimeUsed + packageTableTime;
bundleActiveResult->GetLong(LAST_TIME_CONTINUOUS_TASK_COLUMN_INDEX, relativeLastTimeFrontServiceUsed);
- usageStats.lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + packageTableTime;
+ if (relativeLastTimeFrontServiceUsed == -1) {
+ usageStats.lastContiniousTaskUsed_ = -1;
+ } else {
+ usageStats.lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + packageTableTime;
+ }
bundleActiveResult->GetLong(TOTAL_TIME_COLUMN_INDEX, usageStats.totalInFrontTime_);
bundleActiveResult->GetLong(TOTAL_TIME_CONTINUOUS_TASK_COLUMN_INDEX,
usageStats.totalContiniousTaskUsedTime_);
@@ -1179,5 +1192,23 @@ void BundleActiveUsageDatabase::DeleteUninstalledInfo(const int userId, const st
rdbStore->Delete(deletedRows, tableName, "userId = ? and bundleName = ?", queryCondition);
}
}
+
+int64_t BundleActiveUsageDatabase::GetSystemTimeMs()
+{
+ time_t now;
+ (void)time(&now); // unit is seconds.
+ if (static_cast(now) < 0) {
+ BUNDLE_ACTIVE_LOGE("Get now time error");
+ return 0;
+ }
+ auto tarEndTimePoint = std::chrono::system_clock::from_time_t(now);
+ auto tarDuration = std::chrono::duration_cast(tarEndTimePoint.time_since_epoch());
+ int64_t tarDate = tarDuration.count();
+ if (tarDate < 0) {
+ BUNDLE_ACTIVE_LOGE("tarDuration is less than 0.");
+ return -1;
+ }
+ return static_cast(tarDate);
+}
}
}
\ 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 cb9ec0d..a954957 100644
--- a/services/packagegroup/include/bundle_active_group_handler.h
+++ b/services/packagegroup/include/bundle_active_group_handler.h
@@ -48,7 +48,7 @@ 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 = TEN_MINUTE;
+ static const int CHECK_IDLE_INTERVAL = ONE_MINUTE;
private:
std::shared_ptr bundleActiveGroupController_;
diff --git a/services/packageusage/include/bundle_active_stats_update_listener.h b/services/packageusage/include/bundle_active_stats_update_listener.h
index 5f0b3b8..6968b6c 100644
--- a/services/packageusage/include/bundle_active_stats_update_listener.h
+++ b/services/packageusage/include/bundle_active_stats_update_listener.h
@@ -19,7 +19,7 @@
namespace OHOS {
namespace DeviceUsageStats {
class BundleActiveStatsUpdateListener {
- virtual void OnStatsChanged() = 0;
+ virtual void OnStatsChanged(const int userId) = 0;
virtual void OnStatsReload() = 0;
virtual void OnSystemUpdate(int userId) = 0;
};
diff --git a/services/packageusage/include/bundle_active_user_service.h b/services/packageusage/include/bundle_active_user_service.h
index 1f4dfcf..d7ad255 100644
--- a/services/packageusage/include/bundle_active_user_service.h
+++ b/services/packageusage/include/bundle_active_user_service.h
@@ -44,9 +44,9 @@ public:
}
void Init(const int64_t timeStamp);
~BundleActiveUserService() {};
- void ReportForFlushAndShutdown(const BundleActiveEvent& event);
+ void ReportForShutdown(const BundleActiveEvent& event);
void ReportEvent(const BundleActiveEvent& event);
- void RestoreStats();
+ void RestoreStats(bool forced);
void RenewStatsInMemory(const int64_t timeStamp);
void RenewTableTime(int64_t oldTime, int64_t newTime);
void OnUserRemoved();
@@ -57,6 +57,7 @@ public:
const int64_t endTime, const int userId, const std::string& bundleName);
std::vector QueryEvents(const int64_t beginTime, const int64_t endTime, const int userId,
const std::string& bundleName);
+ void LoadActiveStats(const int64_t timeStamp, const bool& force);
private:
static const int64_t ONE_SECOND_MILLISECONDS = 1000;
@@ -68,7 +69,6 @@ private:
inline static const std::vector PERIOD_LENGTH = {BundleActiveCalendar::DAY_MILLISECONDS,
BundleActiveCalendar::WEEK_MILLISECONDS, BundleActiveCalendar::MONTH_MILLISECONDS,
BundleActiveCalendar::YEAR_MILLISECONDS};
- void LoadActiveStats(const int64_t timeStamp, const bool& force);
void NotifyStatsChanged();
void NotifyNewUpdate();
void printstat();
diff --git a/services/packageusage/src/bundle_active_package_stats.cpp b/services/packageusage/src/bundle_active_package_stats.cpp
index 01048a2..c297264 100644
--- a/services/packageusage/src/bundle_active_package_stats.cpp
+++ b/services/packageusage/src/bundle_active_package_stats.cpp
@@ -24,7 +24,7 @@ BundleActivePackageStats::BundleActivePackageStats()
endTimeStamp_ = 0; // stop time of counting
lastTimeUsed_ = 0; // the timestamp of last launch
totalInFrontTime_ = 0; // the total time of bundle in front.
- lastContiniousTaskUsed_ = 0; // the timestamp of bundle calling a continuous task.
+ lastContiniousTaskUsed_ = -1; // the timestamp of bundle calling a continuous task.
totalContiniousTaskUsedTime_ = 0; // the total time of bundle use continuous tasks.
startCount_ = 0;
bundleStartedCount_ = 0;
diff --git a/services/packageusage/src/bundle_active_report_handler.cpp b/services/packageusage/src/bundle_active_report_handler.cpp
index 87b1496..d02a40d 100644
--- a/services/packageusage/src/bundle_active_report_handler.cpp
+++ b/services/packageusage/src/bundle_active_report_handler.cpp
@@ -50,7 +50,9 @@ void BundleActiveReportHandler::ProcessEvent(const AppExecFwk::InnerEvent::Point
}
case MSG_FLUSH_TO_DISK: {
BUNDLE_ACTIVE_LOGI("FLUSH TO DISK HANDLE");
- bundleActiveCore_->RestoreToDatabase();
+ auto ptrToHandlerobj = event->GetSharedObject();
+ BundleActiveReportHandlerObject tmpHandlerobj = *ptrToHandlerobj;
+ bundleActiveCore_->RestoreToDatabase(tmpHandlerobj.userId_);
break;
}
case MSG_REMOVE_USER: {
diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp
index cdc1639..ae3abd4 100644
--- a/services/packageusage/src/bundle_active_user_service.cpp
+++ b/services/packageusage/src/bundle_active_user_service.cpp
@@ -64,9 +64,8 @@ void BundleActiveUserService::DeleteUninstalledBundleStats(const std::string& bu
void BundleActiveUserService::RenewTableTime(int64_t oldTime, int64_t newTime)
{
BUNDLE_ACTIVE_LOGI("BundleActiveUserService::RenewTableTime called");
- RestoreStats();
+ BUNDLE_ACTIVE_LOGI("BundleActiveUserService::RenewTableTime called current event size is %{public}d", currentStats_[0]->events_.Size());
database_.RenewTableTime(newTime - oldTime);
- LoadActiveStats(newTime, true);
}
void BundleActiveUserService::NotifyStatsChanged()
@@ -74,7 +73,7 @@ void BundleActiveUserService::NotifyStatsChanged()
if (!statsChanged_) {
BUNDLE_ACTIVE_LOGI("BundleActiveUserService::NotifyStatsChanged() set stats changed to true");
statsChanged_ = true;
- listener_.OnStatsChanged();
+ listener_.OnStatsChanged(userId_);
}
}
@@ -136,10 +135,10 @@ void BundleActiveUserService::ReportEvent(const BundleActiveEvent& event)
NotifyStatsChanged();
}
-void BundleActiveUserService::ReportForFlushAndShutdown(const BundleActiveEvent& event)
+void BundleActiveUserService::ReportForShutdown(const BundleActiveEvent& event)
{
- BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportForFlushAndShutdown() called");
- if (event.eventId_ != BundleActiveEvent::FLUSH && event.eventId_ != BundleActiveEvent::SHUTDOWN) {
+ BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportForShutdown() called");
+ if (event.eventId_ != BundleActiveEvent::SHUTDOWN) {
return;
}
if (event.eventId_ == BundleActiveEvent::SHUTDOWN) {
@@ -153,17 +152,20 @@ void BundleActiveUserService::ReportForFlushAndShutdown(const BundleActiveEvent&
it->Update(event.bundleName_, event.continuousTaskAbilityName_, event.timeStamp_, event.eventId_,
event.abilityId_);
}
- BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportForFlushAndShutdown called notify");
+ BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportForShutdown called notify");
NotifyStatsChanged();
}
-void BundleActiveUserService::RestoreStats()
+void BundleActiveUserService::RestoreStats(bool forced)
{
- BUNDLE_ACTIVE_LOGI("BundleActiveUserService::RestoreStats() called");
- if (statsChanged_) {
+ BUNDLE_ACTIVE_LOGI("BundleActiveUserService::RestoreStats() called, userId is %{public}d", userId_);
+ if (statsChanged_ || forced) {
BUNDLE_ACTIVE_LOGI("BundleActiveUserService::RestoreStats() stat changed is true");
for (int i = 0; i < currentStats_.size(); i++) {
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;
@@ -203,6 +205,9 @@ void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const boo
currentStats_[intervalType]->beginTime_ = tmpCalendar.GetMilliseconds();
currentStats_[intervalType]->endTime_ = timeStamp;
}
+ for (auto it : currentStats_) {
+ BUNDLE_ACTIVE_LOGI("loadactive current begin time is %{public}lld", it->beginTime_);
+ }
statsChanged_ = false;
// 延长统计时间到第二天0点
dailyExpiryDate_.SetMilliseconds(timeStamp);
@@ -241,7 +246,7 @@ void BundleActiveUserService::RenewStatsInMemory(const int64_t timeStamp)
}
(*it)->CommitTime(dailyExpiryDate_.GetMilliseconds() - 1);
}
- RestoreStats();
+ RestoreStats(true);
database_.RemoveOldData(timeStamp);
LoadActiveStats(timeStamp, false); // 新建intervalstat或加载当前数据库数据
for (std::string continueBundleName : continueBundles) { // 更新所有事件的时间戳到新的begintime
@@ -260,10 +265,9 @@ void BundleActiveUserService::RenewStatsInMemory(const int64_t timeStamp)
(*itInterval)->Update(continueBundleName, it->first, beginTime, it->second, "");
}
}
- NotifyStatsChanged();
}
}
- RestoreStats();
+ RestoreStats(true);
}
std::vector BundleActiveUserService::QueryPackageStats(int intervalType,
@@ -300,7 +304,7 @@ std::vector BundleActiveUserService::QueryPackageStats
}
int64_t truncatedEndTime = std::min(currentStats->beginTime_, endTime);
- BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryPackageStats bundle name is %{public}s", bundleName.c_str());
+ BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryPackageStats bundle name is %{public}s, truncatedEndTime IS %{public}lld, begin time is %{public}lld", bundleName.c_str(), truncatedEndTime, currentStats->beginTime_);
result = database_.QueryDatabaseUsageStats(intervalType, beginTime, truncatedEndTime, userId);
BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryPackageStats is %{public}d", result.size());
// if we need a in-memory stats, combine current stats with result from database.
@@ -339,6 +343,7 @@ std::vector BundleActiveUserService::QueryEvents(const int64_
}
BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryEvents 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());
// if we need a in-memory stats, combine current stats with result from database.
if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) {
BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryEvents need in memory stats");
--
Gitee
From 0437cfb72315fa504f761e70416014d88735bc6f Mon Sep 17 00:00:00 2001
From: wyuanchao
Date: Thu, 3 Mar 2022 21:49:48 +0800
Subject: [PATCH 11/32] modify log info
Signed-off-by: wyuanchao
---
BUILD.gn | 9 ++-
frameworks/src/bundle_state_common.cpp | 52 +++++++++++++---
frameworks/src/bundle_state_query.cpp | 16 +----
.../napi/include/bundle_state_common.h | 14 +++--
.../napi/include/bundle_state_data.h | 3 +-
services/common/include/bundle_active_log.h | 60 ++++++++++++++++---
services/common/src/bundle_active_log.cpp | 43 +++++++++++++
.../src/bundle_active_open_callback.cpp | 4 +-
.../src/bundle_active_usage_database.cpp | 35 ++++++-----
9 files changed, 182 insertions(+), 54 deletions(-)
create mode 100644 services/common/src/bundle_active_log.cpp
diff --git a/BUILD.gn b/BUILD.gn
index 7a44408..cf37d4b 100644
--- a/BUILD.gn
+++ b/BUILD.gn
@@ -41,6 +41,9 @@ ohos_shared_library("usagestatsinner") {
"samgr_standard:samgr_proxy",
"utils_base:utils",
]
+
+ deps = [ ":usagestatservice" ]
+
part_name = "${device_usage_statistics_part_name}"
subsystem_name = "resourceschedule"
}
@@ -65,7 +68,10 @@ ohos_shared_library("bundlestate") {
"services/packageusage/include",
]
- deps = [ "//foundation/resourceschedule/${device_usage_statistics_part_name}:usagestatsinner" ]
+ deps = [
+ ":usagestatservice",
+ ":usagestatsinner",
+ ]
external_deps = [
"dmsfwk_standard:zuri",
@@ -87,6 +93,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_log.cpp",
"services/common/src/bundle_active_open_callback.cpp",
"services/common/src/bundle_active_service.cpp",
"services/common/src/bundle_active_shutdown_callback_proxy.cpp",
diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp
index b4908dc..51ca1e9 100644
--- a/frameworks/src/bundle_state_common.cpp
+++ b/frameworks/src/bundle_state_common.cpp
@@ -13,6 +13,7 @@
* limitations under the License.
*/
+#include
#include "securec.h"
#include "bundle_active_log.h"
@@ -109,28 +110,28 @@ void BundleStateCommon::GetBundleStateInfoByIntervalForResult(
}
}
-void BundleStateCommon::GetBundleStateInfoForResult(
- napi_env env, const std::vector &packageStats, napi_value result)
+void BundleStateCommon::GetBundleStateInfoForResult(napi_env env,
+ const std::shared_ptr> &packageStats, napi_value result)
{
- for (const auto &item : packageStats) {
+ for (const auto &item : *packageStats) {
napi_value packageObject = nullptr;
NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &packageObject));
napi_value bundleName = nullptr;
NAPI_CALL_RETURN_VOID(
- env, napi_create_string_utf8(env, item.bundleName_.c_str(), NAPI_AUTO_LENGTH, &bundleName));
+ env, napi_create_string_utf8(env, item.second.bundleName_.c_str(), NAPI_AUTO_LENGTH, &bundleName));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "bundleName", bundleName));
napi_value abilityPrevAccessTime = nullptr;
- NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.lastTimeUsed_, &abilityPrevAccessTime));
+ NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.second.lastTimeUsed_, &abilityPrevAccessTime));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityPrevAccessTime",
abilityPrevAccessTime));
napi_value abilityInFgTotalTime = nullptr;
- NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.totalInFrontTime_, &abilityInFgTotalTime));
+ NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.second.totalInFrontTime_, &abilityInFgTotalTime));
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityInFgTotalTime",
abilityInFgTotalTime));
- NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, item.bundleName_.c_str(), packageObject));
+ NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, item.first.c_str(), packageObject));
}
}
@@ -236,5 +237,42 @@ void BundleStateCommon::SettingCallbackPromiseInfo(
info.isCallback = false;
}
}
+
+std::shared_ptr> BundleStateCommon::GetPackageStats(
+ int64_t &beginTime, int64_t &endTime)
+{
+ std::vector packageStats =
+ BundleActiveClient::GetInstance().QueryPackageStats(INTERVAL_TYPE_DEFAULT, beginTime, endTime);
+ std::shared_ptr> mergedPackageStats =
+ std::make_shared>();
+ if (packageStats.empty()) {
+ return nullptr;
+ }
+ for (auto packageStat : packageStats) {
+ std::map::iterator iter =
+ mergedPackageStats->find(packageStat.bundleName_);
+ if (iter != mergedPackageStats->end()) {
+ MergePackageStats(iter->second, packageStat);
+ } else {
+ mergedPackageStats->
+ insert(std::pair(packageStat.bundleName_, packageStat));
+ }
+ }
+ return mergedPackageStats;
+}
+
+void BundleStateCommon::MergePackageStats(BundleActivePackageStats &left, const BundleActivePackageStats &right)
+{
+ if (left.bundleName_ != right.bundleName_) {
+ BUNDLE_ACTIVE_LOGE("Merge package stats failed, existing packageName : %{public}s,"
+ " new packageName : %{public}s,", left.bundleName_.c_str(), right.bundleName_.c_str());
+ return;
+ }
+ left.lastTimeUsed_ = std::max(left.lastTimeUsed_, right.lastTimeUsed_);
+ left.lastContiniousTaskUsed_ = std::max(left.lastContiniousTaskUsed_, right.lastContiniousTaskUsed_);
+ left.totalInFrontTime_ += right.totalInFrontTime_;
+ left.totalContiniousTaskUsedTime_ += right.totalContiniousTaskUsedTime_;
+ left.bundleStartedCount_ += right.bundleStartedCount_;
+}
} // namespace DeviceUsageStats
} // namespace OHOS
\ No newline at end of file
diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp
index a00cded..75a97be 100644
--- a/frameworks/src/bundle_state_query.cpp
+++ b/frameworks/src/bundle_state_query.cpp
@@ -17,9 +17,7 @@
#include "bundle_state_common.h"
#include "bundle_active_log.h"
-#include "bundle_active_client.h"
#include "bundle_state_data.h"
-#include "bundle_state_query.h"
namespace OHOS {
namespace DeviceUsageStats {
@@ -522,7 +520,6 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info)
if (ParseAppUsageParameters(env, info, params) == nullptr) {
return BundleStateCommon::JSParaError(env, params.callback);
}
-
napi_value promise = nullptr;
AsyncCallbackInfoAppUsage *asyncCallbackInfo =
new (std::nothrow) AsyncCallbackInfoAppUsage {.env = env, .asyncWork = nullptr};
@@ -536,10 +533,8 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info)
BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos asyncCallbackInfo->endTime: %{public}lld",
asyncCallbackInfo->endTime);
BundleStateCommon::SettingCallbackPromiseInfo(env, params.callback, asyncCallbackInfo->info, promise);
-
napi_value resourceName = nullptr;
napi_create_string_latin1(env, "QueryBundleStateInfos", NAPI_AUTO_LENGTH, &resourceName);
-
napi_create_async_work(env,
nullptr,
resourceName,
@@ -548,10 +543,9 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info)
AsyncCallbackInfoAppUsage *asyncCallbackInfo = (AsyncCallbackInfoAppUsage *)data;
if (asyncCallbackInfo != nullptr) {
asyncCallbackInfo->packageStats =
- BundleActiveClient::GetInstance().QueryPackageStats(INTERVAL_TYPE_DEFAULT,
- asyncCallbackInfo->beginTime, asyncCallbackInfo->endTime);
+ BundleStateCommon::GetPackageStats(asyncCallbackInfo->beginTime, asyncCallbackInfo->endTime);
} else {
- BUNDLE_ACTIVE_LOGE("QueryBundleStateInfos, asyncCallbackInfo == nullptr");
+ BUNDLE_ACTIVE_LOGE("QueryBundleStateInfos asyncCallbackInfo == nullptr");
}
BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos worker pool thread execute end.");
},
@@ -559,14 +553,12 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info)
AsyncCallbackInfoAppUsage *asyncCallbackInfo = (AsyncCallbackInfoAppUsage *)data;
if (asyncCallbackInfo != nullptr) {
napi_value result = nullptr;
- napi_create_array(env, &result);
+ napi_create_object(env, &result);
BundleStateCommon::GetBundleStateInfoForResult(env, asyncCallbackInfo->packageStats, result);
BundleStateCommon::GetCallbackPromiseResult(env, asyncCallbackInfo->info, result);
-
if (asyncCallbackInfo->info.callback != nullptr) {
napi_delete_reference(env, asyncCallbackInfo->info.callback);
}
-
napi_delete_async_work(env, asyncCallbackInfo->asyncWork);
delete asyncCallbackInfo;
asyncCallbackInfo = nullptr;
@@ -574,9 +566,7 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info)
},
(void *)asyncCallbackInfo,
&asyncCallbackInfo->asyncWork);
-
NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork));
-
if (asyncCallbackInfo->info.isCallback) {
return BundleStateCommon::NapiGetNull(env);
} else {
diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h
index ce44bee..f31a690 100644
--- a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h
+++ b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h
@@ -16,11 +16,11 @@
#ifndef FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_COMMON_H
#define FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_COMMON_H
-#include
-
+#include "bundle_active_client.h"
+#include "bundle_state_data.h"
+#include "bundle_state_query.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
-#include "bundle_state_data.h"
namespace OHOS {
namespace DeviceUsageStats {
@@ -50,8 +50,8 @@ public:
static void GetBundleStateInfoByIntervalForResult(
napi_env env, const std::vector &packageStats, napi_value result);
- static void GetBundleStateInfoForResult(
- napi_env env, const std::vector &packageStats, napi_value result);
+ static void GetBundleStateInfoForResult(napi_env env,
+ const std::shared_ptr> &packageStats, napi_value result);
static void SetPromiseInfo(const napi_env &env, const napi_deferred &deferred, const napi_value &result);
@@ -62,6 +62,10 @@ public:
static napi_value GetInt64NumberValue(const napi_env &env, const napi_value &value, int64_t &result);
static napi_value GetInt32NumberValue(const napi_env &env, const napi_value &value, int32_t &result);
+
+ static std::shared_ptr> GetPackageStats(int64_t &beginTime, int64_t &endTime);
+
+ static void MergePackageStats(BundleActivePackageStats &left, const BundleActivePackageStats &right);
};
} // namespace DeviceUsageStats
} // namespace OHOS
diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h
index a44f85b..c854436 100644
--- a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h
+++ b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h
@@ -16,6 +16,7 @@
#ifndef FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_DATA_H
#define FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_DATA_H
+#include