From 6b2434fcf95eaed652f8a7454d84cd9555746c3d Mon Sep 17 00:00:00 2001 From: laiguizhong Date: Tue, 10 May 2022 19:10:03 +0800 Subject: [PATCH 01/83] =?UTF-8?q?=E4=BF=AE=E6=94=B9BUILD.gn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: laiguizhong --- BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILD.gn b/BUILD.gn index 4eea17e..1c025f9 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -144,7 +144,7 @@ ohos_shared_library("usagestatservice") { "power_manager_native:powermgr_client", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", - "startup_l2:syspara", + "init:libbegetutil", "time_native:time_service", "utils_base:utils", ] -- Gitee From d588553d38ebab0b2bee2d468bf9f63a50b3a73a Mon Sep 17 00:00:00 2001 From: houdisheng Date: Thu, 12 May 2022 09:41:21 +0800 Subject: [PATCH 02/83] =?UTF-8?q?=E8=AE=BE=E5=A4=87=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E4=BF=A1=E6=81=AF=E7=BB=9F=E8=AE=A1=E9=99=8D=E6=9D=83=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- init/device_usage_statistics_service.cfg | 7 ++++--- services/common/include/bundle_active_constant.h | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/init/device_usage_statistics_service.cfg b/init/device_usage_statistics_service.cfg index 193ac5d..034df8a 100644 --- a/init/device_usage_statistics_service.cfg +++ b/init/device_usage_statistics_service.cfg @@ -2,6 +2,7 @@ "jobs" : [{ "name" : "post-fs-data", "cmds" : [ + "mkdir /data/service/el1/public/bundle_usage 0711 device_usage_stats device_usage_stats", "start device_usage_stats_service" ] } @@ -9,9 +10,9 @@ "services" : [{ "name" : "device_usage_stats_service", "path" : ["/system/bin/sa_main", "/system/profile/device_usage_stats_service.xml"], - "uid" : "system", - "gid" : ["system", "shell"], - "secon" : "u:r:device_usage_stats_service:s0" + "uid" : "device_usage_stats", + "gid" : ["device_usage_stats", "shell"] + "apl" : "system_basic" } ] } \ No newline at end of file diff --git a/services/common/include/bundle_active_constant.h b/services/common/include/bundle_active_constant.h index e20b850..82bf37e 100644 --- a/services/common/include/bundle_active_constant.h +++ b/services/common/include/bundle_active_constant.h @@ -121,7 +121,7 @@ const std::string BUNDLE_ACTIVE_DB_BUNDLE_DAILY_TIMEOUT_TIME = "bundleDailyTimeo const std::string BUNDLE_ACTIVE_DB_BOOT_BASED_DURATION = "bootBasedDuration"; 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_DATABASE_DIR = "/data/service/el1/public/bundle_usage/"; const std::string BUNDLE_ACTIVE_VERSION_FILE = "/version"; const std::string DATABASE_FILE_TABLE_NAME = "table"; const std::string SQLITE_MASTER_NAME = "name"; -- Gitee From c11e1feed9fe80c29d528254a063757f23a68879 Mon Sep 17 00:00:00 2001 From: dy_study Date: Mon, 16 May 2022 14:14:57 +0800 Subject: [PATCH 03/83] =?UTF-8?q?IssueNo:#I57IWN=20Description:ability=5Fb?= =?UTF-8?q?ase=E7=9B=AE=E5=BD=95=E6=95=B4=E6=94=B9=E5=8F=8A=E5=91=A8?= =?UTF-8?q?=E8=BE=B9=E5=AD=90=E7=B3=BB=E7=BB=9F=E4=BE=9D=E8=B5=96=E6=A0=87?= =?UTF-8?q?=E5=87=86=E5=8C=96=20Sig:SIG=5FApplicationFramework=20Feature?= =?UTF-8?q?=20or=20Bugfix:Feature=20Binary=20Source:=20No?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: dy_study Change-Id: I60a22368ebe99ba77aa2aa97203c9f629d242d27 --- BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/BUILD.gn b/BUILD.gn index 4eea17e..5214e26 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -128,6 +128,7 @@ ohos_shared_library("usagestatservice") { ] external_deps = [ + "ability_base:configuration", "ability_base:want", "ability_runtime:app_manager", "ability_runtime:wantagent_innerkits", -- Gitee From 521e065c029059b5ab518fe4263df85d980095b5 Mon Sep 17 00:00:00 2001 From: houdisheng Date: Mon, 16 May 2022 17:21:46 +0800 Subject: [PATCH 04/83] =?UTF-8?q?=E5=8E=BB=E9=99=A4apl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- init/device_usage_statistics_service.cfg | 1 - 1 file changed, 1 deletion(-) diff --git a/init/device_usage_statistics_service.cfg b/init/device_usage_statistics_service.cfg index 034df8a..b4f759b 100644 --- a/init/device_usage_statistics_service.cfg +++ b/init/device_usage_statistics_service.cfg @@ -12,7 +12,6 @@ "path" : ["/system/bin/sa_main", "/system/profile/device_usage_stats_service.xml"], "uid" : "device_usage_stats", "gid" : ["device_usage_stats", "shell"] - "apl" : "system_basic" } ] } \ No newline at end of file -- Gitee From 1d204343e06e4c53a363a587e575f97c0d809387 Mon Sep 17 00:00:00 2001 From: houdisheng Date: Mon, 16 May 2022 17:42:31 +0800 Subject: [PATCH 05/83] =?UTF-8?q?=E5=8E=BB=E9=99=A4apl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- init/device_usage_statistics_service.cfg | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/init/device_usage_statistics_service.cfg b/init/device_usage_statistics_service.cfg index b4f759b..fe22484 100644 --- a/init/device_usage_statistics_service.cfg +++ b/init/device_usage_statistics_service.cfg @@ -11,7 +11,9 @@ "name" : "device_usage_stats_service", "path" : ["/system/bin/sa_main", "/system/profile/device_usage_stats_service.xml"], "uid" : "device_usage_stats", - "gid" : ["device_usage_stats", "shell"] + "gid" : ["device_usage_stats", "shell"], + "secon" : "u:r:device_usage_stats_service:s0", + "apl" : "system_basic" } ] } \ No newline at end of file -- Gitee From 88e5ce82093202d92c94354812ed500d17f3c164 Mon Sep 17 00:00:00 2001 From: laiguizhong Date: Mon, 16 May 2022 19:29:41 +0800 Subject: [PATCH 06/83] =?UTF-8?q?=E4=BF=AE=E6=94=B9BUILD.gn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: laiguizhong --- BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILD.gn b/BUILD.gn index 1c025f9..94ded09 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -138,13 +138,13 @@ ohos_shared_library("usagestatservice") { "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", + "init:libbegetutil", "ipc:ipc_core", "native_appdatamgr:native_rdb", "permission_standard:libpermissionsdk_standard", "power_manager_native:powermgr_client", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", - "init:libbegetutil", "time_native:time_service", "utils_base:utils", ] -- Gitee From 4035f2bece01868d5cb2e837445228d19f24fcb9 Mon Sep 17 00:00:00 2001 From: PaDaBoo Date: Tue, 17 May 2022 23:13:55 +0800 Subject: [PATCH 07/83] =?UTF-8?q?appdatamgr=E9=83=A8=E4=BB=B6=E5=88=86?= =?UTF-8?q?=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: PaDaBoo --- BUILD.gn | 2 +- README.md | 2 +- test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/BUILD.gn b/BUILD.gn index 4eea17e..bf8e535 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -139,7 +139,7 @@ ohos_shared_library("usagestatservice") { "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "native_appdatamgr:native_rdb", + "relational_store:native_rdb", "permission_standard:libpermissionsdk_standard", "power_manager_native:powermgr_client", "safwk:system_ability_fwk", diff --git a/README.md b/README.md index f28be98..b0efeab 100644 --- a/README.md +++ b/README.md @@ -97,4 +97,4 @@ resource_schedule_service appexecfwk_standard -native_appdatamgr \ No newline at end of file +relational_store \ No newline at end of file diff --git a/test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn b/test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn index 9ee599a..c64a734 100644 --- a/test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn +++ b/test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn @@ -54,7 +54,7 @@ ohos_fuzztest("BundleActiveOnRemoteRequestFuzzTest") { "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "native_appdatamgr:native_rdb", + "relational_store:native_rdb", "permission_standard:libpermissionsdk_standard", "power_manager_native:powermgr_client", "safwk:system_ability_fwk", -- Gitee From aaf3de1e15968c664b8e82fb04d0d9b772786bea Mon Sep 17 00:00:00 2001 From: houdisheng Date: Wed, 18 May 2022 14:32:30 +0800 Subject: [PATCH 08/83] =?UTF-8?q?=E5=88=A0=E9=99=A4CheckIsSystemAppByUid?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E8=B0=83=E7=94=A8=EF=BC=8C=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E5=86=97=E4=BD=99=E5=8F=98=E9=87=8F=E8=B5=8B=E5=80=BC?= 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 | 11 +++-------- .../src/bundle_active_group_controller.cpp | 1 - 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 08754af..d211889 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -458,20 +458,15 @@ bool BundleActiveService::CheckBundleIsSystemAppAndHasPermission(const int32_t u } std::string bundleName = ""; sptrBundleMgr_->GetBundleNameForUid(uid, bundleName); - bool bundleIsSystemApp = sptrBundleMgr_->CheckIsSystemAppByUid(uid); int32_t bundleHasPermission = AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, NEEDED_PERMISSION); - if (!bundleIsSystemApp) { - errCode = BUNDLE_ACTIVE_FAIL; - BUNDLE_ACTIVE_LOGE("%{public}s is not system app", bundleName.c_str()); - return false; - } else if (bundleHasPermission != 0) { + 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); + BUNDLE_ACTIVE_LOGI(" %{public}s has permission %{public}d", + bundleName.c_str(), bundleHasPermission); return true; } } diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index 119dd47..2340866 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -298,7 +298,6 @@ void BundleActiveGroupController::CheckAndUpdateGroup(const std::string& bundleN 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_ > -- Gitee From fa50eba0d19a866dbcf12871b1137f5973175e4c Mon Sep 17 00:00:00 2001 From: PaDaBoo Date: Wed, 18 May 2022 15:39:14 +0800 Subject: [PATCH 09/83] =?UTF-8?q?appdatamgr=E9=83=A8=E4=BB=B6=E5=88=86?= =?UTF-8?q?=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: PaDaBoo --- BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILD.gn b/BUILD.gn index bf8e535..e07be7c 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -139,9 +139,9 @@ ohos_shared_library("usagestatservice") { "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "relational_store:native_rdb", "permission_standard:libpermissionsdk_standard", "power_manager_native:powermgr_client", + "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "startup_l2:syspara", -- Gitee From a139634b4a062224c0c21b74e5c376e761d1e97f Mon Sep 17 00:00:00 2001 From: PaDaBoo Date: Wed, 18 May 2022 15:52:32 +0800 Subject: [PATCH 10/83] =?UTF-8?q?appdatamgr=E9=83=A8=E4=BB=B6=E5=88=86?= =?UTF-8?q?=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: PaDaBoo --- test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn b/test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn index c64a734..45aaa50 100644 --- a/test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn +++ b/test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn @@ -54,9 +54,9 @@ ohos_fuzztest("BundleActiveOnRemoteRequestFuzzTest") { "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "relational_store:native_rdb", "permission_standard:libpermissionsdk_standard", "power_manager_native:powermgr_client", + "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", "startup_l2:syspara", -- Gitee From f9475809e6684ae299061713fdb0b0c98cb78c85 Mon Sep 17 00:00:00 2001 From: vampire_z Date: Mon, 23 May 2022 14:33:20 +0800 Subject: [PATCH 11/83] SA init optimize in fuzz testcase Signed-off-by: vampire_z --- .../bundleactiveonremoterequest_fuzzer.cpp | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/test/fuzztest/bundleactiveonremoterequest_fuzzer/bundleactiveonremoterequest_fuzzer.cpp b/test/fuzztest/bundleactiveonremoterequest_fuzzer/bundleactiveonremoterequest_fuzzer.cpp index d2b6394..e97c7e1 100644 --- a/test/fuzztest/bundleactiveonremoterequest_fuzzer/bundleactiveonremoterequest_fuzzer.cpp +++ b/test/fuzztest/bundleactiveonremoterequest_fuzzer/bundleactiveonremoterequest_fuzzer.cpp @@ -26,24 +26,26 @@ namespace OHOS { namespace DeviceUsageStats { constexpr int32_t MIN_LEN = 4; constexpr int32_t MAX_CODE_TEST = 15; // current max code is 9 + static bool isInited = false; - void DoInit() + bool DoInit() { auto instance = DelayedSingleton::GetInstance(); if (!instance->runner_) { instance->runner_ = AppExecFwk::EventRunner::Create("device_usage_stats_init_handler"); } if (!instance->runner_) { - return; + return false; } if (!instance->handler_) { instance->handler_ = std::make_shared(instance->runner_); } if (!instance->handler_) { - return; + return false; } instance->InitNecessaryState(); + return true; } int32_t OnRemoteRequest(uint32_t code, MessageParcel& data) @@ -75,9 +77,12 @@ namespace DeviceUsageStats { dataMessageParcel.WriteBuffer(data + sizeof(uint32_t), size); dataMessageParcel.RewindRead(0); - DoInit(); - OnRemoteRequest(code, dataMessageParcel); - DelayedSingleton::GetInstance()->OnStop(); + if (!isInited) { + isInited = DoInit(); + } + if (isInited) { + OnRemoteRequest(code, dataMessageParcel); + } } } // namespace DeviceUsageStats } // namespace OHOS -- Gitee From 7ddf50aec23e855bb6d063bb2022f6ed49aee2fd Mon Sep 17 00:00:00 2001 From: houdisheng Date: Thu, 26 May 2022 15:05:41 +0800 Subject: [PATCH 12/83] =?UTF-8?q?=E4=BF=AE=E6=94=B9BundleActiveUserService?= =?UTF-8?q?=E4=B8=ADlistener=5F=E5=AE=9A=E4=B9=89=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- services/common/include/bundle_active_core.h | 2 +- services/common/src/bundle_active_core.cpp | 2 +- .../include/bundle_active_user_service.h | 4 ++-- .../packageusage/src/bundle_active_user_service.cpp | 12 +++++++++--- 4 files changed, 13 insertions(+), 7 deletions(-) diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 3c861ce..a955ed1 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -46,7 +46,7 @@ public: class BundleActiveReportHandler; -class BundleActiveCore : public BundleActiveStatsUpdateListener { +class BundleActiveCore : public BundleActiveStatsUpdateListener, public std::enable_shared_from_this{ public: BundleActiveCore(); virtual ~BundleActiveCore(); diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 15dcdc5..f9ee8ca 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -194,7 +194,7 @@ std::shared_ptr BundleActiveCore::GetUserDataAndInitial 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, + std::shared_ptr service = std::make_shared(userId, shared_from_this(), debug); if (service == nullptr) { return nullptr; diff --git a/services/packageusage/include/bundle_active_user_service.h b/services/packageusage/include/bundle_active_user_service.h index cb56fc9..e2692bd 100644 --- a/services/packageusage/include/bundle_active_user_service.h +++ b/services/packageusage/include/bundle_active_user_service.h @@ -35,7 +35,7 @@ class BundleActiveCore; class BundleActiveUserService { public: BundleActiveUserService() = delete; - BundleActiveUserService(const int32_t userId, BundleActiveCore& listener, const bool debug):listener_(listener) + BundleActiveUserService(const int32_t userId, std::shared_ptr listener, const bool debug):listener_(listener) { for (int32_t i = 0; i < BundleActivePeriodStats::PERIOD_COUNT; i++) { currentStats_.push_back(nullptr); @@ -82,7 +82,7 @@ private: bool statsChanged_; bool debugUserService_; std::string lastForegroundBundle_; - BundleActiveCore& listener_; + std::weak_ptr listener_; std::vector periodLength_ = {0, 0, 0, 0}; void NotifyStatsChanged(); void NotifyNewUpdate(); diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index c79f1d6..d032480 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -85,13 +85,17 @@ void BundleActiveUserService::NotifyStatsChanged() if (!statsChanged_) { BUNDLE_ACTIVE_LOGI("NotifyStatsChanged() set stats changed to true"); statsChanged_ = true; - listener_.OnStatsChanged(userId_); + if (!listener_.expired()) { + listener_.lock()->OnStatsChanged(userId_); + } } } void BundleActiveUserService::NotifyNewUpdate() { - listener_.OnSystemUpdate(userId_); + if (!listener_.expired()) { + listener_.lock()->OnSystemUpdate(userId_); + } } void BundleActiveUserService::ReportEvent(const BundleActiveEvent& event) @@ -237,7 +241,9 @@ void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const boo if (!timeChanged) { dailyExpiryDate_.TruncateToDay(); } - listener_.OnStatsReload(); + if (!listener_.expired()) { + listener_.lock()->CheckTimeChangeAndGetWallTime(); + } BUNDLE_ACTIVE_LOGI("LoadActiveStats current expire time is %{public}lld, " "begin time is %{public}lld", (long long)dailyExpiryDate_.GetMilliseconds(), (long long)tmpCalendar.GetMilliseconds()); -- Gitee From d6aef41649d915a87546bdbd7209e853d52dbace Mon Sep 17 00:00:00 2001 From: houdisheng Date: Thu, 26 May 2022 15:24:50 +0800 Subject: [PATCH 13/83] CODEX Signed-off-by: houdisheng --- services/common/include/bundle_active_core.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index a955ed1..32758b0 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -46,7 +46,7 @@ public: class BundleActiveReportHandler; -class BundleActiveCore : public BundleActiveStatsUpdateListener, public std::enable_shared_from_this{ +class BundleActiveCore : public BundleActiveStatsUpdateListener, public std::enable_shared_from_this { public: BundleActiveCore(); virtual ~BundleActiveCore(); -- Gitee From 22897186a413f1330aac8708bb1a04df07541497 Mon Sep 17 00:00:00 2001 From: houdisheng Date: Thu, 26 May 2022 21:01:19 +0800 Subject: [PATCH 14/83] =?UTF-8?q?=E5=85=B3=E9=97=ADdb=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- services/common/include/bundle_active_constant.h | 2 +- services/common/include/bundle_active_core.h | 2 +- services/common/src/bundle_active_core.cpp | 2 +- .../include/bundle_active_user_service.h | 4 ++-- .../packageusage/src/bundle_active_user_service.cpp | 12 +++--------- 5 files changed, 8 insertions(+), 14 deletions(-) diff --git a/services/common/include/bundle_active_constant.h b/services/common/include/bundle_active_constant.h index 82bf37e..35c5dd6 100644 --- a/services/common/include/bundle_active_constant.h +++ b/services/common/include/bundle_active_constant.h @@ -126,7 +126,7 @@ const std::string BUNDLE_ACTIVE_VERSION_FILE = "/version"; const std::string DATABASE_FILE_TABLE_NAME = "table"; const std::string SQLITE_MASTER_NAME = "name"; const std::string DATABASE_TYPE[] = {"daily", "weekly", "monthly", "yearly", "event", "usageGroup"}; -const std::string SUFFIX_TYPE[] = {".db", ".db-shm", ".db-wal"}; +const std::string SUFFIX_TYPE[] = {".db"}; } // namespace DeviceUsageStats } // namespace OHOS #endif // BUNDLE_ACTIVE_CONSTANT_H diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 32758b0..3c861ce 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -46,7 +46,7 @@ public: class BundleActiveReportHandler; -class BundleActiveCore : public BundleActiveStatsUpdateListener, public std::enable_shared_from_this { +class BundleActiveCore : public BundleActiveStatsUpdateListener { public: BundleActiveCore(); virtual ~BundleActiveCore(); diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index f9ee8ca..15dcdc5 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -194,7 +194,7 @@ std::shared_ptr BundleActiveCore::GetUserDataAndInitial 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, shared_from_this(), + std::shared_ptr service = std::make_shared(userId, *this, debug); if (service == nullptr) { return nullptr; diff --git a/services/packageusage/include/bundle_active_user_service.h b/services/packageusage/include/bundle_active_user_service.h index e2692bd..cb56fc9 100644 --- a/services/packageusage/include/bundle_active_user_service.h +++ b/services/packageusage/include/bundle_active_user_service.h @@ -35,7 +35,7 @@ class BundleActiveCore; class BundleActiveUserService { public: BundleActiveUserService() = delete; - BundleActiveUserService(const int32_t userId, std::shared_ptr listener, const bool debug):listener_(listener) + BundleActiveUserService(const int32_t userId, BundleActiveCore& listener, const bool debug):listener_(listener) { for (int32_t i = 0; i < BundleActivePeriodStats::PERIOD_COUNT; i++) { currentStats_.push_back(nullptr); @@ -82,7 +82,7 @@ private: bool statsChanged_; bool debugUserService_; std::string lastForegroundBundle_; - std::weak_ptr listener_; + BundleActiveCore& listener_; std::vector periodLength_ = {0, 0, 0, 0}; void NotifyStatsChanged(); void NotifyNewUpdate(); diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index d032480..4b4e5f4 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -85,17 +85,13 @@ void BundleActiveUserService::NotifyStatsChanged() if (!statsChanged_) { BUNDLE_ACTIVE_LOGI("NotifyStatsChanged() set stats changed to true"); statsChanged_ = true; - if (!listener_.expired()) { - listener_.lock()->OnStatsChanged(userId_); - } + listener_.OnStatsChanged(userId_); } } void BundleActiveUserService::NotifyNewUpdate() { - if (!listener_.expired()) { - listener_.lock()->OnSystemUpdate(userId_); - } + listener_.OnSystemUpdate(userId_); } void BundleActiveUserService::ReportEvent(const BundleActiveEvent& event) @@ -241,9 +237,7 @@ void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const boo if (!timeChanged) { dailyExpiryDate_.TruncateToDay(); } - if (!listener_.expired()) { - listener_.lock()->CheckTimeChangeAndGetWallTime(); - } + listener_.CheckTimeChangeAndGetWallTime(); BUNDLE_ACTIVE_LOGI("LoadActiveStats current expire time is %{public}lld, " "begin time is %{public}lld", (long long)dailyExpiryDate_.GetMilliseconds(), (long long)tmpCalendar.GetMilliseconds()); -- Gitee From 12c7a67132b20ad14d0027eb41ce30d776fa294a Mon Sep 17 00:00:00 2001 From: houdisheng Date: Thu, 26 May 2022 21:08:01 +0800 Subject: [PATCH 15/83] =?UTF-8?q?=E5=85=B3=E9=97=ADdb=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- services/common/src/bundle_active_usage_database.cpp | 1 + services/packageusage/src/bundle_active_user_service.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/services/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp index 2195f2e..d41f9d2 100644 --- a/services/common/src/bundle_active_usage_database.cpp +++ b/services/common/src/bundle_active_usage_database.cpp @@ -414,6 +414,7 @@ shared_ptr BundleActiveUsageDatabase::GetBundleActiveRdbSto string currDatabaseFileConfig = BUNDLE_ACTIVE_DATABASE_DIR + databaseFiles_.at(databaseType); RdbStoreConfig config(currDatabaseFileConfig); BundleActiveOpenCallback rdbDataCallBack; + config.SetJournalMode(NativeRdb::JournalMode::MODE_OFF); rdbStore = RdbHelper::GetRdbStore(config, BUNDLE_ACTIVE_RDB_VERSION, rdbDataCallBack, errCode); if ((rdbStore == nullptr)) { BUNDLE_ACTIVE_LOGE("rdbStore is nullptr"); diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index 4b4e5f4..c79f1d6 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -237,7 +237,7 @@ void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const boo if (!timeChanged) { dailyExpiryDate_.TruncateToDay(); } - listener_.CheckTimeChangeAndGetWallTime(); + listener_.OnStatsReload(); BUNDLE_ACTIVE_LOGI("LoadActiveStats current expire time is %{public}lld, " "begin time is %{public}lld", (long long)dailyExpiryDate_.GetMilliseconds(), (long long)tmpCalendar.GetMilliseconds()); -- Gitee From 186064d17d38016e1c8bb740427fe6bec1f01500 Mon Sep 17 00:00:00 2001 From: xiebing Date: Sat, 28 May 2022 18:51:04 +0800 Subject: [PATCH 16/83] =?UTF-8?q?=E9=80=9A=E7=9F=A5=E6=AC=A1=E6=95=B0?= =?UTF-8?q?=E4=BA=8B=E4=BB=B6=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xiebing --- BUILD.gn | 3 + frameworks/src/bundle_state_common.cpp | 75 ++++++++- frameworks/src/bundle_state_init.cpp | 4 +- frameworks/src/bundle_state_query.cpp | 148 ++++++++++++++++++ .../innerkits/include/bundle_active_client.h | 20 ++- .../innerkits/include/bundle_active_proxy.h | 21 ++- .../innerkits/src/bundle_active_client.cpp | 18 +++ .../innerkits/src/bundle_active_proxy.cpp | 48 ++++++ .../bundlestats/js/@ohos.bundleState.d.ts | 49 ++++++ .../napi/include/bundle_state_common.h | 9 ++ .../napi/include/bundle_state_data.h | 15 ++ .../napi/include/bundle_state_inner_errors.h | 2 + .../napi/include/bundle_state_query.h | 2 + .../bundle_active_common_event_subscriber.h | 1 + .../common/include/bundle_active_constant.h | 8 + services/common/include/bundle_active_core.h | 24 ++- services/common/include/bundle_active_log.h | 12 +- ...bundle_active_power_state_callback_proxy.h | 39 +++++ ...ndle_active_power_state_callback_service.h | 36 +++++ .../bundle_active_power_state_callback_stub.h | 40 +++++ .../common/include/bundle_active_service.h | 21 ++- .../include/bundle_active_usage_database.h | 6 + .../common/include/ibundle_active_service.h | 24 ++- services/common/src/bundle_active_core.cpp | 112 ++++++++++++- ...ndle_active_power_state_callback_proxy.cpp | 41 +++++ ...le_active_power_state_callback_service.cpp | 45 ++++++ ...undle_active_power_state_callback_stub.cpp | 47 ++++++ services/common/src/bundle_active_service.cpp | 59 +++++++ services/common/src/bundle_active_stub.cpp | 35 +++++ .../src/bundle_active_usage_database.cpp | 138 ++++++++++++++-- .../include/bundle_active_event.h | 19 ++- .../include/bundle_active_event_stats.h | 18 ++- .../include/bundle_active_user_service.h | 8 + .../packageusage/src/bundle_active_event.cpp | 14 ++ .../src/bundle_active_event_stats.cpp | 29 ++++ .../src/bundle_active_user_service.cpp | 111 +++++++++++++ 36 files changed, 1264 insertions(+), 37 deletions(-) create mode 100644 services/common/include/bundle_active_power_state_callback_proxy.h create mode 100644 services/common/include/bundle_active_power_state_callback_service.h create mode 100644 services/common/include/bundle_active_power_state_callback_stub.h create mode 100644 services/common/src/bundle_active_power_state_callback_proxy.cpp create mode 100644 services/common/src/bundle_active_power_state_callback_service.cpp create mode 100644 services/common/src/bundle_active_power_state_callback_stub.cpp diff --git a/BUILD.gn b/BUILD.gn index 1a9d672..0ba5f34 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -98,6 +98,9 @@ ohos_shared_library("usagestatservice") { "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_power_state_callback_proxy.cpp", + "services/common/src/bundle_active_power_state_callback_service.cpp", + "services/common/src/bundle_active_power_state_callback_stub.cpp", "services/common/src/bundle_active_service.cpp", "services/common/src/bundle_active_shutdown_callback_proxy.cpp", "services/common/src/bundle_active_shutdown_callback_service.cpp", diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp index ae6a6d5..c5efe40 100644 --- a/frameworks/src/bundle_state_common.cpp +++ b/frameworks/src/bundle_state_common.cpp @@ -16,7 +16,7 @@ #include "securec.h" #include "bundle_active_log.h" -#include "bundle_state_data.h" +#include "bundle_state_inner_errors.h" #include "bundle_state_common.h" namespace OHOS { @@ -128,6 +128,58 @@ void BundleStateCommon::GetBundleStateInfoByIntervalForResult( } } +void BundleStateCommon::GetBundleActiveEventStatsForResult(napi_env env, + const std::vector &eventStats, napi_value result) +{ + int32_t index = 0; + for (const auto &item : eventStats) { + napi_value eventStatsObject = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &eventStatsObject)); + + napi_value name = nullptr; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, item.name_.c_str(), NAPI_AUTO_LENGTH, &name)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "name", name)); + + napi_value eventId = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.eventId_, &eventId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "eventId", eventId)); + + napi_value count = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.count_, &count)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "count", count)); + + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, eventStatsObject)); + index++; + } +} + +void BundleStateCommon::GetBundleActiveNotificationNumberForResult(napi_env env, + const std::vector &eventStats, napi_value result) +{ + int32_t index = 0; + for (const auto &item : eventStats) { + napi_value eventStatsObject = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &eventStatsObject)); + + napi_value name = nullptr; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, item.name_.c_str(), NAPI_AUTO_LENGTH, &name)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "name", name)); + + napi_value eventId = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.eventId_, &eventId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "eventId", eventId)); + + napi_value count = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.count_, &count)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "count", count)); + + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, eventStatsObject)); + index++; + } +} + void BundleStateCommon::GetBundleStateInfoForResult(napi_env env, const std::shared_ptr> &packageStats, napi_value result) { @@ -394,6 +446,27 @@ void BundleStateCommon::MergePackageStats(BundleActivePackageStats &left, const left.totalContiniousTaskUsedTime_ += right.totalContiniousTaskUsedTime_; left.bundleStartedCount_ += right.bundleStartedCount_; } + +std::unique_ptr BundleStateCommon::HandleEventStatsInfo( + AsyncCallbackInfoEventStats *asyncCallbackInfo, EventStatesParamsInfo ¶ms) +{ + if (!asyncCallbackInfo) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return nullptr; + } + if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) != EOK) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + return nullptr; + } + std::unique_ptr callbackPtr {asyncCallbackInfo}; + callbackPtr->beginTime = params.beginTime; + callbackPtr->endTime = params.endTime; + BUNDLE_ACTIVE_LOGI("CallbackPtr->beginTime: %{public}lld, callbackPtr->endTime: %{public}lld", + (long long)callbackPtr->beginTime, (long long)callbackPtr->endTime); + return callbackPtr; +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/frameworks/src/bundle_state_init.cpp b/frameworks/src/bundle_state_init.cpp index 56e36f8..27b3e5a 100644 --- a/frameworks/src/bundle_state_init.cpp +++ b/frameworks/src/bundle_state_init.cpp @@ -40,7 +40,9 @@ static napi_value BundleStateInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("queryBundleActiveStates", QueryBundleActiveStates), DECLARE_NAPI_FUNCTION("queryBundleStateInfoByInterval", QueryBundleStateInfoByInterval), DECLARE_NAPI_FUNCTION("queryBundleStateInfos", QueryBundleStateInfos), - DECLARE_NAPI_FUNCTION("getRecentlyUsedModules", GetModuleUsageRecord) + DECLARE_NAPI_FUNCTION("getRecentlyUsedModules", GetModuleUsageRecord), + DECLARE_NAPI_FUNCTION("queryBundleActiveEventStates", QueryBundleActiveEventStates), + DECLARE_NAPI_FUNCTION("queryAppNotificationNumber", QueryAppNotificationNumber) }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index 7b840ef..891e889 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -39,6 +39,8 @@ const uint32_t MODULE_RECORDS_PARAMS = 2; const uint32_t SECOND_ARG = 2; const uint32_t THIRD_ARG = 3; const int32_t MAXNUM_UP_LIMIT = 1000; +const uint32_t EVENT_STATES_MIN_PARAMS = 2; +const uint32_t EVENT_STATES_PARAMS = 3; napi_value ParseModuleRecordsParameters(const napi_env &env, const napi_callback_info &info, ModuleRecordParamsInfo ¶ms) @@ -724,6 +726,152 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) return promise; } } + +napi_value ParseEventStatesParameters(const napi_env &env, const napi_callback_info &info, + EventStatesParamsInfo ¶ms) +{ + size_t argc = EVENT_STATES_PARAMS; + napi_value argv[EVENT_STATES_PARAMS] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NAPI_ASSERT(env, argc == EVENT_STATES_MIN_PARAMS || argc == EVENT_STATES_PARAMS, + "Invalid number of parameters"); + + // argv[0] : beginTime + if ((params.errorCode == ERR_OK) + && ((BundleStateCommon::GetInt64NumberValue(env, argv[0], params.beginTime) == nullptr) + || (params.beginTime < TIME_NUMBER_MIN))) { + BUNDLE_ACTIVE_LOGE("ParseEventStatesParameters failed, beginTime is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; + } + + // argv[1] : endTime + if ((params.errorCode == ERR_OK) + && ((BundleStateCommon::GetInt64NumberValue(env, argv[1], params.endTime) == nullptr) + || (params.endTime < TIME_NUMBER_MIN))) { + BUNDLE_ACTIVE_LOGE("ParseEventStatesParameters failed, endTime is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) && (params.endTime <= params.beginTime)) { + BUNDLE_ACTIVE_LOGE("ParseEventStatesParameters endTime(%{public}lld) <= beginTime(%{public}lld)", + (long long)params.endTime, (long long)params.beginTime); + params.errorCode = ERR_USAGE_STATS_TIME_INTERVAL; + } + + // argv[SECOND_ARG]: callback + if (argc == EVENT_STATES_PARAMS) { + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[SECOND_ARG], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "ParseEventStatesParameters invalid parameter type. " + "Function expected."); + napi_create_reference(env, argv[SECOND_ARG], 1, ¶ms.callback); + } + return BundleStateCommon::NapiGetNull(env); +} + +napi_value QueryBundleActiveEventStates(napi_env env, napi_callback_info info) +{ + EventStatesParamsInfo params; + ParseEventStatesParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + napi_value promise = nullptr; + AsyncCallbackInfoEventStats *asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfoEventStats(env); + std::unique_ptr callbackPtr = + BundleStateCommon::HandleEventStatsInfo(asyncCallbackInfo, params); + if (!callbackPtr) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, "QueryBundleActiveEventStates", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncCallbackInfoEventStats *asyncCallbackInfo = (AsyncCallbackInfoEventStats *)data; + if (asyncCallbackInfo != nullptr) { + asyncCallbackInfo->errorCode = BundleActiveClient::GetInstance() + .QueryEventStats(asyncCallbackInfo->beginTime, + asyncCallbackInfo->endTime, asyncCallbackInfo->eventStats); + } else { + BUNDLE_ACTIVE_LOGE("QueryBundleActiveEventStates, asyncCallbackInfo == nullptr"); + } + }, + [](napi_env env, napi_status status, void *data) { + AsyncCallbackInfoEventStats *asyncCallbackInfo = (AsyncCallbackInfoEventStats *)data; + if (asyncCallbackInfo != nullptr) { + napi_value result = nullptr; + napi_create_array(env, &result); + BundleStateCommon::GetBundleActiveEventStatsForResult(env, asyncCallbackInfo->eventStats, result); + BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); + } + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); + if (callbackPtr->isCallback) { + callbackPtr.release(); + return BundleStateCommon::NapiGetNull(env); + } else { + callbackPtr.release(); + return promise; + } +} + +napi_value QueryAppNotificationNumber(napi_env env, napi_callback_info info) +{ + EventStatesParamsInfo params; + ParseEventStatesParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + napi_value promise = nullptr; + AsyncCallbackInfoEventStats *asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfoEventStats(env); + std::unique_ptr callbackPtr = + BundleStateCommon::HandleEventStatsInfo(asyncCallbackInfo, params); + if (!callbackPtr) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, "QueryAppNotificationNumber", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncCallbackInfoEventStats *asyncCallbackInfo = (AsyncCallbackInfoEventStats *)data; + if (asyncCallbackInfo != nullptr) { + asyncCallbackInfo->errorCode = BundleActiveClient::GetInstance() + .QueryAppNotificationNumber(asyncCallbackInfo->beginTime, + asyncCallbackInfo->endTime, asyncCallbackInfo->eventStats); + } else { + BUNDLE_ACTIVE_LOGE("QueryAppNotificationNumber, asyncCallbackInfo == nullptr"); + } + }, + [](napi_env env, napi_status status, void *data) { + AsyncCallbackInfoEventStats *asyncCallbackInfo = (AsyncCallbackInfoEventStats *)data; + if (asyncCallbackInfo != nullptr) { + napi_value result = nullptr; + napi_create_array(env, &result); + BundleStateCommon::GetBundleActiveNotificationNumberForResult(env, + asyncCallbackInfo->eventStats, result); + BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); + } + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); + if (callbackPtr->isCallback) { + callbackPtr.release(); + return BundleStateCommon::NapiGetNull(env); + } else { + callbackPtr.release(); + return promise; + } +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h index 3e60e1c..872b5e4 100644 --- a/interfaces/innerkits/include/bundle_active_client.h +++ b/interfaces/innerkits/include/bundle_active_client.h @@ -19,6 +19,7 @@ #include "ibundle_active_service.h" #include "bundle_active_package_stats.h" #include "bundle_active_event.h" +#include "bundle_active_event_stats.h" #include "bundle_active_package_stats.h" #include "bundle_active_module_record.h" @@ -80,11 +81,28 @@ public: /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, - * if other SAs call this API, they should explicit define userId + * if other SAs call this API, they should explicit define userId. * return: errorcode. */ int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId = -1); /* + * function: QueryEventStats, query all from event stats in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId = -1); + + /* + * function: QueryAppNotificationNumber, query all app notification number in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId = -1); + /* * function: GetInstance, get instance of client. * return: object of BundleActiveClient. */ diff --git a/interfaces/innerkits/include/bundle_active_proxy.h b/interfaces/innerkits/include/bundle_active_proxy.h index 50db119..10a3229 100644 --- a/interfaces/innerkits/include/bundle_active_proxy.h +++ b/interfaces/innerkits/include/bundle_active_proxy.h @@ -18,6 +18,7 @@ #include "ibundle_active_service.h" #include "bundle_active_event.h" +#include "bundle_active_event_stats.h" #include "bundle_active_package_stats.h" #include "bundle_active_package_stats.h" #include "bundle_active_module_record.h" @@ -78,12 +79,28 @@ public: /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, - * if other SAs call this API, they should explicit define userId + * if other SAs call this API, they should explicit define userId. * return: errorcode. */ int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId = -1) override; /* + * function: QueryEventStats, query all from event stats in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) override; + /* + * function: QueryAppNotificationNumber, query all app notification number in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) override; + /* * function: BundleActiveProxy, default constructor. * parameters: impl */ @@ -96,6 +113,8 @@ public: private: static inline BrokerDelegator delegator_; + int32_t IPCCommunication(int64_t beginTime, int64_t endTime, std::vector& eventStats, + int32_t userId, int32_t communicationFlag); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index ae9f263..beddc8c 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -132,6 +132,24 @@ int32_t BundleActiveClient::QueryFormStatistics(int32_t maxNum, std::vectorQueryFormStatistics(maxNum, results, userId); } +int32_t BundleActiveClient::QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + if (!GetBundleActiveProxy()) { + return -1; + } + return bundleActiveProxy_->QueryEventStats(beginTime, endTime, eventStats, userId); +} + +int32_t BundleActiveClient::QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + if (!GetBundleActiveProxy()) { + return -1; + } + return bundleActiveProxy_->QueryAppNotificationNumber(beginTime, endTime, eventStats, userId); +} + int32_t BundleActiveClient::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) { int32_t ret = -1; diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index 43cfd63..d811a9a 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -242,6 +242,54 @@ int32_t BundleActiveProxy::QueryFormStatistics(int32_t maxNum, std::vector& eventStats, int32_t userId) +{ + int32_t errCode = IPCCommunication(beginTime, endTime, eventStats, userId, QUERY_EVENT_STATS); + for (const auto& singleEvent : eventStats) { + BUNDLE_ACTIVE_LOGI("name is %{public}s, eventId is %{public}d, count is %{public}d", + singleEvent.name_.c_str(), singleEvent.eventId_, singleEvent.count_); + } + return errCode; +} + +int32_t BundleActiveProxy::QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + int32_t errCode = IPCCommunication(beginTime, endTime, eventStats, userId, QUERY_APP_NOTIFICATION_NUMBER); + for (const auto& singleEvent : eventStats) { + BUNDLE_ACTIVE_LOGI("name is %{public}s, eventId is %{public}d, count is %{public}d", + singleEvent.name_.c_str(), singleEvent.eventId_, singleEvent.count_); + } + return errCode; +} + +int32_t BundleActiveProxy::IPCCommunication(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId, int32_t communicationFlag) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(GetDescriptor())) { + return -1; + } + data.WriteInt64(beginTime); + data.WriteInt64(endTime); + data.WriteInt32(userId); + Remote() -> SendRequest(communicationFlag, data, reply, option); + int32_t errCode = reply.ReadInt32(); + int32_t size = reply.ReadInt32(); + std::shared_ptr tmp; + for (int32_t i = 0; i < size; i++) { + tmp = tmp->UnMarshalling(reply); + if (!tmp) { + continue; + } + eventStats.emplace_back(*tmp); + } + return errCode; +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts index 100791b..28ce964 100644 --- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts +++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts @@ -174,6 +174,27 @@ declare namespace bundleState { formRecords: Array; } + /** + * @since 9 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + */ + interface BundleActiveEventState { + /** + * the bundle name or system event name. + */ + name?: string; + + /** + * the event id. + */ + eventId: number; + + /** + * the the event occurrence number. + */ + count: number; + } + /** * @since 7 * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App @@ -343,6 +364,34 @@ declare namespace bundleState { */ function getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback>): void; function getRecentlyUsedModules(maxNum?: number): Promise>; + + /** + * Queries system event states data within a specified period identified by the start and end time. + * + * @since 9 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + * @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 BundleActiveEventState} object Array containing the event states data. + */ + function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback>): void; + function queryBundleActiveEventStates(begin: number, end: number): Promise>; + + /** + * Queries app notification number within a specified period identified by the start and end time. + * + * @since 9 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + * @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 BundleActiveEventState} object Array containing the event states data. + */ + function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback>): void; + function queryAppNotificationNumber(begin: number, end: number): Promise>; } export default bundleState; diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h index f2a172a..a0f5512 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h @@ -50,6 +50,12 @@ public: static void GetBundleStateInfoByIntervalForResult( napi_env env, const std::vector &packageStats, napi_value result); + static void GetBundleActiveEventStatsForResult(napi_env env, + const std::vector &eventStats, napi_value result); + + static void GetBundleActiveNotificationNumberForResult(napi_env env, + const std::vector &eventStats, napi_value result); + static void GetBundleStateInfoForResult(napi_env env, const std::shared_ptr> &packageStats, napi_value result); @@ -74,6 +80,9 @@ public: int64_t &beginTime, int64_t &endTime, int32_t &errCode); static void MergePackageStats(BundleActivePackageStats &left, const BundleActivePackageStats &right); + + static std::unique_ptr HandleEventStatsInfo( + AsyncCallbackInfoEventStats *asyncCallbackInfo, EventStatesParamsInfo ¶ms); }; } // 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 b27b51d..f882e04 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h @@ -23,6 +23,7 @@ #include "napi/native_node_api.h" #include "bundle_active_event.h" +#include "bundle_active_event_stats.h" #include "bundle_active_package_stats.h" namespace OHOS { @@ -80,6 +81,13 @@ struct AsyncCallbackInfoAppUsageByInterval : public AsyncWorkData { std::vector packageStats; }; +struct AsyncCallbackInfoEventStats : public AsyncWorkData { + explicit AsyncCallbackInfoEventStats(napi_env env) : AsyncWorkData(env) {} + int64_t beginTime = -1; + int64_t endTime = -1; + std::vector eventStats; +}; + struct AsyncCallbackInfoAppUsage : public AsyncWorkData { explicit AsyncCallbackInfoAppUsage(napi_env env) : AsyncWorkData(env) {} int64_t beginTime = -1; @@ -131,6 +139,13 @@ struct ModuleRecordParamsInfo { napi_ref callback = nullptr; int32_t errorCode = 0; }; + +struct EventStatesParamsInfo { + int64_t beginTime = -1; + int64_t endTime = -1; + napi_ref callback = nullptr; + int32_t errorCode = 0; +}; } // namespace DeviceUsageStats } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_DATA_H diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h index 3576ab1..d079997 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h @@ -50,6 +50,8 @@ enum : int32_t { ERR_USAGE_STATS_INTERVAL_TYPE, ERR_USAGE_STATS_INTERVAL_NUMBER, ERR_MODULE_STATS_MAXNUM_INVALID, + ERR_EVENT_TYPE, + ERR_EVENT_TYPE_NUMBER, }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_query.h b/interfaces/kits/bundlestats/napi/include/bundle_state_query.h index 0a0492a..0d36f55 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_query.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_query.h @@ -28,6 +28,8 @@ namespace DeviceUsageStats { napi_value QueryBundleStateInfoByInterval(napi_env env, napi_callback_info info); napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info); napi_value GetModuleUsageRecord(napi_env env, napi_callback_info info); + napi_value QueryBundleActiveEventStates(napi_env env, napi_callback_info info); + napi_value QueryAppNotificationNumber(napi_env env, napi_callback_info info); } // namespace DeviceUsageStats } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_QUERY_H diff --git a/services/common/include/bundle_active_common_event_subscriber.h b/services/common/include/bundle_active_common_event_subscriber.h index 5ffc403..28bfe69 100644 --- a/services/common/include/bundle_active_common_event_subscriber.h +++ b/services/common/include/bundle_active_common_event_subscriber.h @@ -46,6 +46,7 @@ public: bundleActiveReportHandler_(bundleActiveReportHandler) {} ~BundleActiveCommonEventSubscriber() = default; void OnReceiveEvent(const CommonEventData &data) override; + void HandleLockEvent(const std::string& action); private: std::mutex mutex_; diff --git a/services/common/include/bundle_active_constant.h b/services/common/include/bundle_active_constant.h index 82bf37e..8cd7ba5 100644 --- a/services/common/include/bundle_active_constant.h +++ b/services/common/include/bundle_active_constant.h @@ -69,6 +69,8 @@ const int32_t FORM_DIMENSION_COLUMN_INDEX = 4; const int32_t FORM_ID_COLUMN_INDEX = 5; const int32_t FORM_COUNT_COLUMN_INDEX = 6; const int32_t FORM_LAST_TIME_COLUMN_INDEX = 7; +const int32_t QUERY_CONDITION_VALID = 0; +const int32_t QUERY_CONDITION_INVALID = -1; const int64_t TWO_SECONDS = 2 * 1000LL; const int64_t THIRTY_MINUTE = 30 * 60 * 1000LL; const int64_t SIX_DAY_IN_MILLIS_MAX_DEBUG = 6 * 1 * 10 * 60 * 1000LL; @@ -125,8 +127,14 @@ const std::string BUNDLE_ACTIVE_DATABASE_DIR = "/data/service/el1/public/bundle_ const std::string BUNDLE_ACTIVE_VERSION_FILE = "/version"; const std::string DATABASE_FILE_TABLE_NAME = "table"; const std::string SQLITE_MASTER_NAME = "name"; +const std::string COMMON_EVENT_UNLOCK_SCREEN = "common.event.UNLOCK_SCREEN"; +const std::string COMMON_EVENT_LOCK_SCREEN = "common.event.LOCK_SCREEN"; const std::string DATABASE_TYPE[] = {"daily", "weekly", "monthly", "yearly", "event", "usageGroup"}; const std::string SUFFIX_TYPE[] = {".db", ".db-shm", ".db-wal"}; +const std::string OPERATION_SYSTEM_LOCK = "SYSTEM_LOCK"; +const std::string OPERATION_SYSTEM_UNLOCK = "SYSTEM_UNLOCK"; +const std::string OPERATION_SYSTEM_SLEEP = "SYSTEM_SLEEP"; +const std::string OPERATION_SYSTEM_WAKEUP = "SYSTEM_WAKEUP"; } // namespace DeviceUsageStats } // namespace OHOS #endif // BUNDLE_ACTIVE_CONSTANT_H diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 3c861ce..fb933eb 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -54,7 +54,7 @@ public: * function: ReportEvent, used to report ability fourground/background/destroy event. * parameters: event, userId */ - int32_t ReportEvent(BundleActiveEvent& event, const int32_t userId); + int32_t ReportEvent(BundleActiveEvent& event, int32_t userId); /* * function: ReportEventToAllUserId, report flush to disk, end_of_day event to service. * parameters: event @@ -112,6 +112,10 @@ public: */ void ShutDown(); /* + * function: PreservePowerStateInfo, called when device change power state, preserve power state info. + */ + void PreservePowerStateInfo(const int32_t eventId); + /* * function: QueryPackageStats, query the package stat for calling user. * parameters: userId, intervalType, beginTime, endTime, bundleName * return: vector of BundleActivePackageStats @@ -126,6 +130,23 @@ public: // query the app group for calling app. int32_t QueryPackageGroup(const int32_t userId, const std::string bundleName); int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId); + /* + * function: QueryEventStats, query all from event stats in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId); + + /* + * function: QueryAppNotificationNumber, query all app notification number in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId); // get the wall time and check if the wall time is changed. int64_t CheckTimeChangeAndGetWallTime(int32_t userId = 0); // convert event timestamp from boot based time to wall time. @@ -163,6 +184,7 @@ private: void RegisterSubscriber(); std::shared_ptr commonEventSubscriber_; void RestoreAllData(); + void ObtainSystemEventName(BundleActiveEvent& event); bool debugCore_; }; } // namespace DeviceUsageStats diff --git a/services/common/include/bundle_active_log.h b/services/common/include/bundle_active_log.h index 0dae499..b61c5a6 100644 --- a/services/common/include/bundle_active_log.h +++ b/services/common/include/bundle_active_log.h @@ -60,7 +60,7 @@ private: static BundleActiveLogLevel logLevel_; }; -#define PRINT_LOG(LEVEL, Level, fmt, ...) \ +#define BUNDLE_ACTIVE_PRINT_LOG(LEVEL, Level, fmt, ...) \ if (BundleActiveLog::JudgeValidLevel(BundleActiveLogLevel::LEVEL)) \ OHOS::HiviewDFX::HiLog::Level(BUNDLE_ACTIVE_LOG_LABEL, \ "[%{public}s(%{public}s):%{public}d] " fmt, \ @@ -69,11 +69,11 @@ private: __LINE__, \ ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGD(fmt, ...) PRINT_LOG(DEBUG, Debug, fmt, ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGI(fmt, ...) PRINT_LOG(INFO, Info, fmt, ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGW(fmt, ...) PRINT_LOG(WARN, Warn, fmt, ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGE(fmt, ...) PRINT_LOG(ERROR, Error, fmt, ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGF(fmt, ...) PRINT_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGD(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(DEBUG, Debug, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGI(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(INFO, Info, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGW(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(WARN, Warn, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGE(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(ERROR, Error, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGF(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) } // namespace DeviceUsageStats } // namespace OHOS #endif // BUNDLE_ACTIVE_LOG_H diff --git a/services/common/include/bundle_active_power_state_callback_proxy.h b/services/common/include/bundle_active_power_state_callback_proxy.h new file mode 100644 index 0000000..c0a158a --- /dev/null +++ b/services/common/include/bundle_active_power_state_callback_proxy.h @@ -0,0 +1,39 @@ +/* + * 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_POWER_STATE_CALLBACK_PROXY_H +#define BUNDLE_ACTIVE_POWER_STATE_CALLBACK_PROXY_H + +#include "ibundle_active_service.h" +#include "ipower_state_callback.h" +#include "nocopyable.h" + +namespace OHOS { +namespace DeviceUsageStats { +using IPowerStateCallback = OHOS::PowerMgr::IPowerStateCallback; +class BundleActivePowerStateCallbackProxy : public IRemoteProxy { +public: + explicit BundleActivePowerStateCallbackProxy(const sptr& impl) + : IRemoteProxy(impl) {} + ~BundleActivePowerStateCallbackProxy() = default; + DISALLOW_COPY_AND_MOVE(BundleActivePowerStateCallbackProxy); + void OnPowerStateChanged(PowerMgr::PowerState state) override; +private: + static inline BrokerDelegator delegator_; +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_POWER_STATE_CALLBACK_PROXY_H + diff --git a/services/common/include/bundle_active_power_state_callback_service.h b/services/common/include/bundle_active_power_state_callback_service.h new file mode 100644 index 0000000..7cca1ea --- /dev/null +++ b/services/common/include/bundle_active_power_state_callback_service.h @@ -0,0 +1,36 @@ + /* + * 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_POWER_STATE_CALLBACK_SERVICE_H +#define BUNDLE_ACTIVE_POWER_STATE_CALLBACK_SERVICE_H + +#include "bundle_active_power_state_callback_stub.h" +#include "bundle_active_core.h" + +namespace OHOS { +namespace DeviceUsageStats { +using OHOS::PowerMgr::PowerState; +class BundleActivePowerStateCallbackService : public BundleActivePowerStateCallbackStub { +public: + BundleActivePowerStateCallbackService(std::shared_ptr bundleActiveCore); + virtual ~BundleActivePowerStateCallbackService() {} + void OnPowerStateChanged(PowerState state) override; +private: + std::shared_ptr bundleActiveCore_; +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_POWER_STATE_CALLBACK_SERVICE_H + diff --git a/services/common/include/bundle_active_power_state_callback_stub.h b/services/common/include/bundle_active_power_state_callback_stub.h new file mode 100644 index 0000000..93ec067 --- /dev/null +++ b/services/common/include/bundle_active_power_state_callback_stub.h @@ -0,0 +1,40 @@ +/* + * 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_POWER_STATE_CALLBACK_STUB_H +#define BUNDLE_ACTIVE_POWER_STATE_CALLBACK_STUB_H + +#include "ipower_state_callback.h" +#include "nocopyable.h" + +#include "ibundle_active_service.h" + +namespace OHOS { +namespace DeviceUsageStats { +using IPowerStateCallback = OHOS::PowerMgr::IPowerStateCallback; +using PowerState = OHOS::PowerMgr::PowerState; +class BundleActivePowerStateCallbackStub : public IRemoteStub { +public: + DISALLOW_COPY_AND_MOVE(BundleActivePowerStateCallbackStub); + BundleActivePowerStateCallbackStub() = default; + virtual ~BundleActivePowerStateCallbackStub() = default; + int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply, MessageOption &option) override; +private: + void PowerStateStub(PowerState state); +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_POWER_STATE_CALLBACK_STUB_H + diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index e8921a4..d8000ef 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -24,6 +24,7 @@ #include "bundle_active_core.h" #include "bundle_active_report_handler.h" #include "bundle_active_shutdown_callback_service.h" +#include "bundle_active_power_state_callback_service.h" #include "bundle_active_app_state_observer.h" #include "bundle_active_continuous_task_observer.h" #include "bundle_active_account_helper.h" @@ -35,7 +36,6 @@ class BundleActiveService : public SystemAbility, public BundleActiveStub, DISALLOW_COPY_AND_MOVE(BundleActiveService); DECLARE_SYSTEM_ABILITY(BundleActiveService); DECLARE_DELAYED_SINGLETON(BundleActiveService); - public: using IBundleMgr = OHOS::AppExecFwk::IBundleMgr; using BundleInfo = OHOS::AppExecFwk::BundleInfo; @@ -97,12 +97,28 @@ public: /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, - * if other SAs call this API, they should explicit define userId + * if other SAs call this API, they should explicit define userId. * return: errorcode. */ int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId = -1) override; /* + * function: QueryEventStats, query all from event stats in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) override; + /* + * function: QueryAppNotificationNumber, query all app notification number in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) override; + /* * function: BundleActiveService, default constructor. * parameters: systemAbilityId, runOnCreate */ @@ -123,6 +139,7 @@ private: std::shared_ptr continuousTaskObserver_; sptr sptrBundleMgr_; sptr shutdownCallback_; + sptr powerStateCallback_; std::shared_ptr runner_; std::shared_ptr handler_; bool ready_ {false}; diff --git a/services/common/include/bundle_active_usage_database.h b/services/common/include/bundle_active_usage_database.h index f26373c..23cfe58 100644 --- a/services/common/include/bundle_active_usage_database.h +++ b/services/common/include/bundle_active_usage_database.h @@ -67,6 +67,10 @@ public: std::shared_ptr>& moduleRecords); void LoadFormData(const int32_t userId, std::map>& moduleRecords); + void QueryEventStats(int32_t eventId, int64_t beginTime, int64_t endTime, + std::map& eventStats, int32_t userId); + void QueryAppNotificationNumber(int32_t eventId, int64_t beginTime, int64_t endTime, + std::map& notificationEventStats, int32_t userId); private: void CheckDatabaseVersion(); @@ -102,6 +106,8 @@ private: void UpdateFormData(const int32_t userId, const std::string bundleName, const std::string moduleName, const BundleActiveFormRecord& formRecord, std::shared_ptr rdbStore); + int32_t JudgeQueryCondition(const int64_t beginTime, const int64_t endTime, const int64_t eventTableTime); + std::string GetSystemEventName(const int32_t userId); private: std::vector databaseFiles_; diff --git a/services/common/include/ibundle_active_service.h b/services/common/include/ibundle_active_service.h index 63d332c..8d8b70f 100644 --- a/services/common/include/ibundle_active_service.h +++ b/services/common/include/ibundle_active_service.h @@ -40,6 +40,7 @@ namespace OHOS { namespace DeviceUsageStats { class BundleActivePackageStats; class BundleActiveEvent; +class BundleActiveEventStats; class BundleActiveModuleRecord; class IBundleActiveService : public IRemoteBroker { @@ -99,12 +100,27 @@ public: /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, - * if other SAs call this API, they should explicit define userId + * if other SAs call this API, they should explicit define userId. * return: errorcode. */ virtual int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId) = 0; - + /* + * function: QueryEventStats, query all from event stats in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + virtual int32_t QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) = 0; + /* + * function: QueryAppNotificationNumber, query all app notification number in specific time span for calling user. + * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, + * if other SAs call this API, they should explicit define userId. + * return: errorcode. + */ + virtual int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) = 0; public: enum { REPORT_EVENT = 1, @@ -115,7 +131,9 @@ public: QUERY_CURRENT_EVENTS = 6, QUERY_BUNDLE_GROUP = 7, SET_BUNDLE_GROUP = 8, - QUERY_FORM_STATS = 9 + QUERY_FORM_STATS = 9, + QUERY_EVENT_STATS = 10, + QUERY_APP_NOTIFICATION_NUMBER = 11 }; public: DECLARE_INTERFACE_DESCRIPTOR(u"Resourceschedule.IBundleActiveService"); diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 15dcdc5..600a374 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -17,6 +17,7 @@ #include "time_service_client.h" #include "bundle_active_event.h" +#include "bundle_active_event_stats.h" #include "bundle_active_report_handler.h" #include "bundle_active_group_common.h" #include "bundle_active_constant.h" @@ -111,9 +112,32 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da handlerobjToPtr); bundleActiveReportHandler_.lock()->SendEvent(event); } + } else if (action == COMMON_EVENT_UNLOCK_SCREEN || action == COMMON_EVENT_LOCK_SCREEN) { + HandleLockEvent(action); } } +void BundleActiveCommonEventSubscriber::HandleLockEvent(const std::string& action) +{ + if (bundleActiveReportHandler_.expired()) { + return; + } + BundleActiveReportHandlerObject tmpHandlerObject(-1, ""); + BundleActiveEvent newEvent; + tmpHandlerObject.event_ = newEvent; + if (action == COMMON_EVENT_UNLOCK_SCREEN) { + tmpHandlerObject.event_.eventId_ = BundleActiveEvent::SYSTEM_UNLOCK; + } else { + tmpHandlerObject.event_.eventId_ = BundleActiveEvent::SYSTEM_LOCK; + } + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); + auto handlerobjToPtr = std::make_shared(tmpHandlerObject); + auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_REPORT_EVENT, + handlerobjToPtr); + bundleActiveReportHandler_.lock()->SendEvent(event); +} + void BundleActiveCore::RegisterSubscriber() { MatchingSkills matchingSkills; @@ -124,6 +148,8 @@ void BundleActiveCore::RegisterSubscriber() matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); + matchingSkills.AddEvent(COMMON_EVENT_UNLOCK_SCREEN); + matchingSkills.AddEvent(COMMON_EVENT_LOCK_SCREEN); CommonEventSubscribeInfo subscriberInfo(matchingSkills); commonEventSubscriber_ = std::make_shared(subscriberInfo, bundleGroupController_, handler_); @@ -293,6 +319,28 @@ void BundleActiveCore::RestoreToDatabaseLocked(const int32_t userId) } } +void BundleActiveCore::PreservePowerStateInfo(const int32_t eventId) +{ + if (!handler_.expired()) { + int32_t userId = -1; + std::vector currentActiveUser; + BundleActiveCore::GetAllActiveUser(currentActiveUser); + if (currentActiveUser.size() == 1) { + userId = currentActiveUser.front(); + } + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); + BundleActiveEvent newEvent; + tmpHandlerObject.event_ = newEvent; + tmpHandlerObject.event_.eventId_ = eventId; + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); + std::shared_ptr handlerobjToPtr = + std::make_shared(tmpHandlerObject); + auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr); + handler_.lock()->SendEvent(event); + } +} + void BundleActiveCore::ShutDown() { std::lock_guard lock(mutex_); @@ -410,11 +458,19 @@ void BundleActiveCore::OnUserSwitched(const int32_t userId) OnStatsChanged(userId); } -int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int32_t userId) +int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, int32_t userId) { BUNDLE_ACTIVE_LOGI("FLUSH interval is %{public}lld, debug is %{public}d", (long long)flushInterval_, debugCore_); event.PrintEvent(debugCore_); std::lock_guard lock(mutex_); + if (event.eventId_ == BundleActiveEvent::SYSTEM_LOCK || event.eventId_ == BundleActiveEvent::SYSTEM_UNLOCK) { + std::vector currentActiveUser; + BundleActiveCore::GetAllActiveUser(currentActiveUser); + if (currentActiveUser.size() == 1) { + userId = currentActiveUser.front(); + } + } + ObtainSystemEventName(event); if (userId == 0 || userId == -1) { return -1; } @@ -422,7 +478,6 @@ int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int32_t us 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) { @@ -430,7 +485,6 @@ int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int32_t us 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(), (long long)event.timeStamp_, userId, event.eventId_); @@ -455,6 +509,26 @@ int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int32_t us return 0; } +void BundleActiveCore::ObtainSystemEventName(BundleActiveEvent& event) +{ + switch (event.eventId_) { + case BundleActiveEvent::SYSTEM_LOCK: + event.bundleName_ = OPERATION_SYSTEM_LOCK; + break; + case BundleActiveEvent::SYSTEM_UNLOCK: + event.bundleName_ = OPERATION_SYSTEM_UNLOCK; + break; + case BundleActiveEvent::SYSTEM_SLEEP: + event.bundleName_ = OPERATION_SYSTEM_SLEEP; + break; + case BundleActiveEvent::SYSTEM_WAKEUP: + event.bundleName_ = OPERATION_SYSTEM_WAKEUP; + break; + default: + break; + } +} + int32_t BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event) { BUNDLE_ACTIVE_LOGI("ReportEventToAllUserId called"); @@ -543,6 +617,38 @@ int32_t BundleActiveCore::QueryFormStatistics(int32_t maxNum, std::vector& eventStats, int32_t userId) +{ + std::lock_guard lock(mutex_); + int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); + if (timeNow == -1) { + return -1; + } + std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_); + if (!service) { + return -1; + } + int32_t errCode = service->QueryEventStats(beginTime, endTime, eventStats, userId); + return errCode; +} + +int32_t BundleActiveCore::QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + std::lock_guard lock(mutex_); + int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); + if (timeNow == -1) { + return -1; + } + std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_); + if (!service) { + return -1; + } + int32_t errCode = service->QueryAppNotificationNumber(beginTime, endTime, eventStats, userId); + return errCode; +} + void BundleActiveCore::SetBundleGroup(const std::string& bundleName, const int32_t newGroup, const int32_t userId) { int32_t newReason = GROUP_CONTROL_REASON_FORCED; diff --git a/services/common/src/bundle_active_power_state_callback_proxy.cpp b/services/common/src/bundle_active_power_state_callback_proxy.cpp new file mode 100644 index 0000000..356183f --- /dev/null +++ b/services/common/src/bundle_active_power_state_callback_proxy.cpp @@ -0,0 +1,41 @@ +/* + * 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 "bundle_active_power_state_callback_proxy.h" +#include "power_state_machine_info.h" + +namespace OHOS { +namespace DeviceUsageStats { +void BundleActivePowerStateCallbackProxy::OnPowerStateChanged(PowerMgr::PowerState state) +{ + sptr remote = Remote(); + if (remote == nullptr) { + return; + } + MessageParcel data; + data.WriteInt32((int32_t)state); + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(BundleActivePowerStateCallbackProxy::GetDescriptor())) { + return; + } + int32_t ret = remote->SendRequest(IPowerStateCallback::POWER_STATE_CHANGED, data, reply, option); + if (ret != ERR_OK) { + BUNDLE_ACTIVE_LOGE("BundleActivePowerStateCallbackProxy::PowerStateCallback failed!"); + } +} +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_power_state_callback_service.cpp b/services/common/src/bundle_active_power_state_callback_service.cpp new file mode 100644 index 0000000..fcbdb37 --- /dev/null +++ b/services/common/src/bundle_active_power_state_callback_service.cpp @@ -0,0 +1,45 @@ +/* + * 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 "bundle_active_power_state_callback_service.h" +#include "power_state_machine_info.h" + +namespace OHOS { +namespace DeviceUsageStats { +using OHOS::PowerMgr::PowerState; +BundleActivePowerStateCallbackService::BundleActivePowerStateCallbackService( + std::shared_ptr bundleActiveCore) +{ + if (bundleActiveCore != nullptr) { + bundleActiveCore_ = bundleActiveCore; + } +} + +void BundleActivePowerStateCallbackService::OnPowerStateChanged(PowerState state) +{ + int32_t eventId; + BUNDLE_ACTIVE_LOGD("BundleActDvePowerStateCallbackService::OnPowerStateChanged power state is %{public}u", state); + if (state == PowerState::AWAKE) { + eventId = BundleActiveEvent::SYSTEM_WAKEUP; + } else if (state == PowerState::SLEEP) { + eventId = BundleActiveEvent::SYSTEM_SLEEP; + } else { + return; + } + bundleActiveCore_->PreservePowerStateInfo(eventId); +} +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_power_state_callback_stub.cpp b/services/common/src/bundle_active_power_state_callback_stub.cpp new file mode 100644 index 0000000..6ec2ff1 --- /dev/null +++ b/services/common/src/bundle_active_power_state_callback_stub.cpp @@ -0,0 +1,47 @@ +/* + * 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 "bundle_active_power_state_callback_stub.h" +#include "bundle_active_event.h" + +namespace OHOS { +namespace DeviceUsageStats { +int32_t BundleActivePowerStateCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply, + MessageOption &option) +{ + std::u16string descriptor = BundleActivePowerStateCallbackStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + PowerMgr::PowerState state = (PowerMgr::PowerState)data.ReadInt32(); + if (descriptor != remoteDescriptor) { + BUNDLE_ACTIVE_LOGE("BundleActivePowerStateCallbackStub::OnRemoteRequest cannot get power mgr service"); + return -1; + } + switch (code) { + case IPowerStateCallback::POWER_STATE_CHANGED: { + PowerStateStub(state); + return ERR_OK; + } + default: + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } +} + +void BundleActivePowerStateCallbackStub::PowerStateStub(PowerMgr::PowerState state) +{ + OnPowerStateChanged(state); +} +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index d211889..c4c691d 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -131,10 +131,14 @@ void BundleActiveService::InitService() return; } shutdownCallback_ = new (std::nothrow) BundleActiveShutdownCallbackService(bundleActiveCore_); + powerStateCallback_ = new (std::nothrow) BundleActivePowerStateCallbackService(bundleActiveCore_); auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance(); if (shutdownCallback_) { powerManagerClient.RegisterShutdownCallback(shutdownCallback_); } + if (powerStateCallback_) { + powerManagerClient.RegisterPowerStateCallback(powerStateCallback_); + } InitAppStateSubscriber(reportHandler_); InitContinuousSubscriber(reportHandler_); bundleActiveCore_->InitBundleGroupController(); @@ -205,6 +209,7 @@ void BundleActiveService::OnStop() if (shutdownCallback_ != nullptr) { auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance(); powerManagerClient.UnRegisterShutdownCallback(shutdownCallback_); + powerManagerClient.UnRegisterPowerStateCallback(powerStateCallback_); return; } BUNDLE_ACTIVE_LOGI("[Server] OnStop"); @@ -506,6 +511,60 @@ int32_t BundleActiveService::QueryFormStatistics(int32_t maxNum, std::vector& eventStats, int32_t userId) +{ + int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); + BUNDLE_ACTIVE_LOGI("QueryEventStats UID is %{public}d", callingUid); + // get userid when userId is -1 + int32_t errCode = 0; + if (userId == -1) { + OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); + if (ret != ERR_OK) { + errCode = -1; + return errCode; + } + } + if (userId != -1) { + BUNDLE_ACTIVE_LOGI("QueryEventStats userid is %{public}d", userId); + AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + if ((CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId, errCode)) || + (AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) == + AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE)) { + errCode = bundleActiveCore_->QueryEventStats(beginTime, endTime, eventStats, userId); + } + } + BUNDLE_ACTIVE_LOGI("QueryEventStats result size is %{public}zu", eventStats.size()); + return errCode; +} + +int32_t BundleActiveService::QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); + BUNDLE_ACTIVE_LOGI("QueryAppNotificationNumber UID is %{public}d", callingUid); + // get userid when userId is -1 + int32_t errCode = 0; + if (userId == -1) { + OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); + if (ret != ERR_OK) { + errCode = -1; + return errCode; + } + } + if (userId != -1) { + BUNDLE_ACTIVE_LOGI("QueryAppNotificationNumber userid is %{public}d", userId); + AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + if ((CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId, errCode)) || + (AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) == + AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE)) { + errCode = bundleActiveCore_->QueryAppNotificationNumber(beginTime, endTime, eventStats, userId); + } + } + BUNDLE_ACTIVE_LOGI("QueryAppNotificationNumber result size is %{public}zu", eventStats.size()); + return errCode; +} + void BundleActiveService::QueryModuleRecordInfos(BundleActiveModuleRecord& moduleRecord) { if (!GetBundleMgrProxy()) { diff --git a/services/common/src/bundle_active_stub.cpp b/services/common/src/bundle_active_stub.cpp index ad5037c..7b14878 100644 --- a/services/common/src/bundle_active_stub.cpp +++ b/services/common/src/bundle_active_stub.cpp @@ -16,6 +16,7 @@ #include "bundle_active_stub.h" #include "bundle_active_package_stats.h" #include "bundle_active_event.h" +#include "bundle_active_event_stats.h" #include "bundle_active_module_record.h" namespace OHOS { @@ -142,6 +143,40 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me } return size == 0; } + case QUERY_EVENT_STATS: { + std::vector result; + int64_t beginTime = data.ReadInt64(); + int64_t endTime = data.ReadInt64(); + int32_t userId = data.ReadInt32(); + int32_t errCode = QueryEventStats(beginTime, endTime, result, userId); + int32_t size = static_cast(result.size()); + reply.WriteInt32(errCode); + reply.WriteInt32(size); + for (int32_t i = 0; i < size; i++) { + bool tmp = result[i].Marshalling(reply); + if (!tmp) { + return 1; + } + } + return size == 0; + } + case QUERY_APP_NOTIFICATION_NUMBER: { + std::vector result; + int64_t beginTime = data.ReadInt64(); + int64_t endTime = data.ReadInt64(); + int32_t userId = data.ReadInt32(); + int32_t errCode = QueryAppNotificationNumber(beginTime, endTime, result, userId); + int32_t size = static_cast(result.size()); + reply.WriteInt32(errCode); + reply.WriteInt32(size); + for (int32_t i = 0; i < size; i++) { + bool tmp = result[i].Marshalling(reply); + if (!tmp) { + return 1; + } + } + return size == 0; + } default: return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/services/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp index 2195f2e..aa8118f 100644 --- a/services/common/src/bundle_active_usage_database.cpp +++ b/services/common/src/bundle_active_usage_database.cpp @@ -1297,19 +1297,8 @@ vector BundleActiveUsageDatabase::QueryDatabaseEvents(int64_t { lock_guard lock(databaseMutex_); vector databaseEvents; - if (eventTableName_ == UNKNOWN_TABLE_NAME) { - BUNDLE_ACTIVE_LOGE("eventTable does not exist"); - return databaseEvents; - } - if (endTime <= beginTime) { - BUNDLE_ACTIVE_LOGE("endTime(%{public}lld) <= beginTime(%{public}lld)", - (long long)endTime, (long long)beginTime); - return databaseEvents; - } int64_t eventTableTime = ParseStartTime(eventTableName_); - if (endTime < eventTableTime) { - BUNDLE_ACTIVE_LOGE("endTime(%{public}lld) <= eventTableTime(%{public}lld)", - (long long)endTime, (long long)eventTableTime); + if (JudgeQueryCondition(beginTime, endTime, eventTableTime) == QUERY_CONDITION_INVALID) { return databaseEvents; } vector queryCondition; @@ -1597,6 +1586,131 @@ void BundleActiveUsageDatabase::LoadFormData(const int32_t userId, std::map& eventStats, int32_t userId) +{ + lock_guard lock(databaseMutex_); + int64_t eventTableTime = ParseStartTime(eventTableName_); + if (JudgeQueryCondition(beginTime, endTime, eventTableTime) == QUERY_CONDITION_INVALID) { + return; + } + vector queryCondition; + int64_t diff = beginTime - eventTableTime; + if (diff >= 0) { + queryCondition.push_back(to_string(diff)); + } else { + queryCondition.push_back(to_string(EVENT_TIME_IN_MILLIS_MIN)); + } + queryCondition.push_back(to_string(endTime - eventTableTime)); + queryCondition.push_back(to_string(userId)); + queryCondition.push_back(to_string(eventId)); + string queryEventSql = "select * from " + eventTableName_ + + " where timeStamp >= ? and timeStamp <= ? and userId = ? and eventId = ?"; + unique_ptr bundleActiveResult = QueryStatsInfoByStep(EVENT_DATABASE_INDEX, + queryEventSql, queryCondition); + if (bundleActiveResult == nullptr) { + return; + } + int32_t tableRowNumber; + bundleActiveResult->GetRowCount(tableRowNumber); + if (tableRowNumber == 0) { + return; + } + BundleActiveEventStats event; + event.name_= GetSystemEventName(eventId); + event.count_ = tableRowNumber; + event.eventId_ = eventId; + eventStats.insert(std::pair(event.name_, event)); +} + +std::string BundleActiveUsageDatabase::GetSystemEventName(const int32_t userId) +{ + std::string systemEventName = ""; + switch (userId) { + case BundleActiveEvent::SYSTEM_LOCK: + systemEventName = OPERATION_SYSTEM_LOCK; + break; + case BundleActiveEvent::SYSTEM_UNLOCK: + systemEventName = OPERATION_SYSTEM_UNLOCK; + break; + case BundleActiveEvent::SYSTEM_SLEEP: + systemEventName = OPERATION_SYSTEM_SLEEP; + break; + case BundleActiveEvent::SYSTEM_WAKEUP: + systemEventName = OPERATION_SYSTEM_WAKEUP; + break; + default: + break; + } + return systemEventName; +} + +void BundleActiveUsageDatabase::QueryAppNotificationNumber(int32_t eventId, int64_t beginTime, + int64_t endTime, std::map& notificationEventStats, int32_t userId) +{ + lock_guard lock(databaseMutex_); + int64_t eventTableTime = ParseStartTime(eventTableName_); + if (JudgeQueryCondition(beginTime, endTime, eventTableTime) == QUERY_CONDITION_INVALID) { + return; + } + vector queryCondition; + int64_t diff = beginTime - eventTableTime; + if (diff >= 0) { + queryCondition.push_back(to_string(diff)); + } else { + queryCondition.push_back(to_string(EVENT_TIME_IN_MILLIS_MIN)); + } + queryCondition.push_back(to_string(endTime - eventTableTime)); + queryCondition.push_back(to_string(userId)); + queryCondition.push_back(to_string(eventId)); + string queryEventSql = "select * from " + eventTableName_ + + " where timeStamp >= ? and timeStamp <= ? and userId = ? and eventId = ?"; + unique_ptr bundleActiveResult = QueryStatsInfoByStep(EVENT_DATABASE_INDEX, + queryEventSql, queryCondition); + if (bundleActiveResult == nullptr) { + return; + } + int32_t tableRowNumber; + bundleActiveResult->GetRowCount(tableRowNumber); + if (tableRowNumber == 0) { + return; + } + BundleActiveEventStats event; + std::map::iterator iter; + for (int32_t i = 0; i < tableRowNumber; i++) { + bundleActiveResult->GoToRow(i); + bundleActiveResult->GetString(BUNDLE_NAME_COLUMN_INDEX, event.name_); + bundleActiveResult->GetInt(EVENT_ID_COLUMN_INDEX, event.eventId_); + iter = notificationEventStats.find(event.name_); + if (iter != notificationEventStats.end()) { + iter->second.count_++; + } else { + event.count_ = 1; + notificationEventStats.insert(std::pair(event.name_, event)); + } + } +} + +int32_t BundleActiveUsageDatabase::JudgeQueryCondition(const int64_t beginTime, + const int64_t endTime, const int64_t eventTableTime) +{ + if (eventTableName_ == UNKNOWN_TABLE_NAME) { + BUNDLE_ACTIVE_LOGE("eventTable does not exist"); + return QUERY_CONDITION_INVALID; + } + if (endTime <= beginTime) { + BUNDLE_ACTIVE_LOGE("endTime(%{public}lld) <= beginTime(%{public}lld)", + (long long)endTime, (long long)beginTime); + return QUERY_CONDITION_INVALID; + } + if (endTime < eventTableTime) { + BUNDLE_ACTIVE_LOGE("endTime(%{public}lld) <= eventTableTime(%{public}lld)", + (long long)endTime, (long long)eventTableTime); + return QUERY_CONDITION_INVALID; + } + return QUERY_CONDITION_VALID; +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/packageusage/include/bundle_active_event.h b/services/packageusage/include/bundle_active_event.h index 57ce14b..963ca49 100644 --- a/services/packageusage/include/bundle_active_event.h +++ b/services/packageusage/include/bundle_active_event.h @@ -38,11 +38,15 @@ public: static const int32_t FLUSH = 12; static const int32_t SCREEN_INTERACTIVE = 13; static const int32_t SCREEN_NON_INTERACTIVE = 14; - static const int32_t KEYGUARD_SHOWN = 15; - static const int32_t KEYGUARD_HIDDEN = 16; - static const int32_t NOTIFICATION_SEEN = 17; - static const int32_t FORM_IS_CLICKED = 18; - static const int32_t FORM_IS_REMOVED = 19; + static const int32_t FORM_IS_CLICKED = 15; + static const int32_t FORM_IS_REMOVED = 16; + static const int32_t KEYGUARD_SHOWN = 17; + static const int32_t KEYGUARD_HIDDEN = 18; + static const int32_t NOTIFICATION_SEEN = 19; + static const int32_t SYSTEM_LOCK = 20; + static const int32_t SYSTEM_UNLOCK = 21; + static const int32_t SYSTEM_SLEEP = 22; + static const int32_t SYSTEM_WAKEUP = 23; inline static const std::string DEVICE_EVENT_PACKAGE_NAME = "openharmony"; std::string bundleName_; std::string continuousTaskAbilityName_; @@ -71,6 +75,11 @@ public: */ BundleActiveEvent(int32_t eventId, int64_t timeStamp); /* + * function: BundleActiveEvent, constructor using event Id, time stamp. + * parameters: eventId, bundleName. + */ + BundleActiveEvent(const int32_t eventId, const std::string bundleName); + /* * function: BundleActiveEvent, constructor of continuous task event. * parameters: bundleName, continuousTaskAbilityName */ diff --git a/services/packageusage/include/bundle_active_event_stats.h b/services/packageusage/include/bundle_active_event_stats.h index 34ee080..59360b7 100644 --- a/services/packageusage/include/bundle_active_event_stats.h +++ b/services/packageusage/include/bundle_active_event_stats.h @@ -20,7 +20,7 @@ namespace OHOS { namespace DeviceUsageStats { -class BundleActiveEventStats { +class BundleActiveEventStats : public Parcelable { public: int32_t eventId_; int64_t beginTimeStamp_; @@ -28,6 +28,8 @@ public: int64_t lastEventTime_; int64_t totalTime_; int32_t count_; + std::string name_; + /* * function: BundleActiveEventStats, default constructor. */ @@ -72,6 +74,20 @@ public: * parameters: right */ void add(const BundleActiveEventStats& right); + + /* + * function: Marshalling, mashalling event stats object to parcel. + * parameters: parcel + * return: result of mashalling, true means successful, flase means failed. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /* + * function: UnMarshalling, Unmashalling event stats object from parcel. + * parameters: parcel + * return: point to a BundleActiveEventStats. + */ + std::shared_ptr UnMarshalling(Parcel &parcel); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/packageusage/include/bundle_active_user_service.h b/services/packageusage/include/bundle_active_user_service.h index cb56fc9..c412f61 100644 --- a/services/packageusage/include/bundle_active_user_service.h +++ b/services/packageusage/include/bundle_active_user_service.h @@ -71,6 +71,10 @@ public: std::vector QueryEvents(const int64_t beginTime, const int64_t endTime, const int32_t userId, const std::string& bundleName); int32_t QueryFormStatistics(int32_t maxNum, std::vector& results); + int32_t QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId); + int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId); void LoadActiveStats(const int64_t timeStamp, const bool& force, const bool& timeChanged); void LoadModuleAndFormStats(); @@ -90,6 +94,10 @@ private: void PrintInMemPackageStats(const int32_t idx, const bool debug); void PrintInMemEventStats(const bool debug); void PrintInMemFormStats(const bool debug, const bool printform); + void GetCachedSystemEvents(std::shared_ptr currentStats, int64_t beginTime, + int64_t endTime, std::map& systemEventStats); + void GetCachedNotificationEvents(std::shared_ptr currentStats, int64_t beginTime, + int64_t endTime, std::map& notificationEventStats); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/packageusage/src/bundle_active_event.cpp b/services/packageusage/src/bundle_active_event.cpp index a96c4cf..c8451b7 100644 --- a/services/packageusage/src/bundle_active_event.cpp +++ b/services/packageusage/src/bundle_active_event.cpp @@ -59,6 +59,20 @@ BundleActiveEvent::BundleActiveEvent(int32_t eventId, int64_t timeStamp) eventId_ = eventId; } +BundleActiveEvent::BundleActiveEvent(const int32_t eventId, const std::string bundleName) +{ + bundleName_ = bundleName; + continuousTaskAbilityName_.clear(); + abilityName_.clear(); + abilityId_.clear(); + moduleName_.clear(); + formName_.clear(); + formDimension_ = 0; + formId_ = 0; + timeStamp_ = 0; + eventId_ = eventId; +} + BundleActiveEvent::BundleActiveEvent(const std::string bundleName, const std::string continuousTaskAbilityName) { bundleName_ = bundleName; diff --git a/services/packageusage/src/bundle_active_event_stats.cpp b/services/packageusage/src/bundle_active_event_stats.cpp index a433446..739019e 100644 --- a/services/packageusage/src/bundle_active_event_stats.cpp +++ b/services/packageusage/src/bundle_active_event_stats.cpp @@ -25,6 +25,7 @@ BundleActiveEventStats::BundleActiveEventStats() lastEventTime_ = 0; totalTime_ = 0; count_ = 0; + name_.clear(); } BundleActiveEventStats::BundleActiveEventStats(const BundleActiveEventStats& orig) @@ -35,6 +36,7 @@ BundleActiveEventStats::BundleActiveEventStats(const BundleActiveEventStats& ori lastEventTime_ = orig.lastEventTime_; totalTime_ = orig.totalTime_; count_ = orig.count_; + name_ = orig.name_; } int32_t BundleActiveEventStats::GetEventId() @@ -81,6 +83,33 @@ void BundleActiveEventStats::add(const BundleActiveEventStats& right) totalTime_ += right.totalTime_; count_ += right.count_; } + +bool BundleActiveEventStats::Marshalling(Parcel &parcel) const +{ + if (parcel.WriteInt32(eventId_) && + parcel.WriteInt64(beginTimeStamp_) && + parcel.WriteInt64(endTimeStamp_) && + parcel.WriteInt64(lastEventTime_) && + parcel.WriteInt64(totalTime_) && + parcel.WriteInt32(count_) && + parcel.WriteString(name_)) { + return true; + } + return false; +} + +std::shared_ptr BundleActiveEventStats::UnMarshalling(Parcel &parcel) +{ + std::shared_ptr result = std::make_shared(); + result->eventId_ = parcel.ReadInt32(); + result->beginTimeStamp_ = parcel.ReadInt64(); + result->endTimeStamp_ = parcel.ReadInt64(); + result->lastEventTime_ = parcel.ReadInt64(); + result->totalTime_ = parcel.ReadInt64(); + result->count_ = parcel.ReadInt32(); + result->name_ = parcel.ReadString(); + return result; +} } // 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 c79f1d6..9084d78 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -410,6 +410,117 @@ int32_t BundleActiveUserService::QueryFormStatistics(int32_t maxNum, std::vector return 0; } +int32_t BundleActiveUserService::QueryEventStats(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + BUNDLE_ACTIVE_LOGI("QueryEventStats called"); + auto currentStats = currentStats_[BundleActivePeriodStats::PERIOD_DAILY]; + if (currentStats == nullptr) { + BUNDLE_ACTIVE_LOGE("current interval stat is null!"); + return BUNDLE_ACTIVE_FAIL; + } + if (beginTime >= currentStats->endTime_) { + return BUNDLE_ACTIVE_FAIL; + } + std::map systemEventStats; + database_.QueryEventStats(BundleActiveEvent::SYSTEM_LOCK, beginTime, endTime, systemEventStats, userId); + database_.QueryEventStats(BundleActiveEvent::SYSTEM_UNLOCK, beginTime, endTime, systemEventStats, userId); + database_.QueryEventStats(BundleActiveEvent::SYSTEM_SLEEP, beginTime, endTime, systemEventStats, userId); + database_.QueryEventStats(BundleActiveEvent::SYSTEM_WAKEUP, beginTime, endTime, systemEventStats, userId); + BUNDLE_ACTIVE_LOGI("Query eventStats data in db result size is %{public}zu", systemEventStats.size()); + PrintInMemEventStats(debugUserService_); + // if we need a in-memory stats, combine current stats with result from database. + if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { + BUNDLE_ACTIVE_LOGI("QueryEventStats need in memory stats"); + GetCachedSystemEvents(currentStats, beginTime, endTime, systemEventStats); + } + std::map::iterator iter; + for (iter = systemEventStats.begin(); iter != systemEventStats.end(); iter++) { + eventStats.push_back(iter->second); + } + return BUNDLE_ACTIVE_SUCCESS; +} + +void BundleActiveUserService::GetCachedSystemEvents(std::shared_ptr currentStats, + int64_t beginTime, int64_t endTime, std::map& systemEventStats) +{ + int32_t eventBeginIdx = currentStats->events_.FindBestIndex(beginTime); + int32_t eventSize = currentStats->events_.Size(); + BundleActiveEventStats singleEventStats; + std::map::iterator iter; + for (int32_t i = eventBeginIdx; i < eventSize; i++) { + if ((currentStats->events_.events_[i].timeStamp_ <= endTime) + && ((currentStats->events_.events_[i].eventId_== BundleActiveEvent::SYSTEM_LOCK) + || (currentStats->events_.events_[i].eventId_== BundleActiveEvent::SYSTEM_UNLOCK) + || (currentStats->events_.events_[i].eventId_== BundleActiveEvent::SYSTEM_SLEEP) + || (currentStats->events_.events_[i].eventId_== BundleActiveEvent::SYSTEM_WAKEUP))) { + singleEventStats.name_ = currentStats->events_.events_[i].bundleName_; + iter = systemEventStats.find(singleEventStats.name_); + if (iter != systemEventStats.end()) { + iter->second.count_++; + } else { + singleEventStats.eventId_ = currentStats->events_.events_[i].eventId_; + singleEventStats.count_ = 1; + systemEventStats.insert(std::pair( + singleEventStats.name_, singleEventStats)); + } + } + } +} + +int32_t BundleActiveUserService::QueryAppNotificationNumber(int64_t beginTime, int64_t endTime, + std::vector& eventStats, int32_t userId) +{ + BUNDLE_ACTIVE_LOGI("QueryAppNotificationNumber called"); + auto currentStats = currentStats_[BundleActivePeriodStats::PERIOD_DAILY]; + if (currentStats == nullptr) { + BUNDLE_ACTIVE_LOGE("current interval stat is null!"); + return BUNDLE_ACTIVE_FAIL; + } + if (beginTime >= currentStats->endTime_) { + return BUNDLE_ACTIVE_FAIL; + } + std::map notificationEventStats; + database_.QueryAppNotificationNumber(BundleActiveEvent::NOTIFICATION_SEEN, + beginTime, endTime, notificationEventStats, userId); + BUNDLE_ACTIVE_LOGI("Query eventStats data in db result size is %{public}zu", notificationEventStats.size()); + PrintInMemEventStats(debugUserService_); + // if we need a in-memory stats, combine current stats with result from database. + if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { + BUNDLE_ACTIVE_LOGI("QueryAppNotificationNumber need in memory stats"); + GetCachedNotificationEvents(currentStats, beginTime, endTime, notificationEventStats); + } + std::map::iterator iter; + for (iter = notificationEventStats.begin(); iter != notificationEventStats.end(); iter++) { + eventStats.push_back(iter->second); + } + return BUNDLE_ACTIVE_SUCCESS; +} + +void BundleActiveUserService::GetCachedNotificationEvents(std::shared_ptr currentStats, + int64_t beginTime, int64_t endTime, std::map& notificationEventStats) +{ + int32_t eventBeginIdx = currentStats->events_.FindBestIndex(beginTime); + int32_t eventSize = currentStats->events_.Size(); + std::map::iterator iter; + BundleActiveEventStats singleEventStats; + for (int32_t i = eventBeginIdx; i < eventSize; i++) { + if ((currentStats->events_.events_[i].timeStamp_ <= endTime) + && (currentStats->events_.events_[i].eventId_== BundleActiveEvent::NOTIFICATION_SEEN)) { + singleEventStats.name_ = currentStats->events_.events_[i].bundleName_; + iter = notificationEventStats.find(singleEventStats.name_); + if (iter != notificationEventStats.end()) { + iter->second.count_++; + } else { + singleEventStats.eventId_ = BundleActiveEvent::NOTIFICATION_SEEN; + singleEventStats.count_ = 1; + notificationEventStats.insert(std::pair( + singleEventStats.name_, singleEventStats)); + } + } + } +} + void BundleActiveUserService::PrintInMemPackageStats(const int32_t idx, const bool debug) { if (!debug) { -- Gitee From 52cd46491b7a490aa08e475b86dbb91123ddadc3 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Sun, 29 May 2022 13:04:08 +0800 Subject: [PATCH 17/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- BUILD.gn | 8 + .../src/bundle_active_group_observer.cpp | 382 ++++++++++++++++++ frameworks/src/bundle_state_init.cpp | 6 +- frameworks/src/bundle_state_query.cpp | 184 ++++++++- .../innerkits/include/bundle_active_client.h | 19 +- .../bundle_active_group_callback_info.h | 88 ++++ .../bundle_active_group_callback_proxy.h | 46 +++ .../bundle_active_group_callback_stub.h | 47 +++ .../innerkits/include/bundle_active_proxy.h | 18 +- .../include/ibundle_active_group_callback.h | 48 +++ .../innerkits/src/bundle_active_client.cpp | 30 +- .../src/bundle_active_group_callback_info.cpp | 97 +++++ .../bundle_active_group_callback_proxy.cpp | 54 +++ .../src/bundle_active_group_callback_stub.cpp | 57 +++ .../innerkits/src/bundle_active_proxy.cpp | 65 ++- .../bundlestats/js/@ohos.bundleState.d.ts | 84 +++- .../include/bundle_active_group_observer.h | 58 +++ .../napi/include/bundle_state_data.h | 52 ++- .../napi/include/bundle_state_inner_errors.h | 1 + .../napi/include/bundle_state_query.h | 1 + .../device_usage_statistics_jsunit.test.js | 51 ++- services/common/include/bundle_active_core.h | 35 +- services/common/include/bundle_active_log.h | 12 +- .../common/include/bundle_active_service.h | 18 +- .../common/include/ibundle_active_service.h | 13 +- .../common/include/remote_death_recipient.h | 49 +++ services/common/src/bundle_active_core.cpp | 123 +++++- services/common/src/bundle_active_service.cpp | 93 ++++- services/common/src/bundle_active_stub.cpp | 29 +- .../include/bundle_active_group_controller.h | 9 +- .../include/bundle_active_user_history.h | 16 +- .../src/bundle_active_group_controller.cpp | 69 ++-- .../src/bundle_active_user_history.cpp | 67 +-- .../unittest/device_usage_statistics_test.cpp | 23 +- 34 files changed, 1783 insertions(+), 169 deletions(-) create mode 100644 frameworks/src/bundle_active_group_observer.cpp create mode 100644 interfaces/innerkits/include/bundle_active_group_callback_info.h create mode 100644 interfaces/innerkits/include/bundle_active_group_callback_proxy.h create mode 100644 interfaces/innerkits/include/bundle_active_group_callback_stub.h create mode 100644 interfaces/innerkits/include/ibundle_active_group_callback.h create mode 100644 interfaces/innerkits/src/bundle_active_group_callback_info.cpp create mode 100644 interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp create mode 100644 interfaces/innerkits/src/bundle_active_group_callback_stub.cpp create mode 100644 interfaces/kits/bundlestats/napi/include/bundle_active_group_observer.h create mode 100644 services/common/include/remote_death_recipient.h diff --git a/BUILD.gn b/BUILD.gn index 1a9d672..9e47f8a 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -31,6 +31,9 @@ config("usagestatsinner_public_config") { ohos_shared_library("usagestatsinner") { sources = [ "interfaces/innerkits/src/bundle_active_client.cpp", + "interfaces/innerkits/src/bundle_active_group_callback_info.cpp", + "interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp", + "interfaces/innerkits/src/bundle_active_group_callback_stub.cpp", "interfaces/innerkits/src/bundle_active_proxy.cpp", "services/packageusage/src/bundle_active_event.cpp", "services/packageusage/src/bundle_active_package_stats.cpp", @@ -58,6 +61,7 @@ ohos_prebuilt_etc("device_usage_statistics_service_init") { ohos_shared_library("bundlestate") { sources = [ + "frameworks/src/bundle_active_group_observer.cpp", "frameworks/src/bundle_state_common.cpp", "frameworks/src/bundle_state_init.cpp", "frameworks/src/bundle_state_query.cpp", @@ -67,6 +71,7 @@ ohos_shared_library("bundlestate") { "services/common/include", "interfaces/innerkits/include", "services/packageusage/include", + "services/packagegroup/include", ] deps = [ @@ -90,6 +95,8 @@ ohos_shared_library("bundlestate") { ohos_shared_library("usagestatservice") { cflags_cc = [] sources = [ + "interfaces/innerkits/src/bundle_active_group_callback_info.cpp", + "interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp", "services/common/src/bundle_active_account_helper.cpp", "services/common/src/bundle_active_app_state_obsever.cpp", "services/common/src/bundle_active_binary_search.cpp", @@ -125,6 +132,7 @@ ohos_shared_library("usagestatservice") { "services/common/include", "services/packageusage/include", "services/packagegroup/include", + "interfaces/innerkits/include", ] external_deps = [ diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp new file mode 100644 index 0000000..39a5b19 --- /dev/null +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -0,0 +1,382 @@ +/* + * 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 "securec.h" + +#include "bundle_active_log.h" +#include "bundle_state_common.h" +#include "bundle_state_data.h" +#include "bundle_state_inner_errors.h" +#include "bundle_active_group_callback_info.h" + +#include "bundle_active_group_observer.h" + +namespace OHOS { +namespace DeviceUsageStats { +const uint32_t UN_REGISTER_GROUP_CALLBACK_MIN_PARAMS = 0; +const uint32_t UN_REGISTER_GROUP_CALLBACK_PARAMS = 1; +const uint32_t REGISTER_GROUP_CALLBACK_MIN_PARAMS = 1; +const uint32_t REGISTER_GROUP_CALLBACK_PARAMS = 2; + +static sptr registerObserver = nullptr; + +BundleActiveGroupObserver::~BundleActiveGroupObserver() +{ + if (bundleGroupCallbackInfo_.ref) { + napi_delete_reference(bundleGroupCallbackInfo_.env, bundleGroupCallbackInfo_.ref); + } +} + +void BundleActiveGroupObserver::SetCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + bundleGroupCallbackInfo_.env = env; + bundleGroupCallbackInfo_.ref = ref; +} + +napi_value SetBundleGroupChangedData(const CallbackReceiveDataWorker *commonEventDataWorkerData, napi_value &result) +{ + BUNDLE_ACTIVE_LOGI("enter"); + + if (!commonEventDataWorkerData) { + BUNDLE_ACTIVE_LOGE("commonEventDataWorkerData is null"); + return nullptr; + } + napi_value value = nullptr; + + // oldGroup + napi_create_int32(commonEventDataWorkerData->env, commonEventDataWorkerData->oldGroup, &value); + napi_set_named_property(commonEventDataWorkerData->env, result, "oldGroup", value); + + // newGroup + napi_create_int32(commonEventDataWorkerData->env, commonEventDataWorkerData->newGroup, &value); + napi_set_named_property(commonEventDataWorkerData->env, result, "newGroup", value); + + // userId + napi_create_int32(commonEventDataWorkerData->env, commonEventDataWorkerData->userId, &value); + napi_set_named_property(commonEventDataWorkerData->env, result, "userId", value); + + // changeReason + napi_create_uint32(commonEventDataWorkerData->env, commonEventDataWorkerData->changeReason, &value); + napi_set_named_property(commonEventDataWorkerData->env, result, "changeReason", value); + // bundleName + napi_create_string_utf8( + commonEventDataWorkerData->env, commonEventDataWorkerData->bundleName.c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(commonEventDataWorkerData->env, result, "bundleName", value); + BUNDLE_ACTIVE_LOGI( + "oldGroup=%{public}d, newGroup=%{public}d, userId=%{public}d, changeReason=%{public}d, bundleName=%{public}s", + commonEventDataWorkerData->oldGroup, commonEventDataWorkerData->newGroup, commonEventDataWorkerData->userId, + commonEventDataWorkerData->changeReason, commonEventDataWorkerData->bundleName.c_str()); + + return BundleStateCommon::NapiGetNull(commonEventDataWorkerData->env); +} + +void UvQueueWorkOnBundleGroupChanged(uv_work_t *work, int status) +{ + BUNDLE_ACTIVE_LOGI("OnBundleGroupChanged uv_work_t start"); + if (!work) { + return; + } + CallbackReceiveDataWorker *callbackReceiveDataWorkerData = (CallbackReceiveDataWorker *)work->data; + if (!callbackReceiveDataWorkerData || !callbackReceiveDataWorkerData->ref) { + BUNDLE_ACTIVE_LOGE("OnBundleGroupChanged commonEventDataWorkerData or ref is null"); + delete work; + work = nullptr; + return; + } + + napi_value result = nullptr; + napi_create_object(callbackReceiveDataWorkerData->env, &result); + if (!SetBundleGroupChangedData(callbackReceiveDataWorkerData, result)) { + delete work; + work = nullptr; + delete callbackReceiveDataWorkerData; + callbackReceiveDataWorkerData = nullptr; + return; + } + + napi_value undefined = nullptr; + napi_get_undefined(callbackReceiveDataWorkerData->env, &undefined); + + napi_value callback = nullptr; + napi_value resultout = nullptr; + napi_get_reference_value(callbackReceiveDataWorkerData->env, callbackReceiveDataWorkerData->ref, &callback); + + napi_value results[ARGS_TWO] = {nullptr}; + results[PARAM_FIRST] = BundleStateCommon::GetErrorValue(callbackReceiveDataWorkerData->env, NO_ERROR); + results[PARAM_SECOND] = result; + NAPI_CALL_RETURN_VOID(callbackReceiveDataWorkerData->env, napi_call_function(callbackReceiveDataWorkerData->env, + undefined, callback, ARGS_TWO, &results[PARAM_FIRST], &resultout)); + delete callbackReceiveDataWorkerData; + callbackReceiveDataWorkerData = nullptr; + delete work; + work = nullptr; +} + +/* +* observer callback when group change +*/ +void BundleActiveGroupObserver::OnBundleGroupChanged(const BundleActiveGroupCallbackInfo &bundleActiveGroupCallbackInfo) +{ + BUNDLE_ACTIVE_LOGI("OnBundleGroupChanged start"); + + uv_loop_s *loop = nullptr; + napi_get_uv_event_loop(bundleGroupCallbackInfo_.env, &loop); + if (!loop) { + BUNDLE_ACTIVE_LOGE("loop instance is nullptr"); + return; + } + + uv_work_t *work = new (std::nothrow) uv_work_t; + if (!work) { + BUNDLE_ACTIVE_LOGE("work is null"); + return; + } + CallbackReceiveDataWorker *callbackReceiveDataWorker = new (std::nothrow) CallbackReceiveDataWorker(); + if (!callbackReceiveDataWorker) { + BUNDLE_ACTIVE_LOGE("callbackReceiveDataWorker is null"); + delete work; + work = nullptr; + return; + } + MessageParcel data; + if (!bundleActiveGroupCallbackInfo.Marshalling(data)) { + BUNDLE_ACTIVE_LOGE("Marshalling fail"); + } + BundleActiveGroupCallbackInfo* callBackInfo = bundleActiveGroupCallbackInfo.Unmarshalling(data); + callbackReceiveDataWorker->oldGroup = callBackInfo->GetOldGroup(); + callbackReceiveDataWorker->newGroup = callBackInfo->GetNewGroup(); + callbackReceiveDataWorker->changeReason = callBackInfo->GetChangeReason(); + callbackReceiveDataWorker->userId = callBackInfo->GetUserId(); + callbackReceiveDataWorker->bundleName = callBackInfo->GetBundleName(); + + callbackReceiveDataWorker->env = bundleGroupCallbackInfo_.env; + callbackReceiveDataWorker->ref = bundleGroupCallbackInfo_.ref; + + work->data = (void *)callbackReceiveDataWorker; + + BUNDLE_ACTIVE_LOGI("OnReceiveEvent this = %{public}p", this); + + uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnBundleGroupChanged); + delete callbackReceiveDataWorker; + callbackReceiveDataWorker = nullptr; + delete work; + work = nullptr; + + BUNDLE_ACTIVE_LOGI("OnBundleGroupChanged end"); +} + +napi_value GetBundleGroupChangeCallback( + const napi_env &env, const napi_value &value, BundleActiveGroupObserverInfo &bundleActiveGroupObserverInfo) +{ + napi_ref result = nullptr; + + bundleActiveGroupObserverInfo.callback = new (std::nothrow) BundleActiveGroupObserver(); + if (!bundleActiveGroupObserverInfo.callback) { + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack callback is null"); + return BundleStateCommon::NapiGetNull(env); + } + + napi_create_reference(env, value, 1, &result); + bundleActiveGroupObserverInfo.callback->SetCallbackInfo(env, result); + + return BundleStateCommon::NapiGetNull(env); +} + +napi_value ParseRegisterGroupCallBackParameters(const napi_env &env, const napi_callback_info &info, + RegisterCallbackInfo ¶ms, sptr &observer) +{ + BUNDLE_ACTIVE_LOGI("enter ParseRegisterGroupCallBackParameters"); + size_t argc = REGISTER_GROUP_CALLBACK_PARAMS; + napi_value argv[REGISTER_GROUP_CALLBACK_PARAMS] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NAPI_ASSERT(env, argc == REGISTER_GROUP_CALLBACK_MIN_PARAMS || argc == REGISTER_GROUP_CALLBACK_PARAMS, + "Invalid number of parameters"); + // arg[0] : callback + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "RegisterGroupCallBack Wrong argument type. Object expected."); + + BundleActiveGroupObserverInfo bundleActiveGroupObserverInfo; + if (!GetBundleGroupChangeCallback(env, argv[0], bundleActiveGroupObserverInfo)) { + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack bundleActiveGroupObserverInfo parse failed"); + return nullptr; + } + observer = bundleActiveGroupObserverInfo.callback; + + // argv[1]: asyncCallback + if (argc == REGISTER_GROUP_CALLBACK_PARAMS) { + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "ParseStatesParameters invalid parameter type. Function expected"); + napi_create_reference(env, argv[1], 1, ¶ms.callback); + } + return BundleStateCommon::NapiGetNull(env); +} + +napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) +{ + BUNDLE_ACTIVE_LOGI("enter RegisterGroupCallBack"); + RegisterCallbackInfo params; + ParseRegisterGroupCallBackParameters(env, info, params, registerObserver); + + if (params.errorCode != ERR_OK || !registerObserver) { + if (registerObserver) { + delete registerObserver; + registerObserver = nullptr; + } + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + napi_value promise = nullptr; + AsyncRegisterCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncRegisterCallbackInfo(env); + if (!asyncCallbackInfo) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + if (memset_s(asyncCallbackInfo, sizeof(AsyncRegisterCallbackInfo), 0, sizeof(AsyncRegisterCallbackInfo)) + != EOK) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + std::unique_ptr callbackPtr {asyncCallbackInfo}; + callbackPtr->observer = registerObserver; + BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); + + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, "RegisterGroupCallBack", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncRegisterCallbackInfo *asyncCallbackInfo = (AsyncRegisterCallbackInfo *)data; + if (asyncCallbackInfo) { + asyncCallbackInfo->state = + BundleActiveClient::GetInstance().RegisterGroupCallBack(asyncCallbackInfo->observer); + } else { + BUNDLE_ACTIVE_LOGE("QueryCurrentBundleActiveStates, asyncCallbackInfo == nullptr"); + } + }, + [](napi_env env, napi_status status, void *data) { + AsyncRegisterCallbackInfo *asyncCallbackInfo = (AsyncRegisterCallbackInfo *)data; + std::unique_ptr callbackPtr {asyncCallbackInfo}; + if (asyncCallbackInfo) { + napi_value result = nullptr; + napi_get_boolean(env, asyncCallbackInfo->state, &result); + BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); + } + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + callbackPtr.release(); + NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); + if (callbackPtr->isCallback) { + return BundleStateCommon::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value ParseUnRegisterGroupCallBackParameters(const napi_env &env, const napi_callback_info &info, + UnRegisterCallbackInfo ¶ms) +{ + size_t argc = UN_REGISTER_GROUP_CALLBACK_PARAMS; + napi_value argv[UN_REGISTER_GROUP_CALLBACK_PARAMS] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NAPI_ASSERT(env, argc == UN_REGISTER_GROUP_CALLBACK_MIN_PARAMS || argc == UN_REGISTER_GROUP_CALLBACK_PARAMS, + "Invalid number of parameters"); + + // argv[1]: callback + if (argc == UN_REGISTER_GROUP_CALLBACK_PARAMS) { + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "ParseStatesParameters invalid parameter type. " + "Function expected."); + napi_create_reference(env, argv[0], 1, ¶ms.callback); + } + return BundleStateCommon::NapiGetNull(env); +} + +napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) +{ + BUNDLE_ACTIVE_LOGI("enter UnRegisterGroupCallBack"); + if (!registerObserver) { + return BundleStateCommon::NapiGetNull(env); + } + + UnRegisterCallbackInfo params; + ParseUnRegisterGroupCallBackParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + + napi_value promise = nullptr; + AsyncUnRegisterCallbackInfo *asyncCallbackInfo = + new (std::nothrow) AsyncUnRegisterCallbackInfo(env); + if (!asyncCallbackInfo) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + if (memset_s(asyncCallbackInfo, sizeof(AsyncUnRegisterCallbackInfo), 0, sizeof(AsyncUnRegisterCallbackInfo)) + != EOK) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + std::unique_ptr callbackPtr {asyncCallbackInfo}; + callbackPtr->observer = registerObserver; + BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); + + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, "UnRegisterGroupCallBack", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncUnRegisterCallbackInfo *asyncCallbackInfo = (AsyncUnRegisterCallbackInfo *)data; + std::unique_ptr callbackPtr {asyncCallbackInfo}; + if (asyncCallbackInfo != nullptr) { + asyncCallbackInfo->state = + BundleActiveClient::GetInstance().UnregisterGroupCallBack(asyncCallbackInfo->observer); + } else { + BUNDLE_ACTIVE_LOGE("UnRegisterGroupCallBack, asyncCallbackInfo == nullptr"); + } + }, + [](napi_env env, napi_status status, void *data) { + AsyncUnRegisterCallbackInfo *asyncCallbackInfo = (AsyncUnRegisterCallbackInfo *)data; + if (asyncCallbackInfo != nullptr) { + napi_value result = nullptr; + napi_get_boolean(env, asyncCallbackInfo->state, &result); + BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); + } + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); + callbackPtr.release(); + if (callbackPtr->isCallback) { + return BundleStateCommon::NapiGetNull(env); + } else { + return promise; + } + delete registerObserver; + registerObserver = nullptr; +} +} // namespace DeviceUsageStats +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/src/bundle_state_init.cpp b/frameworks/src/bundle_state_init.cpp index 56e36f8..5274674 100644 --- a/frameworks/src/bundle_state_init.cpp +++ b/frameworks/src/bundle_state_init.cpp @@ -15,6 +15,7 @@ #include "bundle_state_condition.h" #include "bundle_state_query.h" +#include "bundle_active_group_observer.h" #include "bundle_state_init.h" namespace OHOS { @@ -40,7 +41,10 @@ static napi_value BundleStateInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("queryBundleActiveStates", QueryBundleActiveStates), DECLARE_NAPI_FUNCTION("queryBundleStateInfoByInterval", QueryBundleStateInfoByInterval), DECLARE_NAPI_FUNCTION("queryBundleStateInfos", QueryBundleStateInfos), - DECLARE_NAPI_FUNCTION("getRecentlyUsedModules", GetModuleUsageRecord) + DECLARE_NAPI_FUNCTION("getRecentlyUsedModules", GetModuleUsageRecord), + DECLARE_NAPI_FUNCTION("setBundleGroup", SetBundleGroup), + DECLARE_NAPI_FUNCTION("registerGroupCallBack", RegisterGroupCallBack), + DECLARE_NAPI_FUNCTION("unRegisterGroupCallBack", UnRegisterGroupCallBack), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index 7b840ef..8e7625d 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -19,6 +19,7 @@ #include "bundle_active_log.h" #include "bundle_state_common.h" #include "bundle_state_data.h" +#include "bundle_active_group_observer.h" #include "bundle_state_inner_errors.h" namespace OHOS { @@ -26,11 +27,14 @@ namespace DeviceUsageStats { const uint32_t IS_IDLE_STATE_MIN_PARAMS = 1; const uint32_t IS_IDLE_STATE_PARAMS = 2; const uint32_t PRIORITY_GROUP_MIN_PARAMS = 0; -const uint32_t PRIORITY_GROUP_PARAMS = 1; +const uint32_t PRIORITY_GROUP_MIDDLE_PARAMS = 1; +const uint32_t PRIORITY_GROUP_PARAMS = 2; const uint32_t STATES_MIN_PARAMS = 2; const uint32_t STATES_PARAMS = 3; const uint32_t APP_USAGE_MIN_PARAMS_BY_INTERVAL = 3; const uint32_t APP_USAGE_PARAMS_BY_INTERVAL = 4; +const uint32_t APP_USAGE_MIN_PARAMS_BUNDLE_GROUP = 2; +const uint32_t APP_USAGE_PARAMS_BUNDLE_GROUP = 3; const uint32_t APP_USAGE_MIN_PARAMS = 2; const uint32_t APP_USAGE_PARAMS = 3; const uint32_t MODULE_RECORDS_MIN_PARAMS = 0; @@ -39,6 +43,7 @@ const uint32_t MODULE_RECORDS_PARAMS = 2; const uint32_t SECOND_ARG = 2; const uint32_t THIRD_ARG = 3; const int32_t MAXNUM_UP_LIMIT = 1000; +const std::vector GROUP_TYPE {5, 10, 20, 30, 40, 50, 60}; napi_value ParseModuleRecordsParameters(const napi_env &env, const napi_callback_info &info, ModuleRecordParamsInfo ¶ms) @@ -245,16 +250,41 @@ napi_value ParsePriorityGroupParameters(const napi_env &env, const napi_callback size_t argc = PRIORITY_GROUP_PARAMS; napi_value argv[PRIORITY_GROUP_PARAMS] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_ASSERT(env, argc == PRIORITY_GROUP_MIN_PARAMS || argc == PRIORITY_GROUP_PARAMS, - "Invalid number of parameters"); - - // argv[0]: callback - if (argc == PRIORITY_GROUP_PARAMS) { + NAPI_ASSERT(env, argc == PRIORITY_GROUP_MIN_PARAMS || argc == PRIORITY_GROUP_MIDDLE_PARAMS || + argc == PRIORITY_GROUP_PARAMS, "Invalid number of parameters"); + std::string result = ""; + params.bundleName = ""; + if (argc == PRIORITY_GROUP_MIDDLE_PARAMS) { napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "ParsePriorityGroupParameters invalid parameter type. " - "Function expected."); - napi_create_reference(env, argv[0], 1, ¶ms.callback); + if (valuetype == napi_function) { + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "ParsePriorityGroupParameters invalid parameter type. " + "Function expected."); + napi_create_reference(env, argv[0], 1, ¶ms.callback); + } else { + params.bundleName = BundleStateCommon::GetTypeStringValue(env, argv[0], result); + if (params.bundleName.empty()) { + BUNDLE_ACTIVE_LOGE("ParsePriorityGroupParameters failed, bundleName is empty."); + params.errorCode = ERR_USAGE_STATS_BUNDLENAME_EMPTY; + } + } + } else if (argc == PRIORITY_GROUP_PARAMS) { + // argv[0] : bundleName + params.bundleName = BundleStateCommon::GetTypeStringValue(env, argv[0], result); + if (params.bundleName.empty()) { + BUNDLE_ACTIVE_LOGE("ParsePriorityGroupParameters failed, bundleName is empty."); + params.errorCode = ERR_USAGE_STATS_BUNDLENAME_EMPTY; + } + // argv[1]: callback + if (argc == PRIORITY_GROUP_PARAMS) { + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "ParsePriorityGroupParameters invalid parameter type. " + "Function expected."); + napi_create_reference(env, argv[1], 1, ¶ms.callback); + } } return BundleStateCommon::NapiGetNull(env); } @@ -263,6 +293,9 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) { PriorityGroupParamsInfo params; ParsePriorityGroupParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } napi_value promise = nullptr; AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoPriorityGroup(env); @@ -277,6 +310,9 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } std::unique_ptr callbackPtr {asyncCallbackInfo}; + callbackPtr->bundleName = params.bundleName; + BUNDLE_ACTIVE_LOGI("QueryAppUsagePriorityGroup QueryPackageGroup callbackPtr->bundleName: %{public}s", + callbackPtr->bundleName.c_str()); BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); napi_value resourceName = nullptr; NAPI_CALL(env, napi_create_string_latin1(env, "QueryAppUsagePriorityGroup", NAPI_AUTO_LENGTH, &resourceName)); @@ -285,15 +321,17 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; - if (asyncCallbackInfo != nullptr) { - asyncCallbackInfo->priorityGroup = BundleActiveClient::GetInstance().QueryPackageGroup(); + if (asyncCallbackInfo) { + asyncCallbackInfo->priorityGroup = + BundleActiveClient::GetInstance().QueryPackageGroup(asyncCallbackInfo->bundleName); } else { BUNDLE_ACTIVE_LOGE("QueryAppUsagePriorityGroup, asyncCallbackInfo == nullptr"); } }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; - if (asyncCallbackInfo != nullptr) { + std::unique_ptr callbackPtr {asyncCallbackInfo}; + if (asyncCallbackInfo) { napi_value result = nullptr; napi_create_int32(env, asyncCallbackInfo->priorityGroup, &result); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); @@ -302,11 +340,10 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); + callbackPtr.release(); if (callbackPtr->isCallback) { - callbackPtr.release(); return BundleStateCommon::NapiGetNull(env); } else { - callbackPtr.release(); return promise; } } @@ -413,7 +450,6 @@ napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info) }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { callbackPtr.release(); @@ -716,11 +752,125 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); + callbackPtr.release(); + if (callbackPtr->isCallback) { + return BundleStateCommon::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value ParseAppUsageBundleGroupInfoParameters(const napi_env &env, const napi_callback_info &info, + ParamsBundleGroupInfo ¶ms) +{ + BUNDLE_ACTIVE_LOGD("enter ParseAppUsageBundleGroupInfoParameters"); + size_t argc = APP_USAGE_PARAMS_BUNDLE_GROUP; + napi_value argv[APP_USAGE_PARAMS_BUNDLE_GROUP] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + NAPI_ASSERT(env, argc == APP_USAGE_MIN_PARAMS_BUNDLE_GROUP || argc == APP_USAGE_PARAMS_BUNDLE_GROUP, + "Invalid number of parameters"); + + // argv[0] : bundleName + std::string result = ""; + params.bundleName = BundleStateCommon::GetTypeStringValue(env, argv[0], result); + if (params.bundleName.empty()) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageBundleGroupInfoParameters failed, bundleName is empty."); + params.errorCode = ERR_USAGE_STATS_BUNDLENAME_EMPTY; + } + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + if ((valuetype != napi_string) && (params.errorCode == ERR_OK)) { + BUNDLE_ACTIVE_LOGE("Wrong argument type, string expected."); + params.errorCode = ERR_USAGE_STATS_BUNDLENAME_TYPE; + } + + // argv[1] : newGroup + if ((params.errorCode == ERR_OK) + && (BundleStateCommon::GetInt32NumberValue(env, argv[1], params.newGroup) == nullptr)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageBundleGroupInfoParameters failed, beginTime type is invalid."); + params.errorCode = ERR_USAGE_STATS_GROUP_INVALID; + } + bool flag = false; + if (params.errorCode == ERR_OK) { + for (const auto& item : GROUP_TYPE) { + if (item == params.newGroup) { + flag = true; + break; + } + } + } + if ((params.errorCode == ERR_OK) && !flag) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageBundleGroupInfoParameters failed, newGroup value is invalid."); + params.errorCode = ERR_USAGE_STATS_GROUP_INVALID; + } + + // argv[SECOND_ARG]: callback + if (params.errorCode == ERR_OK && argc == APP_USAGE_PARAMS_BUNDLE_GROUP) { + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[SECOND_ARG], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "ParseAppUsageBundleGroupInfoParameters invalid parameter type. " + "Function expected."); + napi_create_reference(env, argv[SECOND_ARG], 1, ¶ms.callback); + } + return BundleStateCommon::NapiGetNull(env); +} + +napi_value SetBundleGroup(napi_env env, napi_callback_info info) +{ + BUNDLE_ACTIVE_LOGI("enter SetBundleGroup"); + ParamsBundleGroupInfo params; + ParseAppUsageBundleGroupInfoParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + napi_value promise = nullptr; + AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = + new (std::nothrow) AsyncCallbackInfoSetBundleGroup(env); + if (!asyncCallbackInfo) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + if (memset_s(asyncCallbackInfo, sizeof(AsyncCallbackInfoSetBundleGroup), 0, sizeof(AsyncCallbackInfoSetBundleGroup)) + != EOK) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + std::unique_ptr callbackPtr {asyncCallbackInfo}; + callbackPtr->newGroup = params.newGroup; + callbackPtr->bundleName = params.bundleName; + BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); + napi_value resourceName = nullptr; + NAPI_CALL(env, napi_create_string_latin1(env, "SetBundleGroup", NAPI_AUTO_LENGTH, &resourceName)); + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = (AsyncCallbackInfoSetBundleGroup *)data; + if (asyncCallbackInfo) { + asyncCallbackInfo->state = BundleActiveClient::GetInstance().SetBundleGroup( + asyncCallbackInfo->bundleName, asyncCallbackInfo->newGroup, asyncCallbackInfo->errorCode); + } else { + BUNDLE_ACTIVE_LOGE("SetBundleGroup, asyncCallbackInfo == nullptr"); + } + }, + [](napi_env env, napi_status status, void *data) { + AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = (AsyncCallbackInfoSetBundleGroup *)data; + std::unique_ptr callbackPtr {asyncCallbackInfo}; + if (asyncCallbackInfo) { + napi_value result = nullptr; + napi_get_boolean(env, asyncCallbackInfo->state, &result); + BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); + } + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); + callbackPtr.release(); if (callbackPtr->isCallback) { - callbackPtr.release(); return BundleStateCommon::NapiGetNull(env); } else { - callbackPtr.release(); return promise; } } diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h index 3e60e1c..4232aca 100644 --- a/interfaces/innerkits/include/bundle_active_client.h +++ b/interfaces/innerkits/include/bundle_active_client.h @@ -19,7 +19,6 @@ #include "ibundle_active_service.h" #include "bundle_active_package_stats.h" #include "bundle_active_event.h" -#include "bundle_active_package_stats.h" #include "bundle_active_module_record.h" namespace OHOS { @@ -57,8 +56,9 @@ public: /* * function: SetBundleGroup, set specific bundle of specific user to a priority group. * parameters: bundleName, newGroup, userId + * return : void */ - void SetBundleGroup(std::string bundleName, const int32_t newGroup, const int32_t userId); + bool SetBundleGroup(std::string bundleName, const int32_t newGroup, int32_t errCode, int32_t userId = -1); /* * function: QueryCurrentPackageStats, query bundle usage statistics in specific time span for calling bundle. * parameters: intervalType, beginTime, endTime @@ -74,9 +74,10 @@ public: std::vector QueryCurrentEvents(const int64_t beginTime, const int64_t endTime); /* * function: QueryPackageGroup, query bundle priority group calling bundle. + * parameters: bundleName,userId * return: the priority group of calling bundle. */ - int32_t QueryPackageGroup(); + int32_t QueryPackageGroup(const std::string& bundleName, const int32_t userId = -1); /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, @@ -85,6 +86,18 @@ public: */ int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId = -1); /* + * function: observe bundle group change event + * parameters: observer + * return: errorcode. + */ + int32_t RegisterGroupCallBack(const sptr &observer); + /* + * function: unobserve bundle group change event + * parameters: observer + * return: errorcode. + */ + int32_t UnregisterGroupCallBack(const sptr &observer); + /* * function: GetInstance, get instance of client. * return: object of BundleActiveClient. */ diff --git a/interfaces/innerkits/include/bundle_active_group_callback_info.h b/interfaces/innerkits/include/bundle_active_group_callback_info.h new file mode 100644 index 0000000..b774fcf --- /dev/null +++ b/interfaces/innerkits/include/bundle_active_group_callback_info.h @@ -0,0 +1,88 @@ +/* + * 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_GROUP_CALLBACK_INFO_H +#define BUNDLE_ACTIVE_GROUP_CALLBACK_INFO_H + +#include +#include + +#include "parcel.h" + +namespace OHOS { +namespace DeviceUsageStats { +class BundleActiveGroupCallbackInfo : public Parcelable { +public: + BundleActiveGroupCallbackInfo() {}; + BundleActiveGroupCallbackInfo(int32_t userId, int32_t oldGroup, int32_t newGroup, uint32_t changeReason, + std::string bundleName); + + /** + * @brief Get the user id. + * + * @return The id of user. + */ + int32_t GetUserId() const; + + /** + * @brief Get the old group. + * + * @return old group of app. + */ + int32_t GetOldGroup() const; + + /** + * @brief Get the new group. + * + * @return the new group of app. + */ + int32_t GetNewGroup() const; + + /** + * @brief Get the reason of change group. + * + * @return the reason of change group. + */ + uint32_t GetChangeReason() const; + + /** + * @brief Get the name of bundle. + * + * @return The name of bundle. + */ + std::string GetBundleName() const; + + /** + * @brief Marshals a purpose into a parcel. + * + * @param parcel Indicates the parcel object for marshalling. + * @return True if success, else false. + */ + bool Marshalling(Parcel &parcel) const; + static BundleActiveGroupCallbackInfo* Unmarshalling(Parcel &parcel); + +private: + bool ReadFromParcel(Parcel &parcel); + +private: + int32_t oldGroup_ {0}; + int32_t newGroup_ {0}; + int32_t userId_ {-1}; + uint32_t changeReason_ {0}; + std::string bundleName_ {""}; +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_GROUP_CALLBACK_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/include/bundle_active_group_callback_proxy.h b/interfaces/innerkits/include/bundle_active_group_callback_proxy.h new file mode 100644 index 0000000..b287ff5 --- /dev/null +++ b/interfaces/innerkits/include/bundle_active_group_callback_proxy.h @@ -0,0 +1,46 @@ +/* + * 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_GROUP_CALLBACK_PROXY_H +#define BUNDLE_ACTIVE_GROUP_CALLBACK_PROXY_H + +#include "iremote_proxy.h" +#include "ibundle_active_group_callback.h" + +namespace OHOS { +namespace DeviceUsageStats { +class BundleActiveGroupCallbackProxy : public IRemoteProxy { +public: + /* + * function: default constructor. + */ + BundleActiveGroupCallbackProxy() = delete; + explicit BundleActiveGroupCallbackProxy(const sptr& impl); + virtual ~BundleActiveGroupCallbackProxy() override; + DISALLOW_COPY_AND_MOVE(BundleActiveGroupCallbackProxy); + /* + * function: OnBundleGroupChanged, bundleGroupChanged callback, IPC proxy, send message to stub. + * parameters: bundleActiveGroupCallbackInfo + * return: void. + */ + virtual void OnBundleGroupChanged( + const BundleActiveGroupCallbackInfo& continuousTaskCallbackInfo) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_GROUP_CALLBACK_PROXY_H \ No newline at end of file diff --git a/interfaces/innerkits/include/bundle_active_group_callback_stub.h b/interfaces/innerkits/include/bundle_active_group_callback_stub.h new file mode 100644 index 0000000..a748c87 --- /dev/null +++ b/interfaces/innerkits/include/bundle_active_group_callback_stub.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BUNDLE_ACTIVE_GROUP_CALLBACK_STUB_H +#define BUNDLE_ACTIVE_GROUP_CALLBACK_STUB_H + +#include "iremote_stub.h" +#include "ibundle_active_group_callback.h" + +namespace OHOS { +namespace DeviceUsageStats { +class BundleActiveGroupCallbackStub : public IRemoteStub { +public: + BundleActiveGroupCallbackStub()=default; + virtual ~BundleActiveGroupCallbackStub()=default; + /* + * function: OnRemoteRequest, handle message from proxy. + * parameters: code, data, reply, option + * return: errorcode. + */ + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + /* + * function: OnBundleGroupChanged, bundleGroupChanged callback, handle message from proxy. + * parameters: bundleActiveGroupCallbackInfo + * return: void. + */ + virtual void OnBundleGroupChanged( + const BundleActiveGroupCallbackInfo &bundleActiveGroupCallbackInfo) override; +private: + DISALLOW_COPY_AND_MOVE(BundleActiveGroupCallbackStub); +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // BUNDLE_ACTIVE_GROUP_CALLBACK_STUB_H diff --git a/interfaces/innerkits/include/bundle_active_proxy.h b/interfaces/innerkits/include/bundle_active_proxy.h index 50db119..3a1a34d 100644 --- a/interfaces/innerkits/include/bundle_active_proxy.h +++ b/interfaces/innerkits/include/bundle_active_proxy.h @@ -19,8 +19,8 @@ #include "ibundle_active_service.h" #include "bundle_active_event.h" #include "bundle_active_package_stats.h" -#include "bundle_active_package_stats.h" #include "bundle_active_module_record.h" +#include "ibundle_active_group_callback.h" namespace OHOS { namespace DeviceUsageStats { @@ -56,7 +56,7 @@ public: * function: SetBundleGroup, set specific bundle of specific user to a priority group. * parameters: bundleName, newGroup, userId */ - void SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t userId) override; + bool SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) override; /* * function: QueryCurrentPackageStats, query bundle usage statistics in specific time span for calling bundle. * parameters: intervalType, beginTime, endTime @@ -74,7 +74,7 @@ public: * function: QueryPackageGroup, query bundle priority group calling bundle. * return: the priority group of calling bundle. */ - int32_t QueryPackageGroup() override; + int32_t QueryPackageGroup(const std::string& bundleName, const int32_t userId) override; /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, @@ -90,6 +90,18 @@ public: explicit BundleActiveProxy(const sptr& impl) : IRemoteProxy(impl) {} /* + * function: RegisterGroupCallBack, register the observer to groupObservers. + * parameters: observer + * return: result of RegisterGroupCallBack, true or false. + */ + bool RegisterGroupCallBack(const sptr &observer) override; + /* + * function: UnregisterGroupCallBack, remove the observer from groupObservers. + * parameters: observer + * return: result of UnregisterGroupCallBack, true or false. + */ + bool UnregisterGroupCallBack(const sptr &observer) override; + /* * function: ~BundleActiveProxy, default destructor. */ virtual ~BundleActiveProxy() {} diff --git a/interfaces/innerkits/include/ibundle_active_group_callback.h b/interfaces/innerkits/include/ibundle_active_group_callback.h new file mode 100644 index 0000000..296ed9f --- /dev/null +++ b/interfaces/innerkits/include/ibundle_active_group_callback.h @@ -0,0 +1,48 @@ +/* + * 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 IBUNDLE_ACTIVE_GROUP_CALLBACK +#define IBUNDLE_ACTIVE_GROUP_CALLBACK + +#include +#include +#include "iremote_object.h" + +#include "bundle_active_log.h" +#include "bundle_active_group_callback_info.h" + +namespace OHOS { +namespace DeviceUsageStats { +class IBundleActiveGroupCallback : public IRemoteBroker { +public: + + /** + * @brief Called back when a continuous task stop. + * + * @param continuousTaskCallbackInfo Continuous task app info. + */ + virtual void OnBundleGroupChanged( + const BundleActiveGroupCallbackInfo &bundleActiveGroupCallbackInfo) = 0; +public: + DECLARE_INTERFACE_DESCRIPTOR(u"Resourceschedule.IBundleActiveGroupCallback"); + +protected: + enum class message { + ON_BUNDLE_GROUP_CHANGED = 1 + }; +}; +} // namespace BackgroundTaskMgr +} // namespace OHOS +#endif // IBUNDLE_ACTIVE_GROUP_CALLBACK \ No newline at end of file diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index ae9f263..56e90ff 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -85,13 +85,13 @@ std::vector BundleActiveClient::QueryEvents(const int64_t beg return bundleActiveProxy_->QueryEvents(beginTime, endTime, errCode, userId); } -void BundleActiveClient::SetBundleGroup(std::string bundleName, const int32_t newGroup, const int32_t userId) +bool BundleActiveClient::SetBundleGroup(std::string bundleName, const int32_t newGroup, + int32_t& errCode, int32_t userId) { if (!GetBundleActiveProxy()) { - return; + return false; } - bundleActiveProxy_->SetBundleGroup(bundleName, newGroup, userId); - return; + return bundleActiveProxy_->SetBundleGroup(bundleName, newGroup, errCode, userId); } std::vector BundleActiveClient::QueryCurrentPackageStats(const int32_t intervalType, @@ -111,12 +111,12 @@ std::vector BundleActiveClient::QueryCurrentEvents(const int6 return bundleActiveProxy_->QueryCurrentEvents(beginTime, endTime); } -int32_t BundleActiveClient::QueryPackageGroup() +int32_t BundleActiveClient::QueryPackageGroup(const std::string& bundleName, const int32_t userId) { if (!GetBundleActiveProxy()) { return -1; } - return bundleActiveProxy_->QueryPackageGroup(); + return bundleActiveProxy_->QueryPackageGroup(bundleName, userId); } int32_t BundleActiveClient::QueryFormStatistics(int32_t maxNum, std::vector& results, @@ -132,6 +132,24 @@ int32_t BundleActiveClient::QueryFormStatistics(int32_t maxNum, std::vectorQueryFormStatistics(maxNum, results, userId); } +int32_t BundleActiveClient::RegisterGroupCallBack(const sptr &observer) +{ + if (!GetBundleActiveProxy()) { + BUNDLE_ACTIVE_LOGE("GetBackgroundTaskManagerProxy failed."); + return false; + } + return bundleActiveProxy_->RegisterGroupCallBack(observer); +} + +int32_t BundleActiveClient::UnregisterGroupCallBack(const sptr &observer) +{ + if (!GetBundleActiveProxy()) { + BUNDLE_ACTIVE_LOGE("GetBackgroundTaskManagerProxy failed."); + return false; + } + return bundleActiveProxy_->UnregisterGroupCallBack(observer); +} + int32_t BundleActiveClient::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) { int32_t ret = -1; diff --git a/interfaces/innerkits/src/bundle_active_group_callback_info.cpp b/interfaces/innerkits/src/bundle_active_group_callback_info.cpp new file mode 100644 index 0000000..9e21f4c --- /dev/null +++ b/interfaces/innerkits/src/bundle_active_group_callback_info.cpp @@ -0,0 +1,97 @@ +/* + * 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 "bundle_active_log.h" +#include "bundle_active_group_callback_info.h" + +namespace OHOS { +namespace DeviceUsageStats { +BundleActiveGroupCallbackInfo::BundleActiveGroupCallbackInfo(int32_t userId, int32_t oldGroup, int32_t newGroup, + uint32_t changeReason, std::string bundleName) +{ + userId_ = userId; + oldGroup_ = oldGroup; + newGroup_ = newGroup; + changeReason_ = changeReason; + bundleName_ = bundleName; +} + +int32_t BundleActiveGroupCallbackInfo::GetUserId() const +{ + return userId_; +} + +int32_t BundleActiveGroupCallbackInfo::GetOldGroup() const +{ + return oldGroup_; +} + +int32_t BundleActiveGroupCallbackInfo::GetNewGroup() const +{ + return newGroup_; +} + +uint32_t BundleActiveGroupCallbackInfo::GetChangeReason() const +{ + return changeReason_; +} + +std::string BundleActiveGroupCallbackInfo::GetBundleName() const +{ + return bundleName_; +} + +bool BundleActiveGroupCallbackInfo::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(userId_)) { + BUNDLE_ACTIVE_LOGE("Failed to write userId_"); + return false; + } + + if (!parcel.WriteInt32(oldGroup_)) { + BUNDLE_ACTIVE_LOGE("Failed to write creator oldGroup_"); + return false; + } + + if (!parcel.WriteInt32(newGroup_)) { + BUNDLE_ACTIVE_LOGE("Failed to write creator newGroup_"); + return false; + } + + if (!parcel.WriteUint32(changeReason_)) { + BUNDLE_ACTIVE_LOGE("Failed to write creator changeReason_"); + return false; + } + + if (!parcel.WriteString(bundleName_)) { + BUNDLE_ACTIVE_LOGE("Failed to write bundleName_"); + return false; + } + return true; +} + +BundleActiveGroupCallbackInfo* BundleActiveGroupCallbackInfo::Unmarshalling(Parcel &parcel) +{ + BundleActiveGroupCallbackInfo* result = new (std::nothrow) BundleActiveGroupCallbackInfo(); + result->userId_ = parcel.ReadInt32(); + result->oldGroup_ = parcel.ReadInt32(); + result->newGroup_ = parcel.ReadInt32(); + result->changeReason_ = parcel.ReadUint32(); + result->bundleName_ = parcel.ReadString(); + return result; +} +} +} + diff --git a/interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp b/interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp new file mode 100644 index 0000000..5ba451b --- /dev/null +++ b/interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp @@ -0,0 +1,54 @@ +/* + * 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 "errors.h" +#include "bundle_active_log.h" +#include "bundle_active_group_callback_proxy.h" + +namespace OHOS { +namespace DeviceUsageStats { +BundleActiveGroupCallbackProxy::BundleActiveGroupCallbackProxy(const sptr& impl) + : IRemoteProxy(impl) {} +BundleActiveGroupCallbackProxy::~BundleActiveGroupCallbackProxy() {} + +void BundleActiveGroupCallbackProxy::OnBundleGroupChanged( + const BundleActiveGroupCallbackInfo &bundleActiveGroupCallbackInfo) +{ + sptr remote = Remote(); + if (remote == nullptr) { + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack remote is dead."); + return; + } + MessageParcel data; + if (!data.WriteInterfaceToken(BundleActiveGroupCallbackProxy::GetDescriptor())) { + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack write interface token failed."); + return; + } + if (!data.WriteParcelable(&bundleActiveGroupCallbackInfo)) { + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack write parcel failed."); + return; + } + MessageParcel reply; + MessageOption option = {MessageOption::TF_ASYNC}; + int32_t ret = remote->SendRequest( + static_cast(IBundleActiveGroupCallback::message::ON_BUNDLE_GROUP_CHANGED), data, reply, option); + if (ret!= ERR_OK) { + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack SendRequest failed, error code: %{public}d", ret); + } +} +} // namespace BackgroundTaskMgr +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp new file mode 100644 index 0000000..c8ef8ef --- /dev/null +++ b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp @@ -0,0 +1,57 @@ +/* + * 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 "bundle_active_group_callback_stub.h" + +namespace OHOS { +namespace DeviceUsageStats { +std::mutex BundleActiveGroupCallbackStub::callbackMutex_; +int32_t BundleActiveGroupCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply, + MessageOption &option) +{ + std::u16string descriptor = BundleActiveGroupCallbackStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack OnRemoteRequest cannot get power mgr service"); + return -1; + } + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack BundleActiveGroupCallbackStub will switch"); + switch (code) { + case static_cast(IBundleActiveGroupCallback::message::ON_BUNDLE_GROUP_CHANGED): { + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack OnRemoteRequest is nowing ON_BUNDLE_GROUP_CHANGED"); + BundleActiveGroupCallbackInfo* groupInfo = nullptr; + groupInfo = data.ReadParcelable(); + if (!groupInfo) { + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack ReadParcelable failed"); + return -1; + } + OnBundleGroupChanged(*groupInfo); + delete groupInfo; + groupInfo = nullptr; + break; + } + default: + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + return 0; +} + +void BundleActiveGroupCallbackStub::OnBundleGroupChanged( + const BundleActiveGroupCallbackInfo &bundleActiveGroupCallbackInfo) +{ +} +} // namespace DeviceUsageStats +} // namespace OHOS + diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index 43cfd63..9b84ba7 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -116,18 +116,22 @@ std::vector BundleActiveProxy::QueryEvents(const int64_t begi return result; } -void BundleActiveProxy::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t userId) +bool BundleActiveProxy::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) { + BUNDLE_ACTIVE_LOGI("SetBundleGroup enter bundleActiveProxy"); MessageParcel data; MessageParcel reply; MessageOption option; if (!data.WriteInterfaceToken(GetDescriptor())) { - return; + return false; } data.WriteString(bundleName); data.WriteInt32(newGroup); + data.WriteInt32(errCode); data.WriteInt32(userId); + Remote() -> SendRequest(SET_BUNDLE_GROUP, data, reply, option); + return reply.ReadInt32(); } std::vector BundleActiveProxy::QueryCurrentPackageStats(const int32_t intervalType, @@ -193,18 +197,20 @@ std::vector BundleActiveProxy::QueryCurrentEvents(const int64 return result; } -int32_t BundleActiveProxy::QueryPackageGroup() +int32_t BundleActiveProxy::QueryPackageGroup(const std::string& bundleName, const int32_t userId) { MessageParcel data; MessageParcel reply; MessageOption option; + if (!data.WriteInterfaceToken(GetDescriptor())) { return -1; } + data.WriteString(bundleName); + data.WriteInt32(userId); Remote() -> SendRequest(QUERY_BUNDLE_GROUP, data, reply, option); - int32_t packageGroup = reply.ReadInt32(); - BUNDLE_ACTIVE_LOGI("QueryPackageGroup result is %{public}d", packageGroup); - return packageGroup; + + return reply.ReadInt32(); } int32_t BundleActiveProxy::QueryFormStatistics(int32_t maxNum, std::vector& results, @@ -242,6 +248,53 @@ int32_t BundleActiveProxy::QueryFormStatistics(int32_t maxNum, std::vector &observer) +{ + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack enter proxy---------------------"); + if (!observer) { + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack observer null"); + return false; + } + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(GetDescriptor())) { + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack WriteInterfaceToken fail"); + return false; + } + if (!data.WriteRemoteObject(observer->AsObject())) { + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack observer write failed."); + return false; + } + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack proxy is ok"); + int32_t ret = Remote()->SendRequest(REGISTER_GROUP_CALLBACK, data, reply, option); + if (ret!= ERR_OK) { + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack SendRequest failed, error code: %{public}d", ret); + } + return true; +} + +bool BundleActiveProxy::UnregisterGroupCallBack(const sptr &observer) +{ + if (!observer) { + BUNDLE_ACTIVE_LOGE("observer null"); + return false; + } + BUNDLE_ACTIVE_LOGI("unRegisterApplicationStateObserver start"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(GetDescriptor())) { + return false; + } + if (!data.WriteRemoteObject(observer->AsObject())) { + BUNDLE_ACTIVE_LOGE("observer write failed."); + return false; + } + Remote()->SendRequest(UNREGISTER_GROUP_CALLBACK, data, reply, option); + return true; +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts index 100791b..b31dc89 100644 --- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts +++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { AsyncCallback } from './basic'; +import { AsyncCallback , Callback} from './basic'; /** * Provides methods for managing bundle usage statistics, @@ -204,6 +204,32 @@ declare namespace bundleState { */ stateType?: number; } + /** + * @since 7 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + */ + interface BundleActiveGroupCallbackInfo { + /* + * the usage old group of the application + */ + appUsageOldGroup?: number; + /* + * the usage new group of the application + */ + appUsageNewGroup?: number; + /* + * the use id + */ + useId?: number; + /* + * the change reason + */ + changeReason?: number; + /* + * the bundle name + */ + bundleName?: string; + } /** * Checks whether the application with a specified bundle name is in the idle state. @@ -218,19 +244,6 @@ declare namespace bundleState { function isIdleState(bundleName: string, callback: AsyncCallback): void; function isIdleState(bundleName: string): Promise; - /** - * Queries the usage priority group of the calling application. - * - *

The priority defined in a priority group restricts the resource usage of an application, - * for example, restricting the running of background tasks.

- * - * @since 7 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup - * @return Returns the usage priority group of the calling application. - */ - function queryAppUsagePriorityGroup(callback: AsyncCallback): void; - function queryAppUsagePriorityGroup(): Promise; - /** * @since 7 * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App @@ -343,6 +356,49 @@ declare namespace bundleState { */ function getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback>): void; function getRecentlyUsedModules(maxNum?: number): Promise>; + + /** + * Queries the usage priority group of the calling application. + * + *

The priority defined in a priority group restricts the resource usage of an application, + * for example, restricting the running of background tasks.

+ * + * @since 9 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + * @return Returns the usage priority group of the calling application. + */ + function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback): void; + function queryAppUsagePriorityGroup(bundleName? : string): Promise; + + /** + * set bundle group by bundleName and number. + * + * @since 9 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + * @return Returns the result of setBundleGroup, true of false. + */ + function setBundleGroup(bundleName: string, newGroup: number, callback: AsyncCallback): void; + function setBundleGroup(bundleName: string, newGroup: number): Promise; + + /** + * register callback to service. + * + * @since 9 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + * @return Returns BundleActiveGroupCallbackInfo when the group of bundle changed. the result of AsyncCallback is true or false. + */ + function registerGroupCallBack(callback: Callback, callback: AsyncCallback): void; + function registerGroupCallBack(callback: Callback): Promise; + + /** + * unRegister callback from service. + * + * @since 9 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + * @return Returns the result of unRegisterGroupCallBack, true of false. + */ + function unRegisterGroupCallBack(callback: AsyncCallback): void; + function unRegisterGroupCallBack(): Promise; } export default bundleState; diff --git a/interfaces/kits/bundlestats/napi/include/bundle_active_group_observer.h b/interfaces/kits/bundlestats/napi/include/bundle_active_group_observer.h new file mode 100644 index 0000000..3e7cd4f --- /dev/null +++ b/interfaces/kits/bundlestats/napi/include/bundle_active_group_observer.h @@ -0,0 +1,58 @@ +/* + * 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 FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_ACTIVE_GROUP_OBSERVER_H +#define FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_ACTIVE_GROUP_OBSERVER_H + +#include + +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "bundle_active_group_callback_stub.h" +#include "bundle_active_group_callback_info.h" + +namespace OHOS { +namespace DeviceUsageStats { +static const int8_t NO_ERROR = 0; + +class BundleActiveGroupObserver : public BundleActiveGroupCallbackStub { +public: + BundleActiveGroupObserver() =default; + + ~BundleActiveGroupObserver(); + + virtual void OnBundleGroupChanged(const BundleActiveGroupCallbackInfo &bundleActiveGroupCallbackInfo) override; + + void SetCallbackInfo(const napi_env &env, const napi_ref &ref); + +private: + struct BundleGroupCallbackInfo { + napi_env env = nullptr; + napi_ref ref = nullptr; + }; + BundleGroupCallbackInfo bundleGroupCallbackInfo_; +}; + +struct BundleActiveGroupObserverInfo { + napi_ref ref = nullptr; + sptr callback = nullptr; +}; + +napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info); +napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info); +} // namespace DeviceUsageStats +} // namespace OHOS + +#endif // FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_ACTIVE_GROUP_OBSERVER_H \ No newline at end of file diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h index b27b51d..2574fe7 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h @@ -24,6 +24,7 @@ #include "bundle_active_event.h" #include "bundle_active_package_stats.h" +#include "bundle_active_group_observer.h" namespace OHOS { namespace DeviceUsageStats { @@ -42,6 +43,8 @@ namespace DeviceUsageStats { #define INTERVAL_NUMBER_MIN 0 #define INTERVAL_NUMBER_MAX 4 #define TIME_NUMBER_MIN 0 +#define GROUP_NUMBER_MIN 5 +#define GROUP_NUMBER_MAX 50 struct AsyncWorkData { explicit AsyncWorkData(napi_env napiEnv); @@ -54,6 +57,16 @@ struct AsyncWorkData { int32_t errorCode = 0; }; +struct CallbackReceiveDataWorker { + napi_env env = nullptr; + napi_ref ref = nullptr; + int32_t oldGroup = 0; + int32_t newGroup = 0; + int32_t userId = -1; + uint32_t changeReason = 0; + std::string bundleName; +}; + struct AsyncCallbackInfoIsIdleState : public AsyncWorkData { explicit AsyncCallbackInfoIsIdleState(napi_env env) : AsyncWorkData(env) {} std::string bundleName = ""; @@ -62,7 +75,8 @@ struct AsyncCallbackInfoIsIdleState : public AsyncWorkData { struct AsyncCallbackInfoPriorityGroup : public AsyncWorkData { explicit AsyncCallbackInfoPriorityGroup(napi_env env) : AsyncWorkData(env) {} - int32_t priorityGroup = 60; + std::string bundleName = ""; + int32_t priorityGroup = -1; }; struct AsyncCallbackInfoStates : public AsyncWorkData { @@ -86,6 +100,12 @@ struct AsyncCallbackInfoAppUsage : public AsyncWorkData { int64_t endTime = -1; std::shared_ptr> packageStats; }; +struct AsyncCallbackInfoSetBundleGroup : public AsyncWorkData { + explicit AsyncCallbackInfoSetBundleGroup(napi_env env) : AsyncWorkData(env) {} + int32_t newGroup = -1;; + std::string bundleName = ""; + bool state = true; +}; struct AsyncCallbackInfoModuleRecord : public AsyncWorkData { explicit AsyncCallbackInfoModuleRecord(napi_env env) : AsyncWorkData(env) {} @@ -93,6 +113,18 @@ struct AsyncCallbackInfoModuleRecord : public AsyncWorkData { std::vector moduleRecords; }; +struct AsyncUnRegisterCallbackInfo : public AsyncWorkData { + explicit AsyncUnRegisterCallbackInfo(napi_env env) : AsyncWorkData(env) {} + sptr observer = nullptr; + bool state = true; +}; + +struct AsyncRegisterCallbackInfo : public AsyncWorkData { + explicit AsyncRegisterCallbackInfo(napi_env env) : AsyncWorkData(env) {} + sptr observer = nullptr; + bool state = true; +}; + struct IsIdleStateParamsInfo { std::string bundleName = ""; napi_ref callback = nullptr; @@ -100,6 +132,7 @@ struct IsIdleStateParamsInfo { }; struct PriorityGroupParamsInfo { + std::string bundleName; napi_ref callback = nullptr; int32_t errorCode = 0; }; @@ -131,6 +164,23 @@ struct ModuleRecordParamsInfo { napi_ref callback = nullptr; int32_t errorCode = 0; }; + +struct ParamsBundleGroupInfo { + std::string bundleName = ""; + int32_t newGroup = -1; + napi_ref callback = nullptr; + int32_t errorCode = 0; +}; + +struct RegisterCallbackInfo { + napi_ref callback = nullptr; + int32_t errorCode = 0; +}; + +struct UnRegisterCallbackInfo { + napi_ref callback = nullptr; + int32_t errorCode = 0; +}; } // namespace DeviceUsageStats } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_DATA_H diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h index 3576ab1..680b889 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h @@ -49,6 +49,7 @@ enum : int32_t { ERR_USAGE_STATS_TIME_INTERVAL, ERR_USAGE_STATS_INTERVAL_TYPE, ERR_USAGE_STATS_INTERVAL_NUMBER, + ERR_USAGE_STATS_GROUP_INVALID, ERR_MODULE_STATS_MAXNUM_INVALID, }; } // namespace DeviceUsageStats diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_query.h b/interfaces/kits/bundlestats/napi/include/bundle_state_query.h index 0a0492a..594d953 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_query.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_query.h @@ -28,6 +28,7 @@ namespace DeviceUsageStats { napi_value QueryBundleStateInfoByInterval(napi_env env, napi_callback_info info); napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info); napi_value GetModuleUsageRecord(napi_env env, napi_callback_info info); + napi_value SetBundleGroup(napi_env env, napi_callback_info info); } // namespace DeviceUsageStats } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_QUERY_H diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js index cf5f742..0c1a7ba 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -100,7 +100,9 @@ describe("DeviceUsageStatisticsJsTest", function () { */ it("DeviceUsageStatisticsJsTest003", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest003---------------------------'); - bundleState.queryAppUsagePriorityGroup().then( res => { + let bundleName = 'com.example.deviceUsageStatistics'; + let userId = 10; + bundleState.queryAppUsagePriorityGroup(bundleName, userId).then( res => { console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise success.'); expect(true).assertEqual(true); }).catch( err => { @@ -121,7 +123,9 @@ describe("DeviceUsageStatisticsJsTest", function () { */ it("DeviceUsageStatisticsJsTest004", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest004---------------------------'); - bundleState.queryAppUsagePriorityGroup((err, res) => { + let bundleName = 'com.example.deviceUsageStatistics'; + let userId = 10; + bundleState.queryAppUsagePriorityGroup(bundleName, userId, (err, res) => { if (err) { console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failure.'); expect(false).assertEqual(true); @@ -375,5 +379,48 @@ describe("DeviceUsageStatisticsJsTest", function () { done(); }, 500); }) + + it("DeviceUsageStatisticsJsTest015", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest015---------------------------'); + let bundleName = 'com.example.deviceUsageStatistics'; + let newGroup = 10; + bundleState.setBundleGroup(bundleName, newGroup, (err, res) => { + if (err) { + console.info('BUNDLE_ACTIVE setBundleGroup callback failure.'); + expect(false).assertEqual(true); + } else { + console.info('BUNDLE_ACTIVE setBundleGroup callback success.'); + expect(true).assertEqual(true); + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest015 + * @tc.desc: test getRecentlyUsedModules promise. + * @tc.type: FUNC + * @tc.require: SR000GU2UE AR0003GU3EQ + */ + + it("DeviceUsageStatisticsJsTest016", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest017---------------------------'); + bundleState.registerGroupCallBack((err, res) => { + if (err) { + console.info('BUNDLE_ACTIVE registerGroupCallBack callback failure.'); + expect(false).assertEqual(true); + } else { + console.info('BUNDLE_ACTIVE registerGroupCallBack callback success.'); + expect(true).assertEqual(true); + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) }) diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 3c861ce..749b042 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -19,10 +19,13 @@ #include #include "power_mgr_client.h" +#include "accesstoken_kit.h" #ifdef OS_ACCOUNT_PART_ENABLED #include "os_account_manager.h" #endif // OS_ACCOUNT_PART_ENABLED #include "ibundle_active_service.h" +#include "remote_death_recipient.h" +#include "ibundle_active_group_callback.h" #include "bundle_active_debug_mode.h" #include "bundle_active_stats_update_listener.h" #include "bundle_active_user_service.h" @@ -33,6 +36,8 @@ namespace OHOS { namespace DeviceUsageStats { +using namespace OHOS::Security; + class BundleActiveReportHandlerObject { public: BundleActiveEvent event_; @@ -46,7 +51,8 @@ public: class BundleActiveReportHandler; -class BundleActiveCore : public BundleActiveStatsUpdateListener { +class BundleActiveCore : public BundleActiveStatsUpdateListener, + public std::enable_shared_from_this { public: BundleActiveCore(); virtual ~BundleActiveCore(); @@ -124,7 +130,7 @@ public: // check the app idle state for calling user. int32_t IsBundleIdle(const std::string& bundleName, const int32_t userId); // query the app group for calling app. - int32_t QueryPackageGroup(const int32_t userId, const std::string bundleName); + int32_t QueryPackageGroup(const std::string bundleName, const int32_t userId); int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId); // get the wall time and check if the wall time is changed. int64_t CheckTimeChangeAndGetWallTime(int32_t userId = 0); @@ -138,16 +144,35 @@ public: // when user switched, restore old userdata. void OnUserSwitched(const int32_t userId); // force set app group. - void SetBundleGroup(const std::string& bundleName, const int32_t newGroup, const int32_t userId); + int32_t SetBundleGroup(const std::string& bundleName, const int32_t newGroup, const int32_t userId); // get all user in device. void GetAllActiveUser(std::vector& activatedOsAccountIds); // when service stop, call it to unregister commen event and shutdown call back. void UnRegisterSubscriber(); // get system time in MS. int64_t GetSystemTimeMs(); + /* + * function: RegisterGroupCallBack, register the observer to groupObservers. + * parameters: observer + * return: result of RegisterGroupCallBack, true or false. + */ + bool RegisterGroupCallBack(const AccessToken::AccessTokenID& tokenId, + const sptr &observer); + /* + * function: UnregisterGroupCallBack, remove the observer from groupObservers. + * parameters: observer + * return: result of UnregisterGroupCallBack, true or false. + */ + bool UnregisterGroupCallBack(const AccessToken::AccessTokenID& tokenId, + const sptr &observer); int32_t currentUsedUser_; + void OnBundleGroupChanged(const BundleActiveGroupCallbackInfo& callbackInfo); private: + void AddObserverDeathRecipient(const sptr &observer); + void RemoveObserverDeathRecipient(const sptr &observer); + void OnObserverDied(const wptr &remote); + void OnObserverDiedInner(const wptr &remote); int64_t flushInterval_; static const int64_t TIME_CHANGE_THRESHOLD_MILLIS = TWO_SECONDS; const int32_t DEFAULT_USER_ID = -1; @@ -159,10 +184,14 @@ private: int64_t systemTimeShot_; int64_t realTimeShot_; std::mutex mutex_; + std::mutex callbackMutex_; + std::mutex deathRecipientMutex_; std::map> userStatServices_; void RegisterSubscriber(); std::shared_ptr commonEventSubscriber_; void RestoreAllData(); + std::map> groupChangeObservers_; + std::map, sptr> recipientMap_; bool debugCore_; }; } // namespace DeviceUsageStats diff --git a/services/common/include/bundle_active_log.h b/services/common/include/bundle_active_log.h index 0dae499..4a19c08 100644 --- a/services/common/include/bundle_active_log.h +++ b/services/common/include/bundle_active_log.h @@ -60,7 +60,7 @@ private: static BundleActiveLogLevel logLevel_; }; -#define PRINT_LOG(LEVEL, Level, fmt, ...) \ +#define BUNDLE_ACTIVE_PRINT_LOG(LEVEL, Level, fmt, ...) \ if (BundleActiveLog::JudgeValidLevel(BundleActiveLogLevel::LEVEL)) \ OHOS::HiviewDFX::HiLog::Level(BUNDLE_ACTIVE_LOG_LABEL, \ "[%{public}s(%{public}s):%{public}d] " fmt, \ @@ -69,11 +69,11 @@ private: __LINE__, \ ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGD(fmt, ...) PRINT_LOG(DEBUG, Debug, fmt, ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGI(fmt, ...) PRINT_LOG(INFO, Info, fmt, ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGW(fmt, ...) PRINT_LOG(WARN, Warn, fmt, ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGE(fmt, ...) PRINT_LOG(ERROR, Error, fmt, ##__VA_ARGS__) -#define BUNDLE_ACTIVE_LOGF(fmt, ...) PRINT_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGD(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(DEBUG, Debug, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGI(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(INFO, Info, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGW(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(WARN, Warn, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGE(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(ERROR, Error, fmt, ##__VA_ARGS__) +#define BUNDLE_ACTIVE_LOGF(fmt, ...) BUNDLE_ACTIVE_PRINT_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) } // namespace DeviceUsageStats } // namespace OHOS #endif // BUNDLE_ACTIVE_LOG_H diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index e8921a4..b6ef191 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -75,7 +75,7 @@ public: * function: SetBundleGroup, set specific bundle of specific user to a priority group. * parameters: bundleName, newGroup, userId */ - void SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t userId) override; + bool SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t& errCode, int32_t userId) override; /* * function: QueryCurrentPackageStats, query bundle usage statistics in specific time span for calling bundle. * parameters: intervalType, beginTime, endTime @@ -93,7 +93,7 @@ public: * function: QueryPackageGroup, query bundle priority group calling bundle. * return: the priority group of calling bundle. */ - int32_t QueryPackageGroup() override; + int32_t QueryPackageGroup(const std::string& bundleName, int32_t userId) override; /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, @@ -107,6 +107,20 @@ public: * parameters: systemAbilityId, runOnCreate */ BundleActiveService(const int32_t systemAbilityId, bool runOnCreate); + /* + * function: RegisterGroupCallBack, register the observer to groupObservers. + * parameters: observer + * return: result of RegisterGroupCallBack, true or false. + */ + bool RegisterGroupCallBack(const sptr &observer) override; + /* + * function: UnregisterGroupCallBack, remove the observer from groupObservers. + * parameters: observer + * return: result of UnregisterGroupCallBack, true or false. + */ + bool UnregisterGroupCallBack(const sptr &observer) override; + +protected: /** * @brief The OnStart callback. */ diff --git a/services/common/include/ibundle_active_service.h b/services/common/include/ibundle_active_service.h index 63d332c..92fde69 100644 --- a/services/common/include/ibundle_active_service.h +++ b/services/common/include/ibundle_active_service.h @@ -33,6 +33,8 @@ #include "system_ability_definition.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" +#include "ibundle_active_group_callback.h" +#include "bundle_active_group_callback_proxy.h" #include "bundle_active_log.h" @@ -90,12 +92,12 @@ public: * function: QueryPackageGroup, query bundle priority group calling bundle. * return: the priority group of calling bundle. */ - virtual int32_t QueryPackageGroup() = 0; + virtual int32_t QueryPackageGroup(const std::string& bundleName, int32_t userId) = 0; /* * function: SetBundleGroup, set specific bundle of specific user to a priority group. * parameters: bundleName, newGroup, userId */ - virtual void SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t userId) = 0; + virtual bool SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) = 0; /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, @@ -105,6 +107,9 @@ public: virtual int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId) = 0; + virtual bool RegisterGroupCallBack(const sptr &observer) = 0; + virtual bool UnregisterGroupCallBack(const sptr &observer) = 0; + public: enum { REPORT_EVENT = 1, @@ -115,7 +120,9 @@ public: QUERY_CURRENT_EVENTS = 6, QUERY_BUNDLE_GROUP = 7, SET_BUNDLE_GROUP = 8, - QUERY_FORM_STATS = 9 + QUERY_FORM_STATS = 9, + REGISTER_GROUP_CALLBACK = 10, + UNREGISTER_GROUP_CALLBACK = 11 }; public: DECLARE_INTERFACE_DESCRIPTOR(u"Resourceschedule.IBundleActiveService"); diff --git a/services/common/include/remote_death_recipient.h b/services/common/include/remote_death_recipient.h new file mode 100644 index 0000000..3398e22 --- /dev/null +++ b/services/common/include/remote_death_recipient.h @@ -0,0 +1,49 @@ +/* + * 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 REMOTE_DEATH_RECIPIENT_H +#define REMOTE_DEATH_RECIPIENT_H + +#include + +#include "iremote_object.h" + +namespace OHOS { +namespace DeviceUsageStats { +class RemoteDeathRecipient : public IRemoteObject::DeathRecipient { +public: + explicit RemoteDeathRecipient(std::function &)> callback) + { + callback_ = callback; + } + + ~RemoteDeathRecipient() + { + callback_ = nullptr; + } + + void OnRemoteDied(const wptr &object) + { + if (callback_ != nullptr) { + callback_(object); + } + } + +private: + std::function &)> callback_; +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // REMOTE_DEATH_RECIPIENT_H \ No newline at end of file diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 15dcdc5..26c8402 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ #include "bundle_active_core.h" - +#include "accesstoken_kit.h" #include "time_service_client.h" #include "bundle_active_event.h" @@ -164,7 +164,7 @@ void BundleActiveCore::InitBundleGroupController() } if (bundleGroupController_ != nullptr && bundleGroupHandler_ != nullptr) { bundleGroupHandler_->Init(bundleGroupController_); - bundleGroupController_->SetHandlerAndCreateUserHistory(bundleGroupHandler_, realTimeShot_); + bundleGroupController_->SetHandlerAndCreateUserHistory(bundleGroupHandler_, realTimeShot_, shared_from_this()); BUNDLE_ACTIVE_LOGI("Init Set group controller and handler done"); } else { return; @@ -543,17 +543,17 @@ int32_t BundleActiveCore::QueryFormStatistics(int32_t maxNum, std::vector timer = MiscServices::TimeServiceClient::GetInstance(); int64_t bootBasedTimeStamp = timer->GetBootTimeMs(); - bundleGroupController_->SetBundleGroup(bundleName, userId, newGroup, newReason, bootBasedTimeStamp, false); + return bundleGroupController_->SetBundleGroup(bundleName, userId, newGroup, newReason, bootBasedTimeStamp); } -int32_t BundleActiveCore::QueryPackageGroup(const int32_t userId, const std::string bundleName) +int32_t BundleActiveCore::QueryPackageGroup(const std::string bundleName, const int32_t userId) { - return bundleGroupController_->QueryPackageGroup(userId, bundleName); + return bundleGroupController_->QueryPackageGroup(bundleName, userId); } int32_t BundleActiveCore::IsBundleIdle(const std::string& bundleName, const int32_t userId) @@ -596,6 +596,117 @@ int64_t BundleActiveCore::GetSystemTimeMs() } return static_cast(tarDate); } + +void BundleActiveCore::OnBundleGroupChanged(const BundleActiveGroupCallbackInfo& callbackInfo) +{ + std::lock_guard lock(callbackMutex_); + for (const auto &item : groupChangeObservers_) { + auto observer = item.second; + if (observer) { + BUNDLE_ACTIVE_LOGD( + "RegisterGroupCallBack will OnBundleGroupChanged!,oldGroup is %{public}d, newGroup is %{public}d", + callbackInfo.GetOldGroup(), callbackInfo.GetNewGroup()); + observer->OnBundleGroupChanged(callbackInfo); + } + } +} + +bool BundleActiveCore::RegisterGroupCallBack(const AccessToken::AccessTokenID& tokenId, + const sptr &observer) +{ + std::lock_guard lock(callbackMutex_); + if (!observer) { + BUNDLE_ACTIVE_LOGI("observer is null, return"); + return false; + } + auto item = groupChangeObservers_.find(tokenId); + if (item != groupChangeObservers_.end()) { + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack observer exist, return"); + return false; + } + groupChangeObservers_.emplace(tokenId, observer); + AddObserverDeathRecipient(observer); + BUNDLE_ACTIVE_LOGD("RegisterGroupCallBack number is %{public}d", static_cast(groupChangeObservers_.size())); + return true; +} + +bool BundleActiveCore::UnregisterGroupCallBack(const AccessToken::AccessTokenID& tokenId, + const sptr &observer) +{ + std::lock_guard lock(callbackMutex_); + auto item = groupChangeObservers_.find(tokenId); + if (item == groupChangeObservers_.end()) { + BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack observer is not exist, return"); + return false; + } + groupChangeObservers_.erase(tokenId); + RemoveObserverDeathRecipient(item->second); + return true; +} + +void BundleActiveCore::AddObserverDeathRecipient(const sptr &observer) +{ + std::lock_guard lock(deathRecipientMutex_); + if (!observer || !(observer->AsObject())) { + BUNDLE_ACTIVE_LOGI("observer nullptr."); + return; + } + auto remoteObj = observer->AsObject(); + auto it = recipientMap_.find(observer->AsObject()); + if (it != recipientMap_.end()) { + BUNDLE_ACTIVE_LOGI("This death recipient has been added."); + return; + } else { + sptr deathRecipient = new (std::nothrow) RemoteDeathRecipient( + [this](const wptr &remote) { this->OnObserverDied(remote); }); + if (!deathRecipient) { + BUNDLE_ACTIVE_LOGI("create death recipient failed"); + return ; + } + observer->AsObject()->AddDeathRecipient(deathRecipient); + recipientMap_.emplace(observer->AsObject(), deathRecipient); + } +} +void BundleActiveCore::RemoveObserverDeathRecipient(const sptr &observer) +{ + std::lock_guard lock(deathRecipientMutex_); + if (!observer || !(observer->AsObject())) { + return ; + } + auto iter = recipientMap_.find(observer->AsObject()); + if (iter != recipientMap_.end()) { + iter->first->RemoveDeathRecipient(iter->second); + recipientMap_.erase(iter); + return ; + } +} + +void BundleActiveCore::OnObserverDied(const wptr &remote) +{ + if (remote == nullptr) { + BUNDLE_ACTIVE_LOGE("remote object is null."); + return; + } + + bundleGroupHandler_->PostSyncTask([this, &remote]() { this->OnObserverDiedInner(remote); }); +} + +void BundleActiveCore::OnObserverDiedInner(const wptr &remote) +{ + std::lock_guard lock(deathRecipientMutex_); + sptr objectProxy = remote.promote(); + if (remote == nullptr || !objectProxy) { + BUNDLE_ACTIVE_LOGE("get remote object failed"); + return; + } + for (const auto& item : groupChangeObservers_) { + if ((item.second) && ((item.second)->AsObject()) && ((item.second)->AsObject() == objectProxy)) { + groupChangeObservers_.erase(item.first); + break; + } + } + recipientMap_.erase(objectProxy); +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index d211889..790e7cc 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -322,9 +322,28 @@ std::vector BundleActiveService::QueryEvents(const int64_t be return result; } -void BundleActiveService::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t userId) +bool BundleActiveService::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t& errCode, + int32_t userId) { - bundleActiveCore_->SetBundleGroup(bundleName, newGroup, userId); + bool result = false; + // get uid + int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); + AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + if (userId == -1) { + OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); + if (ret != ERR_OK) { + errCode = -1; + return result; + } + } + if (userId != -1) { + BUNDLE_ACTIVE_LOGI("SetBundleGroup userid is %{public}d", userId); + if (CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId, errCode) || + AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) == AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE) { + result = bundleActiveCore_->SetBundleGroup(bundleName, newGroup, userId); + } + } + return result; } @@ -388,31 +407,69 @@ std::vector BundleActiveService::QueryCurrentEvents(const int return result; } -int32_t BundleActiveService::QueryPackageGroup() +int32_t BundleActiveService::QueryPackageGroup(const std::string& bundleName, int32_t userId) { - BUNDLE_ACTIVE_LOGI("QueryPackageGroup stats called"); // get uid int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); BUNDLE_ACTIVE_LOGI("QueryPackageGroup UID is %{public}d", callingUid); - // get userid - int32_t userId = -1; + int32_t errCode = 0; int32_t result = -1; - OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); - BUNDLE_ACTIVE_LOGI("QueryPackageGroup user id is %{public}d", userId); - if (ret == ERR_OK && userId != -1) { - if (!GetBundleMgrProxy()) { - BUNDLE_ACTIVE_LOGE("get bundle manager proxy failed!"); + if (userId == -1) { + OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); + if (ret != ERR_OK) { + errCode = -1; return result; } - std::string bundleName = ""; - // get bundle name - sptrBundleMgr_->GetBundleNameForUid(callingUid, bundleName); - BUNDLE_ACTIVE_LOGI("QueryPackageGroup bundlename is %{public}s", bundleName.c_str()); + } + if (userId != -1) { + if (bundleName.empty()) { + std::string bundleName = ""; + sptrBundleMgr_->GetBundleNameForUid(callingUid, bundleName); + } if (!bundleName.empty()) { - result = bundleActiveCore_->QueryPackageGroup(userId, bundleName); + AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + if (CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId, errCode) || + AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) == + AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE) { + result = bundleActiveCore_->QueryPackageGroup(bundleName, userId); + } } } - BUNDLE_ACTIVE_LOGI("QueryPackageGroup result is %{public}d", result); + return result; +} + +bool BundleActiveService::RegisterGroupCallBack(const sptr &observer) +{ + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack enter bundleService"); + int result = false; + if (!bundleActiveCore_) { + return result; + } + int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); + AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + int32_t errCode = 0; + if (CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId, errCode) || + AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) == AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE) { + result = bundleActiveCore_->RegisterGroupCallBack(tokenId, observer); + } + return result; +} + +bool BundleActiveService::UnregisterGroupCallBack(const sptr &observer) +{ + int32_t result = false; + if (!bundleActiveCore_) { + return result; + } + + int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); + AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + int32_t errCode = 0; + if (CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId, errCode) || + AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) == AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE) { + result = bundleActiveCore_->UnregisterGroupCallBack(tokenId, observer); + } + return result; } @@ -453,7 +510,7 @@ bool BundleActiveService::CheckBundleIsSystemAppAndHasPermission(const int32_t u OHOS::Security::AccessToken::AccessTokenID tokenId, int32_t& errCode) { if (!GetBundleMgrProxy()) { - BUNDLE_ACTIVE_LOGE("Get bundle manager proxy failed!"); + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack Get bundle manager proxy failed!"); return false; } std::string bundleName = ""; diff --git a/services/common/src/bundle_active_stub.cpp b/services/common/src/bundle_active_stub.cpp index ad5037c..c707b4d 100644 --- a/services/common/src/bundle_active_stub.cpp +++ b/services/common/src/bundle_active_stub.cpp @@ -84,9 +84,10 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me case SET_BUNDLE_GROUP: { std::string bundleName = data.ReadString(); int32_t newGroup = data.ReadInt32(); + int32_t errCode = data.ReadInt32(); int32_t userId = data.ReadInt32(); - SetBundleGroup(bundleName, newGroup, userId); - return 0; + int32_t result = SetBundleGroup(bundleName, newGroup, errCode, userId); + return reply.WriteInt32(result); } case QUERY_CURRENT_USAGE_STATS: { std::vector result; @@ -122,8 +123,9 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me return size == 0; } case QUERY_BUNDLE_GROUP: { - int32_t result = -1; - result = QueryPackageGroup(); + std::string bundleName = data.ReadString(); + int32_t userId = data.ReadInt32(); + int32_t result = QueryPackageGroup(bundleName, userId); return reply.WriteInt32(result); } case QUERY_FORM_STATS: { @@ -142,6 +144,25 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me } return size == 0; } + case REGISTER_GROUP_CALLBACK: { + auto observer = iface_cast(data.ReadRemoteObject()); + if (!observer) { + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack observer is null, return"); + return false; + } + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack observer is ok"); + int32_t result = RegisterGroupCallBack(observer); + return reply.WriteInt32(result); + } + case UNREGISTER_GROUP_CALLBACK: { + auto observer = iface_cast(data.ReadRemoteObject()); + if (!observer) { + BUNDLE_ACTIVE_LOGE("unRegisterGroupCallBack observer is null, return"); + return false; + } + int32_t result = UnregisterGroupCallBack(observer); + return reply.WriteInt32(result); + } default: return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/services/packagegroup/include/bundle_active_group_controller.h b/services/packagegroup/include/bundle_active_group_controller.h index 0f534cd..6cfa429 100644 --- a/services/packagegroup/include/bundle_active_group_controller.h +++ b/services/packagegroup/include/bundle_active_group_controller.h @@ -32,7 +32,6 @@ namespace DeviceUsageStats { using namespace DeviceUsageStatsGroupConst; class BundleActiveGroupHandler; - class BundleActiveGroupController { public: using PowerMgrClient = OHOS::PowerMgr::PowerMgrClient; @@ -55,7 +54,7 @@ public: ~BundleActiveGroupController() {} std::shared_ptr bundleUserHistory_; void SetHandlerAndCreateUserHistory(const std::shared_ptr& groupHandler, - const int64_t bootFromTimeStamp); + const int64_t bootFromTimeStamp, const std::shared_ptr& bundleActiveCore); void ReportEvent(const BundleActiveEvent& event, const int64_t bootBasedTimeStamp, const int32_t userId); void CheckAndUpdateGroup(const std::string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp); bool CheckEachBundleState(const int32_t userId); @@ -64,14 +63,14 @@ public: void OnUserRemoved(const int32_t userId); void OnBundleUninstalled(const int32_t userId, const std::string bundleName); void OnScreenChanged(const bool& isScreenOn, const int64_t bootFromTimeStamp); - void SetBundleGroup(const std::string& bundleName, const int32_t userId, int32_t newGroup, uint32_t reason, - const int64_t bootBasedTimeStamp, const bool& resetTimeout); + int32_t SetBundleGroup(const std::string& bundleName, const int32_t userId, int32_t newGroup, uint32_t reason, + const int64_t bootBasedTimeStamp); void RestoreToDatabase(const int32_t userId); void RestoreDurationToDatabase(); bool IsBundleInstalled(const std::string& bundleName, const int32_t userId); bool IsScreenOn(); int32_t IsBundleIdle(const std::string& bundleName, const int32_t userId); - int32_t QueryPackageGroup(const int32_t userId, const std::string& bundleName); + int32_t QueryPackageGroup(const std::string& bundleName, const int32_t userId); void ShutDown(const int64_t bootBasedTimeStamp, const int32_t userId); void OnUserSwitched(const int32_t userId, const int32_t currentUsedUser); diff --git a/services/packagegroup/include/bundle_active_user_history.h b/services/packagegroup/include/bundle_active_user_history.h index 7279324..b661701 100644 --- a/services/packagegroup/include/bundle_active_user_history.h +++ b/services/packagegroup/include/bundle_active_user_history.h @@ -27,6 +27,7 @@ namespace OHOS { namespace DeviceUsageStats { using namespace DeviceUsageStatsGroupConst; +class BundleActiveCore; class BundleActiveUserHistory { public: @@ -36,11 +37,12 @@ public: int64_t screenOnTimeStamp_; int64_t ScreenOnDuration_; BundleActiveUsageDatabase database_; - BundleActiveUserHistory(const int64_t bootBasedTimeStamp); + BundleActiveUserHistory(const int64_t bootBasedTimeStamp, + const std::shared_ptr& bundleActiveCore); std::shared_ptr GetUsageHistoryForBundle(const std::string& bundleName, - const int32_t userId, const int64_t bootBasedTimeStamp, const bool& create); + const int32_t userId, const int64_t bootBasedTimeStamp, const bool create); std::shared_ptr>> GetUserHistory( - const int32_t userId, const bool& create); + const int32_t userId, const bool create); std::shared_ptr GetUsageHistoryInUserHistory(std::shared_ptr>> oneUserHistory, std::string bundleName, int64_t bootBasedTimeStamp, bool create); @@ -48,9 +50,9 @@ public: int64_t GetScreenOnTimeStamp(int64_t bootBasedTimeStamp); void ReportUsage(std::shared_ptr oneBundleUsageHistory, const std::string& bundleName, const int32_t newGroup, const uint32_t groupReason, const int64_t bootBasedTimeStamp, - const int64_t timeUntilNextCheck); - void SetBundleGroup(const std::string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, - int32_t newGroup, uint32_t groupReason, const bool& resetTimeout); + const int64_t timeUntilNextCheck, const int32_t userId); + int32_t SetBundleGroup(const std::string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, + int32_t newGroup, uint32_t groupReason); int32_t GetLevelIndex(const std::string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, const std::vector screenTimeLeve, const std::vector bootFromTimeLevel); void WriteDeviceDuration(); @@ -61,7 +63,9 @@ public: void OnBundleUninstalled(const int32_t userId, const std::string bundleName); private: + std::mutex setGroupMutex_; bool isScreenOn_; + std::weak_ptr bundleActiveCore_; }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index 2340866..677fe11 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -81,12 +81,13 @@ void BundleActiveGroupController::OnScreenChanged(const bool& isScreenOn, const } void BundleActiveGroupController::SetHandlerAndCreateUserHistory( - const std::shared_ptr& groupHandler, const int64_t bootFromTimeStamp) + const std::shared_ptr& groupHandler, const int64_t bootFromTimeStamp, + const std::shared_ptr& bundleActiveCore) { if (bundleUserHistory_ == nullptr) { BUNDLE_ACTIVE_LOGI("SetHandlerAndCreateUserHistory bundleUserHistory_ is null, " "called constructor, bootstamp is %{public}lld", (long long)bootFromTimeStamp); - bundleUserHistory_ = std::make_shared(bootFromTimeStamp); + bundleUserHistory_ = std::make_shared(bootFromTimeStamp, bundleActiveCore); } OnScreenChanged(IsScreenOn(), bootFromTimeStamp); activeGroupHandler_ = groupHandler; @@ -242,17 +243,17 @@ void BundleActiveGroupController::ReportEvent(const BundleActiveEvent& event, co switch (eventId) { case BundleActiveEvent::NOTIFICATION_SEEN: bundleUserHistory_->ReportUsage(bundleUsageHistory, event.bundleName_, ACTIVE_GROUP_DAILY, - eventReason, 0, bootBasedTimeStamp + timeoutForNotifySeen_); + eventReason, 0, bootBasedTimeStamp + timeoutForNotifySeen_, userId); timeUntilNextCheck = timeoutForNotifySeen_; break; case BundleActiveEvent::SYSTEM_INTERACTIVE: bundleUserHistory_->ReportUsage(bundleUsageHistory, event.bundleName_, ACTIVE_GROUP_ALIVE, - eventReason, 0, bootBasedTimeStamp + timeoutForSystemInteraction_); + eventReason, 0, bootBasedTimeStamp + timeoutForSystemInteraction_, userId); timeUntilNextCheck = timeoutForSystemInteraction_; break; default: bundleUserHistory_->ReportUsage(bundleUsageHistory, event.bundleName_, ACTIVE_GROUP_ALIVE, - eventReason, bootBasedTimeStamp, bootBasedTimeStamp + timeoutForDirectlyUse_); + eventReason, bootBasedTimeStamp, bootBasedTimeStamp + timeoutForDirectlyUse_, userId); timeUntilNextCheck = timeoutForDirectlyUse_; break; } @@ -308,40 +309,41 @@ void BundleActiveGroupController::CheckAndUpdateGroup(const std::string& bundleN } if (oldGroup < newGroup || notTimeout) { BUNDLE_ACTIVE_LOGI("CheckAndUpdateGroup called SetBundleGroup"); - bundleUserHistory_->SetBundleGroup(bundleName, userId, bootBasedTimeStamp, newGroup, groupReason, false); + bundleUserHistory_->SetBundleGroup(bundleName, userId, bootBasedTimeStamp, newGroup, groupReason); } } -void BundleActiveGroupController::SetBundleGroup(const std::string& bundleName, const int32_t userId, int32_t newGroup, - uint32_t reason, const int64_t bootBasedTimeStamp, const bool& resetTimeout) +int32_t BundleActiveGroupController::SetBundleGroup(const std::string& bundleName, const int32_t userId, + int32_t newGroup, uint32_t reason, const int64_t bootBasedTimeStamp) { std::lock_guard lock(mutex_); - if (IsBundleInstalled(bundleName, userId) == false) { - return; + if (!IsBundleInstalled(bundleName, userId)) { + return false; } auto oneBundleHistory = bundleUserHistory_->GetUsageHistoryForBundle(bundleName, userId, bootBasedTimeStamp, true); - if (oneBundleHistory->currentGroup_ < ACTIVE_GROUP_ALIVE) { - return; + if (!oneBundleHistory || (oneBundleHistory->currentGroup_ < ACTIVE_GROUP_ALIVE)) { + return false; } - int64_t bootBasedTimeStampAdjusted = bundleUserHistory_->GetBootBasedTimeStamp(bootBasedTimeStamp); - if (newGroup > ACTIVE_GROUP_ALIVE && oneBundleHistory->bundleAliveTimeoutTimeStamp_ > - bootBasedTimeStampAdjusted) { - BUNDLE_ACTIVE_LOGI("%{public}s should be decreased, but time out in alive is not expire! now is %{public}lld," - "timeout is %{public}lld", - bundleName.c_str(), - (long long)bootBasedTimeStampAdjusted, (long long)oneBundleHistory->bundleAliveTimeoutTimeStamp_); - newGroup = ACTIVE_GROUP_ALIVE; - reason = oneBundleHistory->reasonInGroup_; - } else if (newGroup > ACTIVE_GROUP_DAILY && oneBundleHistory->bundleDailyTimeoutTimeStamp_ > - bootBasedTimeStampAdjusted) { - newGroup = ACTIVE_GROUP_DAILY; - if (oneBundleHistory->currentGroup_ != newGroup) { - reason = GROUP_CONTROL_REASON_USAGE | GROUP_CONTROL_REASON_TIMEOUT; - } else { + if (reason != GROUP_CONTROL_REASON_FORCED) { + int64_t bootBasedTimeStampAdjusted = bundleUserHistory_->GetBootBasedTimeStamp(bootBasedTimeStamp); + if (newGroup > ACTIVE_GROUP_ALIVE && + oneBundleHistory->bundleAliveTimeoutTimeStamp_ > bootBasedTimeStampAdjusted) { + BUNDLE_ACTIVE_LOGI("%{public}s should be decreased, but time out in alive is not expire!" + "now is %{public}lld,timeout is %{public}lld", bundleName.c_str(), + (long long)bootBasedTimeStampAdjusted, (long long)oneBundleHistory->bundleAliveTimeoutTimeStamp_); + newGroup = ACTIVE_GROUP_ALIVE; reason = oneBundleHistory->reasonInGroup_; + } else if (newGroup > ACTIVE_GROUP_DAILY && + oneBundleHistory->bundleDailyTimeoutTimeStamp_ > bootBasedTimeStampAdjusted) { + newGroup = ACTIVE_GROUP_DAILY; + if (oneBundleHistory->currentGroup_ != newGroup) { + reason = GROUP_CONTROL_REASON_USAGE | GROUP_CONTROL_REASON_TIMEOUT; + } else { + reason = oneBundleHistory->reasonInGroup_; + } } } - bundleUserHistory_->SetBundleGroup(bundleName, userId, bootBasedTimeStamp, newGroup, reason, false); + return bundleUserHistory_->SetBundleGroup(bundleName, userId, bootBasedTimeStamp, newGroup, reason); } int32_t BundleActiveGroupController::IsBundleIdle(const std::string& bundleName, const int32_t userId) @@ -364,21 +366,22 @@ int32_t BundleActiveGroupController::IsBundleIdle(const std::string& bundleName, } } -int32_t BundleActiveGroupController::QueryPackageGroup(const int32_t userId, const std::string& bundleName) +int32_t BundleActiveGroupController::QueryPackageGroup(const std::string& bundleName, const int32_t userId) { BUNDLE_ACTIVE_LOGI("QueryPackageGroup called"); sptr timer = MiscServices::TimeServiceClient::GetInstance(); - if (IsBundleInstalled(bundleName, userId) == false) { + if (!IsBundleInstalled(bundleName, userId)) { + BUNDLE_ACTIVE_LOGI("QueryPackageGroup is not bundleInstalled"); return -1; } + int64_t bootBasedTimeStamp = timer->GetBootTimeMs(); auto oneBundleHistory = bundleUserHistory_->GetUsageHistoryForBundle( bundleName, userId, bootBasedTimeStamp, false); - if (oneBundleHistory == nullptr) { + if (!oneBundleHistory) { return -1; - } else { - return oneBundleHistory->currentGroup_; } + return oneBundleHistory->currentGroup_; } bool BundleActiveGroupController::IsBundleInstalled(const std::string& bundleName, const int32_t userId) diff --git a/services/packagegroup/src/bundle_active_user_history.cpp b/services/packagegroup/src/bundle_active_user_history.cpp index 42175f3..ee6841f 100644 --- a/services/packagegroup/src/bundle_active_user_history.cpp +++ b/services/packagegroup/src/bundle_active_user_history.cpp @@ -12,10 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#include "bundle_active_user_history.h" #include "bundle_active_group_common.h" #include "bundle_active_constant.h" +#include "bundle_active_core.h" +#include "bundle_active_group_callback_info.h" +#include "bundle_active_user_history.h" namespace OHOS { namespace DeviceUsageStats { @@ -56,7 +57,8 @@ void BundleActiveUserHistory::OnBundleUninstalled(const int32_t userId, const st database_.OnPackageUninstalled(userId, bundleName); } -BundleActiveUserHistory::BundleActiveUserHistory(const int64_t bootBasedTimeStamp) +BundleActiveUserHistory::BundleActiveUserHistory(const int64_t bootBasedTimeStamp, + const std::shared_ptr& bundleActiveCore) { bootBasedTimeStamp_ = bootBasedTimeStamp; screenOnTimeStamp_ = bootBasedTimeStamp; @@ -65,6 +67,9 @@ BundleActiveUserHistory::BundleActiveUserHistory(const int64_t bootBasedTimeStam bootBasedDuration_ = bootAndScreenOnDuraton.first; ScreenOnDuration_ = bootAndScreenOnDuraton.second; isScreenOn_ = false; + if (bundleActiveCore) { + bundleActiveCore_ = bundleActiveCore; + } } int32_t BundleActiveUserHistory::GetLevelIndex(const string& bundleName, const int32_t userId, @@ -107,13 +112,13 @@ int64_t BundleActiveUserHistory::GetScreenOnTimeStamp(int64_t bootBasedTimeStamp } shared_ptr>> BundleActiveUserHistory::GetUserHistory( - const int32_t userId, const bool& create) + const int32_t userId, const bool create) { auto it = userHistory_.find(userId); - if (it == userHistory_.end() && create) { + if ((it == userHistory_.end()) && create) { shared_ptr>> usageHistoryInserted = database_.GetBundleHistoryData(userId); - if (usageHistoryInserted == nullptr) { + if (!usageHistoryInserted) { BUNDLE_ACTIVE_LOGI("GetUserHistory READ FROM DATABASE FAILD"); usageHistoryInserted = make_shared>>(); @@ -126,13 +131,13 @@ shared_ptr>> BundleActiveUser shared_ptr BundleActiveUserHistory::GetUsageHistoryInUserHistory( shared_ptr>> oneUserHistory, - string bundleName, int64_t bootBasedTimeStamp, bool create) + string bundleName, int64_t bootBasedTimeStamp, const bool create) { - if (oneUserHistory == nullptr) { + if (!oneUserHistory) { return nullptr; } auto it = oneUserHistory->find(bundleName); - if (it == oneUserHistory->end() && create) { + if ((it == oneUserHistory->end()) && create) { shared_ptr usageHistoryInserted = make_shared(); usageHistoryInserted->lastBootFromUsedTimeStamp_ = GetBootBasedTimeStamp(bootBasedTimeStamp); @@ -147,14 +152,14 @@ shared_ptr BundleActiveUserHistory::GetUsageHistoryI } shared_ptr BundleActiveUserHistory::GetUsageHistoryForBundle( - const string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, const bool& create) + const string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, const bool create) { auto oneUserHistory = GetUserHistory(userId, create); - if (oneUserHistory == nullptr) { + if (!oneUserHistory) { return nullptr; } auto oneBundleHistory = GetUsageHistoryInUserHistory(oneUserHistory, bundleName, bootBasedTimeStamp, create); - if (oneBundleHistory == nullptr) { + if (!oneBundleHistory) { return nullptr; } return oneBundleHistory; @@ -162,7 +167,7 @@ shared_ptr BundleActiveUserHistory::GetUsageHistoryF void BundleActiveUserHistory::ReportUsage(shared_ptr oneBundleUsageHistory, const string& bundleName, const int32_t newGroup, const uint32_t groupReason, const int64_t bootBasedTimeStamp, - const int64_t timeUntilNextCheck) + const int64_t timeUntilNextCheck, const int32_t userId) { if (timeUntilNextCheck > bootBasedTimeStamp) { int64_t nextCheckTimeStamp = bootBasedDuration_ + (timeUntilNextCheck - bootBasedTimeStamp_); @@ -181,39 +186,51 @@ void BundleActiveUserHistory::ReportUsage(shared_ptr (bootBasedTimeStamp - bootBasedTimeStamp_); oneBundleUsageHistory->lastScreenUsedTimeStamp_ = GetScreenOnTimeStamp(bootBasedTimeStamp); } + int32_t oldGroup = oneBundleUsageHistory->currentGroup_; if (oneBundleUsageHistory->currentGroup_ > newGroup) { oneBundleUsageHistory->currentGroup_ = newGroup; } oneBundleUsageHistory->reasonInGroup_ = GROUP_CONTROL_REASON_USAGE | groupReason; oneBundleUsageHistory->isChanged_ = true; + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack will ReportUsage"); + BundleActiveGroupCallbackInfo callbackInfo( + userId, oldGroup, newGroup, oneBundleUsageHistory->reasonInGroup_, bundleName); + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack BundleActiveGroupCallbackInfo build success"); + if (!bundleActiveCore_.expired()) { + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack will callback!"); + bundleActiveCore_.lock()->OnBundleGroupChanged(callbackInfo); + } } -void BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int32_t userId, - const int64_t bootBasedTimeStamp, int32_t newGroup, uint32_t groupReason, const bool& resetTimeout) +int32_t BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int32_t userId, + const int64_t bootBasedTimeStamp, int32_t newGroup, uint32_t groupReason) { + std::lock_guard lock(setGroupMutex_); BUNDLE_ACTIVE_LOGI("set %{public}s to group %{public}d, reason is %{public}d, userId is %{public}d", bundleName.c_str(), newGroup, groupReason, userId); shared_ptr>> userBundleHistory = GetUserHistory(userId, false); - if (userBundleHistory == nullptr) { - return; + if (!userBundleHistory) { + return false; } shared_ptr oneBundleHistory = GetUsageHistoryInUserHistory(userBundleHistory, bundleName, bootBasedTimeStamp, false); - if (oneBundleHistory == nullptr) { - return; + if (!oneBundleHistory) { + return false; } 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; + return false; } + int32_t oldGroup = oneBundleHistory->currentGroup_; oneBundleHistory->currentGroup_ = newGroup; oneBundleHistory->reasonInGroup_ = groupReason; - int64_t setTimeStamp = GetBootBasedTimeStamp(bootBasedTimeStamp); - if (resetTimeout) { - oneBundleHistory->bundleAliveTimeoutTimeStamp_ = setTimeStamp; - oneBundleHistory->bundleDailyTimeoutTimeStamp_ = setTimeStamp; - } oneBundleHistory->isChanged_ = true; + BundleActiveGroupCallbackInfo callbackInfo( + userId, oldGroup, newGroup, oneBundleHistory->reasonInGroup_, bundleName); + if (!bundleActiveCore_.expired()) { + bundleActiveCore_.lock()->OnBundleGroupChanged(callbackInfo); + } + return true; } void BundleActiveUserHistory::UpdateBootBasedAndScreenTime(const bool& isScreenOn, const int64_t bootBasedTimeStamp, diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 9a4eca3..2baf288 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -25,6 +25,7 @@ #include "bundle_active_client.h" #include "bundle_active_event.h" +#include "bundle_active_group_callback_stub.h" using namespace testing::ext; @@ -39,6 +40,7 @@ static std::string DEFAULT_ABILITYID = "1234"; static std::string DEFAULT_ABILITYNAME = "testability"; static int32_t DEFAULT_USERID = 0; static int64_t LARGE_NUM = 20000000000000; +static int32_t DEFAULT_GROUP = 10; class DeviceUsageStatisticsTest : public testing::Test { public: @@ -154,11 +156,6 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_IsBundleIdle_001, * @tc.type: FUNC * @tc.require: */ -HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackageGroup_001, Function | MediumTest | Level0) -{ - int32_t result = BundleActiveClient::GetInstance().QueryPackageGroup(); - EXPECT_EQ(result, -1); -} /* * @tc.name: DeviceUsageStatisticsTest_QueryFormStatistics_001 @@ -177,6 +174,22 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryFormStatistic EXPECT_EQ(errCode, 0); EXPECT_EQ(results.size(), 0); } + +HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_SetBundleGroup_001, Function | MediumTest | Level0) +{ + bool result = BundleActiveClient::GetInstance().SetBundleGroup(DEFAULT_BUNDLENAME, DEFAULT_GROUP, DEFAULT_USERID); + EXPECT_EQ(result, true); +} + +HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_RegisterGroupCallBack_001, Function | MediumTest | Level0) +{ + auto observer=std::make_shared(); + if (!observer) { + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack construct observer!------------------------------"); + } + bool result = BundleActiveClient::GetInstance().RegisterGroupCallBack(observer.get()); + EXPECT_EQ(result, true); +} } // namespace DeviceUsageStats } // namespace OHOS -- Gitee From 4108f80877548ec6887fcba823827be9c600de4b Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Sun, 29 May 2022 15:19:36 +0800 Subject: [PATCH 18/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E5=88=86=E7=BB=84=E6=9F=A5=E8=AF=A2=E3=80=81?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E3=80=81=E7=9B=91=E5=90=AC=E6=B3=A8=E5=86=8C?= =?UTF-8?q?=E5=92=8C=E8=A7=A3=E6=B3=A8=E5=86=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- interfaces/innerkits/include/bundle_active_client.h | 3 --- interfaces/innerkits/src/bundle_active_client.cpp | 2 +- .../innerkits/src/bundle_active_group_callback_stub.cpp | 1 - services/common/include/bundle_active_core.h | 2 +- services/common/include/bundle_active_service.h | 2 +- services/common/src/bundle_active_core.cpp | 2 +- services/common/src/bundle_active_service.cpp | 2 +- .../packagegroup/include/bundle_active_group_controller.h | 2 +- services/packagegroup/include/bundle_active_user_history.h | 2 +- services/packagegroup/src/bundle_active_group_controller.cpp | 2 +- services/packagegroup/src/bundle_active_user_history.cpp | 4 +--- 11 files changed, 9 insertions(+), 15 deletions(-) diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h index 0b92fc3..c17f023 100644 --- a/interfaces/innerkits/include/bundle_active_client.h +++ b/interfaces/innerkits/include/bundle_active_client.h @@ -19,11 +19,8 @@ #include "ibundle_active_service.h" #include "bundle_active_package_stats.h" #include "bundle_active_event.h" -<<<<<<< HEAD -======= #include "bundle_active_event_stats.h" #include "bundle_active_package_stats.h" ->>>>>>> c717d1a3e77206b75b1c62a1857e23a05d78014c #include "bundle_active_module_record.h" namespace OHOS { diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 0e06d7b..cc7312c 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -86,7 +86,7 @@ std::vector BundleActiveClient::QueryEvents(const int64_t beg } bool BundleActiveClient::SetBundleGroup(std::string bundleName, const int32_t newGroup, - int32_t& errCode, int32_t userId) + int32_t errCode, int32_t userId) { if (!GetBundleActiveProxy()) { return false; diff --git a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp index c8ef8ef..5eadd17 100644 --- a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp +++ b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp @@ -17,7 +17,6 @@ namespace OHOS { namespace DeviceUsageStats { -std::mutex BundleActiveGroupCallbackStub::callbackMutex_; int32_t BundleActiveGroupCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply, MessageOption &option) { diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 7d160a8..50e4662 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -165,7 +165,7 @@ public: // when user switched, restore old userdata. void OnUserSwitched(const int32_t userId); // force set app group. - int32_t SetBundleGroup(const std::string& bundleName, const int32_t newGroup, const int32_t userId); + bool SetBundleGroup(const std::string& bundleName, const int32_t newGroup, const int32_t userId); // get all user in device. void GetAllActiveUser(std::vector& activatedOsAccountIds); // when service stop, call it to unregister commen event and shutdown call back. diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index d4ce2f6..77aeb83 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -75,7 +75,7 @@ public: * function: SetBundleGroup, set specific bundle of specific user to a priority group. * parameters: bundleName, newGroup, userId */ - bool SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t& errCode, int32_t userId) override; + bool SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) override; /* * function: QueryCurrentPackageStats, query bundle usage statistics in specific time span for calling bundle. * parameters: intervalType, beginTime, endTime diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index e689cc7..1df139e 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -649,7 +649,7 @@ int32_t BundleActiveCore::QueryAppNotificationNumber(int64_t beginTime, int64_t return errCode; } -void BundleActiveCore::SetBundleGroup(const std::string& bundleName, const int32_t newGroup, const int32_t userId) +bool BundleActiveCore::SetBundleGroup(const std::string& bundleName, const int32_t newGroup, const int32_t userId) { int32_t newReason = GROUP_CONTROL_REASON_FORCED; sptr timer = MiscServices::TimeServiceClient::GetInstance(); diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index d3ceb10..9c6dc3a 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -327,7 +327,7 @@ std::vector BundleActiveService::QueryEvents(const int64_t be return result; } -bool BundleActiveService::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t& errCode, +bool BundleActiveService::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) { bool result = false; diff --git a/services/packagegroup/include/bundle_active_group_controller.h b/services/packagegroup/include/bundle_active_group_controller.h index 6cfa429..0fe896e 100644 --- a/services/packagegroup/include/bundle_active_group_controller.h +++ b/services/packagegroup/include/bundle_active_group_controller.h @@ -63,7 +63,7 @@ public: void OnUserRemoved(const int32_t userId); void OnBundleUninstalled(const int32_t userId, const std::string bundleName); void OnScreenChanged(const bool& isScreenOn, const int64_t bootFromTimeStamp); - int32_t SetBundleGroup(const std::string& bundleName, const int32_t userId, int32_t newGroup, uint32_t reason, + bool SetBundleGroup(const std::string& bundleName, const int32_t userId, int32_t newGroup, uint32_t reason, const int64_t bootBasedTimeStamp); void RestoreToDatabase(const int32_t userId); void RestoreDurationToDatabase(); diff --git a/services/packagegroup/include/bundle_active_user_history.h b/services/packagegroup/include/bundle_active_user_history.h index b661701..c7e3e5d 100644 --- a/services/packagegroup/include/bundle_active_user_history.h +++ b/services/packagegroup/include/bundle_active_user_history.h @@ -51,7 +51,7 @@ public: void ReportUsage(std::shared_ptr oneBundleUsageHistory, const std::string& bundleName, const int32_t newGroup, const uint32_t groupReason, const int64_t bootBasedTimeStamp, const int64_t timeUntilNextCheck, const int32_t userId); - int32_t SetBundleGroup(const std::string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, + bool SetBundleGroup(const std::string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, int32_t newGroup, uint32_t groupReason); int32_t GetLevelIndex(const std::string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, const std::vector screenTimeLeve, const std::vector bootFromTimeLevel); diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index 677fe11..54dc3d1 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -313,7 +313,7 @@ void BundleActiveGroupController::CheckAndUpdateGroup(const std::string& bundleN } } -int32_t BundleActiveGroupController::SetBundleGroup(const std::string& bundleName, const int32_t userId, +bool BundleActiveGroupController::SetBundleGroup(const std::string& bundleName, const int32_t userId, int32_t newGroup, uint32_t reason, const int64_t bootBasedTimeStamp) { std::lock_guard lock(mutex_); diff --git a/services/packagegroup/src/bundle_active_user_history.cpp b/services/packagegroup/src/bundle_active_user_history.cpp index ee6841f..93fb2a1 100644 --- a/services/packagegroup/src/bundle_active_user_history.cpp +++ b/services/packagegroup/src/bundle_active_user_history.cpp @@ -12,8 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "bundle_active_group_common.h" -#include "bundle_active_constant.h" #include "bundle_active_core.h" #include "bundle_active_group_callback_info.h" #include "bundle_active_user_history.h" @@ -202,7 +200,7 @@ void BundleActiveUserHistory::ReportUsage(shared_ptr } } -int32_t BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int32_t userId, +bool BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, int32_t newGroup, uint32_t groupReason) { std::lock_guard lock(setGroupMutex_); -- Gitee From 9e4811fc61dcef4d13a4d681cb6e6d60d227564f Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Mon, 30 May 2022 21:35:46 +0800 Subject: [PATCH 19/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E9=97=AE=E9=A2=98=E4=BF=AE=E5=A4=8D1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../src/bundle_active_group_observer.cpp | 31 +++++++------- frameworks/src/bundle_state_query.cpp | 17 ++++---- .../innerkits/include/bundle_active_client.h | 2 +- .../innerkits/include/bundle_active_proxy.h | 2 +- .../innerkits/src/bundle_active_client.cpp | 6 ++- .../bundle_active_group_callback_proxy.cpp | 2 - .../src/bundle_active_group_callback_stub.cpp | 4 +- .../innerkits/src/bundle_active_proxy.cpp | 7 ++-- .../bundlestats/js/@ohos.bundleState.d.ts | 41 ++++++++++++++++++- .../common/include/bundle_active_service.h | 2 +- .../common/include/ibundle_active_service.h | 2 +- services/common/src/bundle_active_core.cpp | 5 ++- services/common/src/bundle_active_service.cpp | 17 +++++--- .../src/bundle_active_group_controller.cpp | 24 ++--------- .../src/bundle_active_user_history.cpp | 4 ++ 15 files changed, 102 insertions(+), 64 deletions(-) diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index 39a5b19..2b48c1e 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -78,7 +78,8 @@ napi_value SetBundleGroupChangedData(const CallbackReceiveDataWorker *commonEven commonEventDataWorkerData->env, commonEventDataWorkerData->bundleName.c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(commonEventDataWorkerData->env, result, "bundleName", value); BUNDLE_ACTIVE_LOGI( - "oldGroup=%{public}d, newGroup=%{public}d, userId=%{public}d, changeReason=%{public}d, bundleName=%{public}s", + "RegisterGroupCallBack oldGroup=%{public}d, newGroup=%{public}d, userId=%{public}d, " + "changeReason=%{public}d, bundleName=%{public}s", commonEventDataWorkerData->oldGroup, commonEventDataWorkerData->newGroup, commonEventDataWorkerData->userId, commonEventDataWorkerData->changeReason, commonEventDataWorkerData->bundleName.c_str()); @@ -171,12 +172,13 @@ void BundleActiveGroupObserver::OnBundleGroupChanged(const BundleActiveGroupCall BUNDLE_ACTIVE_LOGI("OnReceiveEvent this = %{public}p", this); - uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnBundleGroupChanged); - delete callbackReceiveDataWorker; - callbackReceiveDataWorker = nullptr; - delete work; - work = nullptr; - + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnBundleGroupChanged); + if (ret != 0) { + delete callbackReceiveDataWorker; + callbackReceiveDataWorker = nullptr; + delete work; + work = nullptr; + } BUNDLE_ACTIVE_LOGI("OnBundleGroupChanged end"); } @@ -269,12 +271,11 @@ napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) asyncCallbackInfo->state = BundleActiveClient::GetInstance().RegisterGroupCallBack(asyncCallbackInfo->observer); } else { - BUNDLE_ACTIVE_LOGE("QueryCurrentBundleActiveStates, asyncCallbackInfo == nullptr"); + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack, asyncCallbackInfo == nullptr"); } }, [](napi_env env, napi_status status, void *data) { AsyncRegisterCallbackInfo *asyncCallbackInfo = (AsyncRegisterCallbackInfo *)data; - std::unique_ptr callbackPtr {asyncCallbackInfo}; if (asyncCallbackInfo) { napi_value result = nullptr; napi_get_boolean(env, asyncCallbackInfo->state, &result); @@ -283,11 +284,12 @@ napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork)); - callbackPtr.release(); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { + callbackPtr.release(); return BundleStateCommon::NapiGetNull(env); } else { + callbackPtr.release(); return promise; } } @@ -342,7 +344,7 @@ napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->observer = registerObserver; BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); - + BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack will Async"); napi_value resourceName = nullptr; NAPI_CALL(env, napi_create_string_latin1(env, "UnRegisterGroupCallBack", NAPI_AUTO_LENGTH, &resourceName)); NAPI_CALL(env, napi_create_async_work(env, @@ -350,7 +352,6 @@ napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { AsyncUnRegisterCallbackInfo *asyncCallbackInfo = (AsyncUnRegisterCallbackInfo *)data; - std::unique_ptr callbackPtr {asyncCallbackInfo}; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->state = BundleActiveClient::GetInstance().UnregisterGroupCallBack(asyncCallbackInfo->observer); @@ -369,14 +370,14 @@ napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); - callbackPtr.release(); if (callbackPtr->isCallback) { + callbackPtr.release(); return BundleStateCommon::NapiGetNull(env); } else { + callbackPtr.release(); return promise; } - delete registerObserver; - registerObserver = nullptr; + } } // 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 663deae..8dc58bb 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -43,7 +43,7 @@ const uint32_t MODULE_RECORDS_PARAMS = 2; const uint32_t SECOND_ARG = 2; const uint32_t THIRD_ARG = 3; const int32_t MAXNUM_UP_LIMIT = 1000; -const std::vector GROUP_TYPE {5, 10, 20, 30, 40, 50, 60}; +const std::vector GROUP_TYPE {10, 20, 30, 40, 50, 60}; const uint32_t EVENT_STATES_MIN_PARAMS = 2; const uint32_t EVENT_STATES_PARAMS = 3; @@ -313,7 +313,7 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->bundleName = params.bundleName; - BUNDLE_ACTIVE_LOGI("QueryAppUsagePriorityGroup QueryPackageGroup callbackPtr->bundleName: %{public}s", + BUNDLE_ACTIVE_LOGI("QueryPackageGroup callbackPtr->bundleName: %{public}s", callbackPtr->bundleName.c_str()); BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); napi_value resourceName = nullptr; @@ -331,21 +331,22 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) } }, [](napi_env env, napi_status status, void *data) { - AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; - std::unique_ptr callbackPtr {asyncCallbackInfo}; + AsyncCallbackInfoPriorityGroup * asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; if (asyncCallbackInfo) { napi_value result = nullptr; napi_create_int32(env, asyncCallbackInfo->priorityGroup, &result); + BUNDLE_ACTIVE_LOGI("QueryPackageGroup, group is %{public}d",asyncCallbackInfo->priorityGroup); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); - callbackPtr.release(); if (callbackPtr->isCallback) { + callbackPtr.release(); return BundleStateCommon::NapiGetNull(env); } else { + callbackPtr.release(); return promise; } } @@ -842,6 +843,8 @@ napi_value SetBundleGroup(napi_env env, napi_callback_info info) std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->newGroup = params.newGroup; callbackPtr->bundleName = params.bundleName; + BUNDLE_ACTIVE_LOGI("SetBundleGroup, bundleName is %{public}s, newGroup is %{public}d", + callbackPtr->bundleName.c_str(), callbackPtr->newGroup); BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); napi_value resourceName = nullptr; NAPI_CALL(env, napi_create_string_latin1(env, "SetBundleGroup", NAPI_AUTO_LENGTH, &resourceName)); @@ -859,7 +862,6 @@ napi_value SetBundleGroup(napi_env env, napi_callback_info info) }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = (AsyncCallbackInfoSetBundleGroup *)data; - std::unique_ptr callbackPtr {asyncCallbackInfo}; if (asyncCallbackInfo) { napi_value result = nullptr; napi_get_boolean(env, asyncCallbackInfo->state, &result); @@ -869,10 +871,11 @@ napi_value SetBundleGroup(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); - callbackPtr.release(); if (callbackPtr->isCallback) { + callbackPtr.release(); return BundleStateCommon::NapiGetNull(env); } else { + callbackPtr.release(); return promise; } } diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h index c17f023..38bc5a7 100644 --- a/interfaces/innerkits/include/bundle_active_client.h +++ b/interfaces/innerkits/include/bundle_active_client.h @@ -79,7 +79,7 @@ public: * parameters: bundleName,userId * return: the priority group of calling bundle. */ - int32_t QueryPackageGroup(const std::string& bundleName, const int32_t userId = -1); + int32_t QueryPackageGroup(std::string& bundleName, const int32_t userId = -1); /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, diff --git a/interfaces/innerkits/include/bundle_active_proxy.h b/interfaces/innerkits/include/bundle_active_proxy.h index f5eede3..cbe56c5 100644 --- a/interfaces/innerkits/include/bundle_active_proxy.h +++ b/interfaces/innerkits/include/bundle_active_proxy.h @@ -75,7 +75,7 @@ public: * function: QueryPackageGroup, query bundle priority group calling bundle. * return: the priority group of calling bundle. */ - int32_t QueryPackageGroup(const std::string& bundleName, const int32_t userId) override; + int32_t QueryPackageGroup(std::string& bundleName, const int32_t userId) override; /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index cc7312c..e826996 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -111,12 +111,14 @@ std::vector BundleActiveClient::QueryCurrentEvents(const int6 return bundleActiveProxy_->QueryCurrentEvents(beginTime, endTime); } -int32_t BundleActiveClient::QueryPackageGroup(const std::string& bundleName, const int32_t userId) +int32_t BundleActiveClient::QueryPackageGroup(std::string& bundleName, const int32_t userId) { if (!GetBundleActiveProxy()) { return -1; } - return bundleActiveProxy_->QueryPackageGroup(bundleName, userId); + int32_t result = bundleActiveProxy_->QueryPackageGroup(bundleName, userId); + BUNDLE_ACTIVE_LOGI("QueryPackageGroup group is %{public}d ", result); + return result; } int32_t BundleActiveClient::QueryFormStatistics(int32_t maxNum, std::vector& results, diff --git a/interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp b/interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp index 5ba451b..768d809 100644 --- a/interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp @@ -12,8 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - #include #include "errors.h" #include "bundle_active_log.h" diff --git a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp index 5eadd17..87b7d9f 100644 --- a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp +++ b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace DeviceUsageStats { +static std::mutex callbackMutex_; int32_t BundleActiveGroupCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply, MessageOption &option) { @@ -26,11 +27,12 @@ int32_t BundleActiveGroupCallbackStub::OnRemoteRequest(uint32_t code, MessagePar BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack OnRemoteRequest cannot get power mgr service"); return -1; } - BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack BundleActiveGroupCallbackStub will switch"); + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack BundleActiveGroupCallbackStub will switch"); switch (code) { case static_cast(IBundleActiveGroupCallback::message::ON_BUNDLE_GROUP_CHANGED): { BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack OnRemoteRequest is nowing ON_BUNDLE_GROUP_CHANGED"); BundleActiveGroupCallbackInfo* groupInfo = nullptr; + std::unique_lock lock(callbackMutex_); groupInfo = data.ReadParcelable(); if (!groupInfo) { BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack ReadParcelable failed"); diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index b03c83b..ec934e6 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -197,7 +197,7 @@ std::vector BundleActiveProxy::QueryCurrentEvents(const int64 return result; } -int32_t BundleActiveProxy::QueryPackageGroup(const std::string& bundleName, const int32_t userId) +int32_t BundleActiveProxy::QueryPackageGroup(std::string& bundleName, const int32_t userId) { MessageParcel data; MessageParcel reply; @@ -209,8 +209,9 @@ int32_t BundleActiveProxy::QueryPackageGroup(const std::string& bundleName, cons data.WriteString(bundleName); data.WriteInt32(userId); Remote() -> SendRequest(QUERY_BUNDLE_GROUP, data, reply, option); - - return reply.ReadInt32(); + int32_t result = reply.ReadInt32(); + BUNDLE_ACTIVE_LOGI("the result of QueryPackgeGroup is %{public}d", result); + return result; } int32_t BundleActiveProxy::QueryFormStatistics(int32_t maxNum, std::vector& results, diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts index b40149a..e7f69dc 100644 --- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts +++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts @@ -391,6 +391,43 @@ declare namespace bundleState { function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback): void; function queryAppUsagePriorityGroup(bundleName? : string): Promise; + /** + * Declares group type. + * + * @since 9 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + */ + export enum GroupType { + /** + * Indicates the alive group. + */ + ACTIVE_GROUP_ALIVE = 10, + + /** + * Indicates the daily group. + */ + ACTIVE_GROUP_DAILY = 20, + + /** + * Indicates the fixed group. + */ + ACTIVE_GROUP_FIXED = 30, + + /** + * Indicates the rare group. + */ + ACTIVE_GROUP_RARE = 40, + + /** + * Indicates the limit group. + */ + ACTIVE_GROUP_LIMIT = 50, + /** + * Indicates the never group. + */ + ACTIVE_GROUP_NEVER = 60 + } + /** * set bundle group by bundleName and number. * @@ -398,8 +435,8 @@ declare namespace bundleState { * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App * @return Returns the result of setBundleGroup, true of false. */ - function setBundleGroup(bundleName: string, newGroup: number, callback: AsyncCallback): void; - function setBundleGroup(bundleName: string, newGroup: number): Promise; + function setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback): void; + function setBundleGroup(bundleName: string, newGroup: GroupType): Promise; /** * register callback to service. diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index 77aeb83..1b87a98 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -93,7 +93,7 @@ public: * function: QueryPackageGroup, query bundle priority group calling bundle. * return: the priority group of calling bundle. */ - int32_t QueryPackageGroup(const std::string& bundleName, int32_t userId) override; + int32_t QueryPackageGroup(std::string& bundleName, int32_t userId) override; /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, diff --git a/services/common/include/ibundle_active_service.h b/services/common/include/ibundle_active_service.h index a455be6..a9de2d5 100644 --- a/services/common/include/ibundle_active_service.h +++ b/services/common/include/ibundle_active_service.h @@ -93,7 +93,7 @@ public: * function: QueryPackageGroup, query bundle priority group calling bundle. * return: the priority group of calling bundle. */ - virtual int32_t QueryPackageGroup(const std::string& bundleName, int32_t userId) = 0; + virtual int32_t QueryPackageGroup(std::string& bundleName, int32_t userId) = 0; /* * function: SetBundleGroup, set specific bundle of specific user to a priority group. * parameters: bundleName, newGroup, userId diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 1df139e..6eadd99 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -709,7 +709,7 @@ void BundleActiveCore::OnBundleGroupChanged(const BundleActiveGroupCallbackInfo& for (const auto &item : groupChangeObservers_) { auto observer = item.second; if (observer) { - BUNDLE_ACTIVE_LOGD( + BUNDLE_ACTIVE_LOGI( "RegisterGroupCallBack will OnBundleGroupChanged!,oldGroup is %{public}d, newGroup is %{public}d", callbackInfo.GetOldGroup(), callbackInfo.GetNewGroup()); observer->OnBundleGroupChanged(callbackInfo); @@ -720,6 +720,7 @@ void BundleActiveCore::OnBundleGroupChanged(const BundleActiveGroupCallbackInfo& bool BundleActiveCore::RegisterGroupCallBack(const AccessToken::AccessTokenID& tokenId, const sptr &observer) { + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack enter BundleActiveCore, return"); std::lock_guard lock(callbackMutex_); if (!observer) { BUNDLE_ACTIVE_LOGI("observer is null, return"); @@ -732,7 +733,7 @@ bool BundleActiveCore::RegisterGroupCallBack(const AccessToken::AccessTokenID& t } groupChangeObservers_.emplace(tokenId, observer); AddObserverDeathRecipient(observer); - BUNDLE_ACTIVE_LOGD("RegisterGroupCallBack number is %{public}d", static_cast(groupChangeObservers_.size())); + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack number is %{public}d", static_cast(groupChangeObservers_.size())); return true; } diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 9c6dc3a..6113387 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -412,11 +412,11 @@ std::vector BundleActiveService::QueryCurrentEvents(const int return result; } -int32_t BundleActiveService::QueryPackageGroup(const std::string& bundleName, int32_t userId) +int32_t BundleActiveService::QueryPackageGroup(std::string& bundleName, int32_t userId) { // get uid int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("QueryPackageGroup UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("QueryPackageGroup UID is %{public}d", callingUid); int32_t errCode = 0; int32_t result = -1; if (userId == -1) { @@ -428,14 +428,21 @@ int32_t BundleActiveService::QueryPackageGroup(const std::string& bundleName, in } if (userId != -1) { if (bundleName.empty()) { - std::string bundleName = ""; - sptrBundleMgr_->GetBundleNameForUid(callingUid, bundleName); + if (!GetBundleMgrProxy()) { + BUNDLE_ACTIVE_LOGE("get bundle manager proxy failed!"); + return result; + } + std::string g_bundleName = ""; + sptrBundleMgr_->GetBundleNameForUid(callingUid, g_bundleName); + bundleName = g_bundleName; } if (!bundleName.empty()) { AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); if (CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId, errCode) || AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) == AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE) { + BUNDLE_ACTIVE_LOGD("QueryPackageGroup bundleName is %{public}s, userId is %{public}d", + bundleName.c_str(), userId); result = bundleActiveCore_->QueryPackageGroup(bundleName, userId); } } @@ -445,7 +452,7 @@ int32_t BundleActiveService::QueryPackageGroup(const std::string& bundleName, in bool BundleActiveService::RegisterGroupCallBack(const sptr &observer) { - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack enter bundleService"); + BUNDLE_ACTIVE_LOGD("RegisterGroupCallBack enter bundleService"); int result = false; if (!bundleActiveCore_) { return result; diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index 54dc3d1..7a0d0ed 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -281,6 +281,7 @@ void BundleActiveGroupController::CheckAndUpdateGroup(const std::string& bundleN uint32_t groupReason = oneBundleHistory->reasonInGroup_; uint32_t oldGroupControlReason = groupReason & GROUP_CONTROL_REASON_MASK; if (oldGroupControlReason == GROUP_CONTROL_REASON_FORCED) { + BUNDLE_ACTIVE_LOGI("%{public}s is forced set, return", bundleName.c_str()); return; } int32_t oldGroup = oneBundleHistory->currentGroup_; @@ -321,28 +322,9 @@ bool BundleActiveGroupController::SetBundleGroup(const std::string& bundleName, return false; } auto oneBundleHistory = bundleUserHistory_->GetUsageHistoryForBundle(bundleName, userId, bootBasedTimeStamp, true); - if (!oneBundleHistory || (oneBundleHistory->currentGroup_ < ACTIVE_GROUP_ALIVE)) { + if (!oneBundleHistory) { return false; } - if (reason != GROUP_CONTROL_REASON_FORCED) { - int64_t bootBasedTimeStampAdjusted = bundleUserHistory_->GetBootBasedTimeStamp(bootBasedTimeStamp); - if (newGroup > ACTIVE_GROUP_ALIVE && - oneBundleHistory->bundleAliveTimeoutTimeStamp_ > bootBasedTimeStampAdjusted) { - BUNDLE_ACTIVE_LOGI("%{public}s should be decreased, but time out in alive is not expire!" - "now is %{public}lld,timeout is %{public}lld", bundleName.c_str(), - (long long)bootBasedTimeStampAdjusted, (long long)oneBundleHistory->bundleAliveTimeoutTimeStamp_); - newGroup = ACTIVE_GROUP_ALIVE; - reason = oneBundleHistory->reasonInGroup_; - } else if (newGroup > ACTIVE_GROUP_DAILY && - oneBundleHistory->bundleDailyTimeoutTimeStamp_ > bootBasedTimeStampAdjusted) { - newGroup = ACTIVE_GROUP_DAILY; - if (oneBundleHistory->currentGroup_ != newGroup) { - reason = GROUP_CONTROL_REASON_USAGE | GROUP_CONTROL_REASON_TIMEOUT; - } else { - reason = oneBundleHistory->reasonInGroup_; - } - } - } return bundleUserHistory_->SetBundleGroup(bundleName, userId, bootBasedTimeStamp, newGroup, reason); } @@ -374,13 +356,13 @@ int32_t BundleActiveGroupController::QueryPackageGroup(const std::string& bundle BUNDLE_ACTIVE_LOGI("QueryPackageGroup is not bundleInstalled"); return -1; } - int64_t bootBasedTimeStamp = timer->GetBootTimeMs(); auto oneBundleHistory = bundleUserHistory_->GetUsageHistoryForBundle( bundleName, userId, bootBasedTimeStamp, false); if (!oneBundleHistory) { return -1; } + BUNDLE_ACTIVE_LOGI("QueryPackageGroup group is %{public}d, ",oneBundleHistory->currentGroup_); return oneBundleHistory->currentGroup_; } diff --git a/services/packagegroup/src/bundle_active_user_history.cpp b/services/packagegroup/src/bundle_active_user_history.cpp index 93fb2a1..c166eca 100644 --- a/services/packagegroup/src/bundle_active_user_history.cpp +++ b/services/packagegroup/src/bundle_active_user_history.cpp @@ -167,6 +167,9 @@ void BundleActiveUserHistory::ReportUsage(shared_ptr const string& bundleName, const int32_t newGroup, const uint32_t groupReason, const int64_t bootBasedTimeStamp, const int64_t timeUntilNextCheck, const int32_t userId) { + if ((oneBundleUsageHistory->reasonInGroup_ & GROUP_CONTROL_REASON_MASK) == GROUP_CONTROL_REASON_FORCED) { + return; + } if (timeUntilNextCheck > bootBasedTimeStamp) { int64_t nextCheckTimeStamp = bootBasedDuration_ + (timeUntilNextCheck - bootBasedTimeStamp_); if (newGroup == ACTIVE_GROUP_ALIVE) { @@ -223,6 +226,7 @@ bool BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int oneBundleHistory->currentGroup_ = newGroup; oneBundleHistory->reasonInGroup_ = groupReason; oneBundleHistory->isChanged_ = true; + BUNDLE_ACTIVE_LOGI("SetBundleGroup set success"); BundleActiveGroupCallbackInfo callbackInfo( userId, oldGroup, newGroup, oneBundleHistory->reasonInGroup_, bundleName); if (!bundleActiveCore_.expired()) { -- Gitee From 1d7a4c5b41de745ed11d14b6d91f88a3019a545d Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Mon, 30 May 2022 21:52:41 +0800 Subject: [PATCH 20/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E9=97=AE=E9=A2=98codecheck?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- frameworks/src/bundle_active_group_observer.cpp | 1 - frameworks/src/bundle_state_query.cpp | 3 +-- services/packagegroup/src/bundle_active_group_controller.cpp | 2 +- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index 2b48c1e..fc89965 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -377,7 +377,6 @@ napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) callbackPtr.release(); return promise; } - } } // 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 8dc58bb..7f449cb 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -331,11 +331,10 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) } }, [](napi_env env, napi_status status, void *data) { - AsyncCallbackInfoPriorityGroup * asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; + AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; if (asyncCallbackInfo) { napi_value result = nullptr; napi_create_int32(env, asyncCallbackInfo->priorityGroup, &result); - BUNDLE_ACTIVE_LOGI("QueryPackageGroup, group is %{public}d",asyncCallbackInfo->priorityGroup); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index 7a0d0ed..2f66c2b 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -362,7 +362,7 @@ int32_t BundleActiveGroupController::QueryPackageGroup(const std::string& bundle if (!oneBundleHistory) { return -1; } - BUNDLE_ACTIVE_LOGI("QueryPackageGroup group is %{public}d, ",oneBundleHistory->currentGroup_); + BUNDLE_ACTIVE_LOGI("QueryPackageGroup group is %{public}d ", oneBundleHistory->currentGroup_); return oneBundleHistory->currentGroup_; } -- Gitee From c9c2c799fd889225694c431264d2ce4b8d1fd5e3 Mon Sep 17 00:00:00 2001 From: houdisheng Date: Tue, 31 May 2022 13:42:58 +0800 Subject: [PATCH 21/83] =?UTF-8?q?=E5=B0=86event=E5=92=8C=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E4=BF=A1=E6=81=AF=E8=90=BD=E7=9B=98=E9=80=BB?= =?UTF-8?q?=E8=BE=91=E5=88=86=E7=A6=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- .../include/bundle_active_usage_database.h | 3 ++- .../src/bundle_active_usage_database.cpp | 21 ++++++++++++------- .../src/bundle_active_group_controller.cpp | 3 ++- .../include/bundle_active_event.h | 6 ++++++ .../packageusage/src/bundle_active_event.cpp | 13 ++++++++++++ .../src/bundle_active_period_stats.cpp | 2 +- .../src/bundle_active_user_service.cpp | 8 ++++--- 7 files changed, 43 insertions(+), 13 deletions(-) diff --git a/services/common/include/bundle_active_usage_database.h b/services/common/include/bundle_active_usage_database.h index 23cfe58..e544d6c 100644 --- a/services/common/include/bundle_active_usage_database.h +++ b/services/common/include/bundle_active_usage_database.h @@ -41,7 +41,8 @@ public: ~BundleActiveUsageDatabase(); void InitDatabaseTableInfo(int64_t currentTime); void InitUsageGroupDatabase(const int32_t databaseType, const bool forModuleRecords); - void UpdateUsageData(int32_t databaseType, BundleActivePeriodStats &stats); + void UpdateBundleUsageData(int32_t databaseType, BundleActivePeriodStats &stats); + void UpdateEventData(int32_t databaseType, BundleActivePeriodStats &stats); std::shared_ptr GetCurrentUsageData(int32_t databaseType, int32_t userId); void RenewTableTime(int64_t timeDiffMillis); int32_t GetOptimalIntervalType(int64_t beginTime, int64_t endTime); diff --git a/services/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp index aa8118f..a809cb9 100644 --- a/services/common/src/bundle_active_usage_database.cpp +++ b/services/common/src/bundle_active_usage_database.cpp @@ -1167,7 +1167,20 @@ void BundleActiveUsageDatabase::RenewTableTime(int64_t changedTime) } } -void BundleActiveUsageDatabase::UpdateUsageData(int32_t databaseType, BundleActivePeriodStats &stats) +void BundleActiveUsageDatabase::UpdateEventData(int32_t databaseType, BundleActivePeriodStats &stats) +{ + lock_guard lock(databaseMutex_); + CheckDatabaseFile(databaseType); + if (databaseType != DAILY_DATABASE_INDEX) { + return; + } + if (stats.events_.Size() != 0) { + CheckDatabaseFile(EVENT_DATABASE_INDEX); + FlushEventInfo(EVENT_DATABASE_INDEX, stats); + } +} + +void BundleActiveUsageDatabase::UpdateBundleUsageData(int32_t databaseType, BundleActivePeriodStats &stats) { lock_guard lock(databaseMutex_); if (databaseType < 0 || databaseType >= EVENT_DATABASE_INDEX) { @@ -1175,12 +1188,6 @@ void BundleActiveUsageDatabase::UpdateUsageData(int32_t databaseType, BundleActi return; } CheckDatabaseFile(databaseType); - if (databaseType == DAILY_DATABASE_INDEX) { - if (stats.events_.Size() != 0) { - CheckDatabaseFile(EVENT_DATABASE_INDEX); - FlushEventInfo(EVENT_DATABASE_INDEX, stats); - } - } int32_t packageTableIndex = BundleActiveBinarySearch::GetInstance()->BinarySearch( sortedTableArray_.at(databaseType), stats.beginTime_); if (packageTableIndex < 0) { diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index 54dc3d1..5d22086 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -224,6 +224,7 @@ void BundleActiveGroupController::ReportEvent(const BundleActiveEvent& event, co } std::lock_guard lock(mutex_); if (IsBundleInstalled(event.bundleName_, userId) == false) { + BUNDLE_ACTIVE_LOGE("Report an uninstalled package event, return!"); return; } int32_t eventId = event.eventId_; @@ -374,7 +375,7 @@ int32_t BundleActiveGroupController::QueryPackageGroup(const std::string& bundle BUNDLE_ACTIVE_LOGI("QueryPackageGroup is not bundleInstalled"); return -1; } - + int64_t bootBasedTimeStamp = timer->GetBootTimeMs(); auto oneBundleHistory = bundleUserHistory_->GetUsageHistoryForBundle( bundleName, userId, bootBasedTimeStamp, false); diff --git a/services/packageusage/include/bundle_active_event.h b/services/packageusage/include/bundle_active_event.h index 963ca49..e92dda6 100644 --- a/services/packageusage/include/bundle_active_event.h +++ b/services/packageusage/include/bundle_active_event.h @@ -120,6 +120,12 @@ public: * return: string of bundlename, timestamp, eventid. */ std::string ToString(); + /** + * @brief get if the event is reported by bundle usage. + * + * @return return true if event reported by bundle usage. + */ + static bool IsBundleEvent(const int32_t eventId); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/packageusage/src/bundle_active_event.cpp b/services/packageusage/src/bundle_active_event.cpp index c8451b7..e005984 100644 --- a/services/packageusage/src/bundle_active_event.cpp +++ b/services/packageusage/src/bundle_active_event.cpp @@ -183,6 +183,19 @@ std::string BundleActiveEvent::ToString() return "bundle name is " + this->bundleName_ + ", event is " + std::to_string(this->eventId_) + ", timestamp is " + std::to_string(this->timeStamp_) + "\n"; } + +bool BundleActiveEvent::IsBundleEvent(const int32_t eventId) +{ + if (eventId == ABILITY_BACKGROUND || + eventId == ABILITY_FOREGROUND || + eventId == ABILITY_STOP || + eventId == LONG_TIME_TASK_STARTTED || + eventId == LONG_TIME_TASK_ENDED || + eventId == END_OF_THE_DAY) { + return true; + } + return false; +} } // 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 d223d62..a6c4414 100644 --- a/services/packageusage/src/bundle_active_period_stats.cpp +++ b/services/packageusage/src/bundle_active_period_stats.cpp @@ -53,7 +53,7 @@ void BundleActivePeriodStats::Update(const std::string bundleName, const std::st tmpUsageStats->Update("", timeStamp, eventId, abilityId); } } - } else { + } else if (BundleActiveEvent::IsBundleEvent(eventId)){ auto usageStats = GetOrCreateUsageStats(bundleName); usageStats->Update(longTimeTaskName, timeStamp, eventId, abilityId); } diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index 9084d78..7f091db 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -173,10 +173,12 @@ void BundleActiveUserService::RestoreStats(bool forced) BUNDLE_ACTIVE_LOGI("RestoreStats() stat changed is true"); for (uint32_t i = 0; i < currentStats_.size(); i++) { if (currentStats_[i]) { - if (currentStats_[i]->bundleStats_.empty() && currentStats_[i]->events_.events_.empty()) { - continue; + if (!currentStats_[i]->bundleStats_.empty()) { + database_.UpdateBundleUsageData(i, *(currentStats_[i])); + } + if (!currentStats_[i]->events_.events_.empty() && i == BundleActivePeriodStats::PERIOD_DAILY) { + database_.UpdateEventData(i, *(currentStats_[i])); } - database_.UpdateUsageData(i, *(currentStats_[i])); } } if (!moduleRecords_.empty()) { -- Gitee From b8a21e20d618ca3693ee89b773f6cbcd174c1456 Mon Sep 17 00:00:00 2001 From: houdisheng Date: Tue, 31 May 2022 14:53:03 +0800 Subject: [PATCH 22/83] =?UTF-8?q?=E5=B0=86event=E5=92=8C=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E4=BF=A1=E6=81=AF=E8=90=BD=E7=9B=98=E9=80=BB?= =?UTF-8?q?=E8=BE=91=E5=88=86=E7=A6=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- services/packagegroup/src/bundle_active_group_controller.cpp | 2 -- services/packageusage/src/bundle_active_period_stats.cpp | 2 +- services/packageusage/src/bundle_active_user_service.cpp | 2 +- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index 5d22086..518bf1b 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -218,7 +218,6 @@ uint32_t BundleActiveGroupController::EventToGroupReason(const int32_t eventId) void BundleActiveGroupController::ReportEvent(const BundleActiveEvent& event, const int64_t bootBasedTimeStamp, const int32_t userId) { - BUNDLE_ACTIVE_LOGI("ReportEvent called"); if (bundleGroupEnable_ == false) { return; } @@ -375,7 +374,6 @@ int32_t BundleActiveGroupController::QueryPackageGroup(const std::string& bundle BUNDLE_ACTIVE_LOGI("QueryPackageGroup is not bundleInstalled"); return -1; } - int64_t bootBasedTimeStamp = timer->GetBootTimeMs(); auto oneBundleHistory = bundleUserHistory_->GetUsageHistoryForBundle( bundleName, userId, bootBasedTimeStamp, false); diff --git a/services/packageusage/src/bundle_active_period_stats.cpp b/services/packageusage/src/bundle_active_period_stats.cpp index a6c4414..c8b6994 100644 --- a/services/packageusage/src/bundle_active_period_stats.cpp +++ b/services/packageusage/src/bundle_active_period_stats.cpp @@ -53,7 +53,7 @@ void BundleActivePeriodStats::Update(const std::string bundleName, const std::st tmpUsageStats->Update("", timeStamp, eventId, abilityId); } } - } else if (BundleActiveEvent::IsBundleEvent(eventId)){ + } else if (BundleActiveEvent::IsBundleEvent(eventId)) { auto usageStats = GetOrCreateUsageStats(bundleName); usageStats->Update(longTimeTaskName, timeStamp, eventId, abilityId); } diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index 7f091db..8d88bf5 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -176,7 +176,7 @@ void BundleActiveUserService::RestoreStats(bool forced) if (!currentStats_[i]->bundleStats_.empty()) { database_.UpdateBundleUsageData(i, *(currentStats_[i])); } - if (!currentStats_[i]->events_.events_.empty() && i == BundleActivePeriodStats::PERIOD_DAILY) { + if (!currentStats_[i]->events_.events_.empty()) { database_.UpdateEventData(i, *(currentStats_[i])); } } -- Gitee From 3d1b637818ab06e0166402563746dcd985746a85 Mon Sep 17 00:00:00 2001 From: houdisheng Date: Tue, 31 May 2022 15:12:51 +0800 Subject: [PATCH 23/83] =?UTF-8?q?=E5=B0=86event=E5=92=8C=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E4=BF=A1=E6=81=AF=E8=90=BD=E7=9B=98=E9=80=BB?= =?UTF-8?q?=E8=BE=91=E5=88=86=E7=A6=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- services/packageusage/src/bundle_active_user_service.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index 8d88bf5..7f091db 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -176,7 +176,7 @@ void BundleActiveUserService::RestoreStats(bool forced) if (!currentStats_[i]->bundleStats_.empty()) { database_.UpdateBundleUsageData(i, *(currentStats_[i])); } - if (!currentStats_[i]->events_.events_.empty()) { + if (!currentStats_[i]->events_.events_.empty() && i == BundleActivePeriodStats::PERIOD_DAILY) { database_.UpdateEventData(i, *(currentStats_[i])); } } -- Gitee From acc3262ca2ec1b7345890059671616bedb7410b8 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 31 May 2022 20:41:08 +0800 Subject: [PATCH 24/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E4=BF=AE=E6=94=B92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../src/bundle_active_group_observer.cpp | 26 +++++----- frameworks/src/bundle_state_common.cpp | 15 +++++- frameworks/src/bundle_state_init.cpp | 49 +++++++++++++++++-- frameworks/src/bundle_state_query.cpp | 14 ++++-- .../innerkits/include/bundle_active_client.h | 2 +- .../innerkits/include/bundle_active_proxy.h | 6 +-- .../innerkits/src/bundle_active_client.cpp | 5 +- .../innerkits/src/bundle_active_proxy.cpp | 18 +++---- .../napi/include/bundle_state_condition.h | 9 ++++ .../napi/include/bundle_state_init.h | 3 +- .../napi/include/bundle_state_inner_errors.h | 3 ++ services/common/include/bundle_active_core.h | 6 +-- .../common/include/bundle_active_service.h | 6 +-- .../common/include/ibundle_active_service.h | 6 +-- services/common/src/bundle_active_core.cpp | 22 ++++----- services/common/src/bundle_active_service.cpp | 27 +++++----- .../include/bundle_active_group_controller.h | 2 +- .../include/bundle_active_user_history.h | 2 +- .../src/bundle_active_group_controller.cpp | 13 +++-- .../src/bundle_active_user_history.cpp | 23 +++++---- 20 files changed, 166 insertions(+), 91 deletions(-) diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index fc89965..a782165 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -142,12 +142,12 @@ void BundleActiveGroupObserver::OnBundleGroupChanged(const BundleActiveGroupCall return; } - uv_work_t *work = new (std::nothrow) uv_work_t; + uv_work_t* work = new (std::nothrow) uv_work_t; if (!work) { BUNDLE_ACTIVE_LOGE("work is null"); return; } - CallbackReceiveDataWorker *callbackReceiveDataWorker = new (std::nothrow) CallbackReceiveDataWorker(); + CallbackReceiveDataWorker* callbackReceiveDataWorker = new (std::nothrow) CallbackReceiveDataWorker(); if (!callbackReceiveDataWorker) { BUNDLE_ACTIVE_LOGE("callbackReceiveDataWorker is null"); delete work; @@ -179,7 +179,6 @@ void BundleActiveGroupObserver::OnBundleGroupChanged(const BundleActiveGroupCall delete work; work = nullptr; } - BUNDLE_ACTIVE_LOGI("OnBundleGroupChanged end"); } napi_value GetBundleGroupChangeCallback( @@ -249,7 +248,7 @@ napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - if (memset_s(asyncCallbackInfo, sizeof(AsyncRegisterCallbackInfo), 0, sizeof(AsyncRegisterCallbackInfo)) + if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) != EOK) { params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; delete asyncCallbackInfo; @@ -268,7 +267,7 @@ napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) [](napi_env env, void *data) { AsyncRegisterCallbackInfo *asyncCallbackInfo = (AsyncRegisterCallbackInfo *)data; if (asyncCallbackInfo) { - asyncCallbackInfo->state = + asyncCallbackInfo->errorCode = BundleActiveClient::GetInstance().RegisterGroupCallBack(asyncCallbackInfo->observer); } else { BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack, asyncCallbackInfo == nullptr"); @@ -278,6 +277,7 @@ napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) AsyncRegisterCallbackInfo *asyncCallbackInfo = (AsyncRegisterCallbackInfo *)data; if (asyncCallbackInfo) { napi_value result = nullptr; + asyncCallbackInfo->state = (asyncCallbackInfo->errorCode == ERR_OK) ? true : false; napi_get_boolean(env, asyncCallbackInfo->state, &result); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } @@ -317,16 +317,17 @@ napi_value ParseUnRegisterGroupCallBackParameters(const napi_env &env, const nap napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) { BUNDLE_ACTIVE_LOGI("enter UnRegisterGroupCallBack"); - if (!registerObserver) { - return BundleStateCommon::NapiGetNull(env); - } UnRegisterCallbackInfo params; ParseUnRegisterGroupCallBackParameters(env, info, params); if (params.errorCode != ERR_OK) { return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - + if (!registerObserver) { + BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack observer is not"); + params.errorCode = ERR_REGISTER_OBSERVER_IS_NULL; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } napi_value promise = nullptr; AsyncUnRegisterCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncUnRegisterCallbackInfo(env); @@ -334,7 +335,7 @@ napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - if (memset_s(asyncCallbackInfo, sizeof(AsyncUnRegisterCallbackInfo), 0, sizeof(AsyncUnRegisterCallbackInfo)) + if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) != EOK) { params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; delete asyncCallbackInfo; @@ -353,7 +354,7 @@ napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) [](napi_env env, void *data) { AsyncUnRegisterCallbackInfo *asyncCallbackInfo = (AsyncUnRegisterCallbackInfo *)data; if (asyncCallbackInfo != nullptr) { - asyncCallbackInfo->state = + asyncCallbackInfo->errorCode = BundleActiveClient::GetInstance().UnregisterGroupCallBack(asyncCallbackInfo->observer); } else { BUNDLE_ACTIVE_LOGE("UnRegisterGroupCallBack, asyncCallbackInfo == nullptr"); @@ -363,6 +364,7 @@ napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) AsyncUnRegisterCallbackInfo *asyncCallbackInfo = (AsyncUnRegisterCallbackInfo *)data; if (asyncCallbackInfo != nullptr) { napi_value result = nullptr; + asyncCallbackInfo->state = (asyncCallbackInfo->errorCode == ERR_OK) ? true : false; napi_get_boolean(env, asyncCallbackInfo->state, &result); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } @@ -370,6 +372,7 @@ napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); + registerObserver = nullptr; if (callbackPtr->isCallback) { callbackPtr.release(); return BundleStateCommon::NapiGetNull(env); @@ -377,6 +380,7 @@ napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) callbackPtr.release(); return promise; } + } } // namespace DeviceUsageStats } // namespace OHOS \ No newline at end of file diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp index c5efe40..8eb41d7 100644 --- a/frameworks/src/bundle_state_common.cpp +++ b/frameworks/src/bundle_state_common.cpp @@ -50,6 +50,7 @@ napi_value BundleStateCommon::NapiGetNull(napi_env env) void BundleStateCommon::GetCallbackPromiseResult(const napi_env &env, const AsyncWorkData &workData, const napi_value &result) { + if (workData.isCallback) { SetCallbackInfo(env, workData.callback, workData.errorCode, result); } else { @@ -67,7 +68,13 @@ void BundleStateCommon::SetCallbackInfo( napi_value resultout = nullptr; napi_get_reference_value(env, callbackIn, &callback); napi_value results[ARGS_TWO] = {nullptr}; - results[PARAM_FIRST] = GetErrorValue(env, errorCode); + if (errorCode == -1) { + results[PARAM_FIRST] = GetErrorValue(env, ERR_SERVICE_FAILED); + } else if (errorCode == 0) { + results[PARAM_FIRST] = GetErrorValue(env, errorCode); + } else if (errorCode == 1) { + results[PARAM_FIRST] = GetErrorValue(env, ERR_REPEAT_OPERATION); + } results[PARAM_SECOND] = result; NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &results[PARAM_FIRST], &resultout)); @@ -303,7 +310,11 @@ void BundleStateCommon::SetPromiseInfo(const napi_env &env, const napi_deferred if (errorCode == ERR_OK) { napi_resolve_deferred(env, deferred, result); } else { - napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode)); + if (errorCode == -1) { + napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_SERVICE_FAILED)); + } else if (errorCode == 1) { + napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_REPEAT_OPERATION)); + } } } diff --git a/frameworks/src/bundle_state_init.cpp b/frameworks/src/bundle_state_init.cpp index 91a53b1..99dddd2 100644 --- a/frameworks/src/bundle_state_init.cpp +++ b/frameworks/src/bundle_state_init.cpp @@ -24,7 +24,7 @@ EXTERN_C_START static const uint8_t ARG_FIRST = 1; -napi_ref intervalTypeConstructor_ = nullptr; +napi_ref typeConstructor_ = nullptr; /* * Module export function @@ -52,6 +52,7 @@ static napi_value BundleStateInit(napi_env env, napi_value exports) NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); InitIntervalType(env, exports); + InitGroupType(env, exports); return exports; } @@ -84,14 +85,54 @@ napi_value InitIntervalType(napi_env env, napi_value exports) }; napi_value result = nullptr; - napi_define_class(env, "IntervalType", NAPI_AUTO_LENGTH, EnumIntervalTypeConstructor, + napi_define_class(env, "IntervalType", NAPI_AUTO_LENGTH, EnumTypeConstructor, nullptr, sizeof(desc) / sizeof(*desc), desc, &result); - napi_create_reference(env, result, refCount, &intervalTypeConstructor_); + napi_create_reference(env, result, refCount, &typeConstructor_); napi_set_named_property(env, exports, "IntervalType", result); return exports; } -napi_value EnumIntervalTypeConstructor(napi_env env, napi_callback_info info) +napi_value InitGroupType(napi_env env, napi_value exports) +{ + napi_value active_group_alive; + napi_value active_group_daily; + napi_value active_group_fixed; + napi_value active_group_rare; + napi_value active_group_limit; + napi_value active_group_never; + int32_t refCount = 1; + + napi_create_uint32(env, static_cast(BundleStateCondition::GroupType::ACTIVE_GROUP_ALIVE), + &active_group_alive); + napi_create_uint32(env, static_cast(BundleStateCondition::GroupType::ACTIVE_GROUP_DAILY), + &active_group_daily); + napi_create_uint32(env, static_cast(BundleStateCondition::GroupType::ACTIVE_GROUP_FIXED), + &active_group_fixed); + napi_create_uint32(env, static_cast(BundleStateCondition::GroupType::ACTIVE_GROUP_RARE), + &active_group_rare); + napi_create_uint32(env, static_cast(BundleStateCondition::GroupType::ACTIVE_GROUP_LIMIT), + &active_group_limit); + napi_create_uint32(env, static_cast(BundleStateCondition::GroupType::ACTIVE_GROUP_NEVER), + &active_group_never); + + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("ACTIVE_GROUP_ALIVE", active_group_alive), + DECLARE_NAPI_STATIC_PROPERTY("ACTIVE_GROUP_DAILY", active_group_daily), + DECLARE_NAPI_STATIC_PROPERTY("ACTIVE_GROUP_FIXED", active_group_fixed), + DECLARE_NAPI_STATIC_PROPERTY("ACTIVE_GROUP_RARE", active_group_rare), + DECLARE_NAPI_STATIC_PROPERTY("ACTIVE_GROUP_LIMIT", active_group_limit), + DECLARE_NAPI_STATIC_PROPERTY("ACTIVE_GROUP_NEVER", active_group_never), + }; + + napi_value result = nullptr; + napi_define_class(env, "GroupType", NAPI_AUTO_LENGTH, EnumTypeConstructor, + nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_create_reference(env, result, refCount, &typeConstructor_); + napi_set_named_property(env, exports, "GroupType", result); + return exports; +} + +napi_value EnumTypeConstructor(napi_env env, napi_callback_info info) { size_t argc = 0; napi_value args[ARG_FIRST] = {0}; diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index 7f449cb..ece5ad4 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -331,10 +331,14 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) } }, [](napi_env env, napi_status status, void *data) { - AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; + AsyncCallbackInfoPriorityGroup * asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; if (asyncCallbackInfo) { + if(asyncCallbackInfo->priorityGroup == -1) { + asyncCallbackInfo->priorityGroup = ERR_SERVICE_FAILED; + } napi_value result = nullptr; napi_create_int32(env, asyncCallbackInfo->priorityGroup, &result); + BUNDLE_ACTIVE_LOGD("QueryPackageGroup, group is %{public}d", asyncCallbackInfo->priorityGroup); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, @@ -754,10 +758,11 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); - callbackPtr.release(); if (callbackPtr->isCallback) { + callbackPtr.release(); return BundleStateCommon::NapiGetNull(env); } else { + callbackPtr.release(); return promise; } } @@ -832,7 +837,7 @@ napi_value SetBundleGroup(napi_env env, napi_callback_info info) params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - if (memset_s(asyncCallbackInfo, sizeof(AsyncCallbackInfoSetBundleGroup), 0, sizeof(AsyncCallbackInfoSetBundleGroup)) + if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) != EOK) { params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; delete asyncCallbackInfo; @@ -853,7 +858,7 @@ napi_value SetBundleGroup(napi_env env, napi_callback_info info) [](napi_env env, void *data) { AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = (AsyncCallbackInfoSetBundleGroup *)data; if (asyncCallbackInfo) { - asyncCallbackInfo->state = BundleActiveClient::GetInstance().SetBundleGroup( + asyncCallbackInfo->errorCode = BundleActiveClient::GetInstance().SetBundleGroup( asyncCallbackInfo->bundleName, asyncCallbackInfo->newGroup, asyncCallbackInfo->errorCode); } else { BUNDLE_ACTIVE_LOGE("SetBundleGroup, asyncCallbackInfo == nullptr"); @@ -863,6 +868,7 @@ napi_value SetBundleGroup(napi_env env, napi_callback_info info) AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = (AsyncCallbackInfoSetBundleGroup *)data; if (asyncCallbackInfo) { napi_value result = nullptr; + asyncCallbackInfo->state = (asyncCallbackInfo->errorCode == ERR_OK) ? true : false; napi_get_boolean(env, asyncCallbackInfo->state, &result); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h index 38bc5a7..c7668f2 100644 --- a/interfaces/innerkits/include/bundle_active_client.h +++ b/interfaces/innerkits/include/bundle_active_client.h @@ -60,7 +60,7 @@ public: * parameters: bundleName, newGroup, userId * return : void */ - bool SetBundleGroup(std::string bundleName, const int32_t newGroup, int32_t errCode, int32_t userId = -1); + int32_t SetBundleGroup(std::string bundleName, const int32_t newGroup, int32_t errCode, int32_t userId = -1); /* * function: QueryCurrentPackageStats, query bundle usage statistics in specific time span for calling bundle. * parameters: intervalType, beginTime, endTime diff --git a/interfaces/innerkits/include/bundle_active_proxy.h b/interfaces/innerkits/include/bundle_active_proxy.h index cbe56c5..a0b90b3 100644 --- a/interfaces/innerkits/include/bundle_active_proxy.h +++ b/interfaces/innerkits/include/bundle_active_proxy.h @@ -57,7 +57,7 @@ public: * function: SetBundleGroup, set specific bundle of specific user to a priority group. * parameters: bundleName, newGroup, userId */ - bool SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) override; + int32_t SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) override; /* * function: QueryCurrentPackageStats, query bundle usage statistics in specific time span for calling bundle. * parameters: intervalType, beginTime, endTime @@ -111,13 +111,13 @@ public: * parameters: observer * return: result of RegisterGroupCallBack, true or false. */ - bool RegisterGroupCallBack(const sptr &observer) override; + int32_t RegisterGroupCallBack(const sptr &observer) override; /* * function: UnregisterGroupCallBack, remove the observer from groupObservers. * parameters: observer * return: result of UnregisterGroupCallBack, true or false. */ - bool UnregisterGroupCallBack(const sptr &observer) override; + int32_t UnregisterGroupCallBack(const sptr &observer) override; /* * function: ~BundleActiveProxy, default destructor. */ diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index e826996..efaf269 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -85,11 +85,11 @@ std::vector BundleActiveClient::QueryEvents(const int64_t beg return bundleActiveProxy_->QueryEvents(beginTime, endTime, errCode, userId); } -bool BundleActiveClient::SetBundleGroup(std::string bundleName, const int32_t newGroup, +int32_t BundleActiveClient::SetBundleGroup(std::string bundleName, const int32_t newGroup, int32_t errCode, int32_t userId) { if (!GetBundleActiveProxy()) { - return false; + return -1; } return bundleActiveProxy_->SetBundleGroup(bundleName, newGroup, errCode, userId); } @@ -117,7 +117,6 @@ int32_t BundleActiveClient::QueryPackageGroup(std::string& bundleName, const int return -1; } int32_t result = bundleActiveProxy_->QueryPackageGroup(bundleName, userId); - BUNDLE_ACTIVE_LOGI("QueryPackageGroup group is %{public}d ", result); return result; } diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index ec934e6..b77b642 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -116,14 +116,14 @@ std::vector BundleActiveProxy::QueryEvents(const int64_t begi return result; } -bool BundleActiveProxy::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) +int32_t BundleActiveProxy::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) { BUNDLE_ACTIVE_LOGI("SetBundleGroup enter bundleActiveProxy"); MessageParcel data; MessageParcel reply; MessageOption option; if (!data.WriteInterfaceToken(GetDescriptor())) { - return false; + return -1; } data.WriteString(bundleName); data.WriteInt32(newGroup); @@ -210,7 +210,6 @@ int32_t BundleActiveProxy::QueryPackageGroup(std::string& bundleName, const int3 data.WriteInt32(userId); Remote() -> SendRequest(QUERY_BUNDLE_GROUP, data, reply, option); int32_t result = reply.ReadInt32(); - BUNDLE_ACTIVE_LOGI("the result of QueryPackgeGroup is %{public}d", result); return result; } @@ -250,9 +249,9 @@ int32_t BundleActiveProxy::QueryFormStatistics(int32_t maxNum, std::vector &observer) +int32_t BundleActiveProxy::RegisterGroupCallBack(const sptr &observer) { - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack enter proxy---------------------"); + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack enter proxy"); if (!observer) { BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack observer null"); return false; @@ -268,21 +267,20 @@ bool BundleActiveProxy::RegisterGroupCallBack(const sptrSendRequest(REGISTER_GROUP_CALLBACK, data, reply, option); if (ret!= ERR_OK) { BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack SendRequest failed, error code: %{public}d", ret); } - return true; + return reply.ReadInt32(); } -bool BundleActiveProxy::UnregisterGroupCallBack(const sptr &observer) +int32_t BundleActiveProxy::UnregisterGroupCallBack(const sptr &observer) { if (!observer) { BUNDLE_ACTIVE_LOGE("observer null"); return false; } - BUNDLE_ACTIVE_LOGI("unRegisterApplicationStateObserver start"); + BUNDLE_ACTIVE_LOGI("UnregisterGroupCallBack start"); MessageParcel data; MessageParcel reply; MessageOption option; @@ -294,7 +292,7 @@ bool BundleActiveProxy::UnregisterGroupCallBack(const sptrSendRequest(UNREGISTER_GROUP_CALLBACK, data, reply, option); - return true; + return reply.ReadInt32(); } int32_t BundleActiveProxy::QueryEventStats(int64_t beginTime, int64_t endTime, diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_condition.h b/interfaces/kits/bundlestats/napi/include/bundle_state_condition.h index eb4dc7a..d051d6a 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_condition.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_condition.h @@ -30,6 +30,15 @@ public: BY_MONTHLY, BY_ANNUALLY, }; + + enum GroupType { + ACTIVE_GROUP_ALIVE = 10, + ACTIVE_GROUP_DAILY = 20, + ACTIVE_GROUP_FIXED = 30, + ACTIVE_GROUP_RARE = 40, + ACTIVE_GROUP_LIMIT = 50, + ACTIVE_GROUP_NEVER = 60, + }; }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_init.h b/interfaces/kits/bundlestats/napi/include/bundle_state_init.h index 7ac5260..8e65667 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_init.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_init.h @@ -28,7 +28,8 @@ extern "C" { __attribute__((constructor)) void RegisterModule(void); static napi_value BundleStateInit(napi_env env, napi_value exports); static napi_value InitIntervalType(napi_env env, napi_value exports); -static napi_value EnumIntervalTypeConstructor(napi_env env, napi_callback_info info); +static napi_value InitGroupType(napi_env env, napi_value exports); +static napi_value EnumTypeConstructor(napi_env env, napi_callback_info info); #ifdef __cplusplus } diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h index 3c48aec..fc4c9f6 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h @@ -53,6 +53,9 @@ enum : int32_t { ERR_MODULE_STATS_MAXNUM_INVALID, ERR_EVENT_TYPE, ERR_EVENT_TYPE_NUMBER, + ERR_SERVICE_FAILED, + ERR_REPEAT_OPERATION, + ERR_REGISTER_OBSERVER_IS_NULL, }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 50e4662..4f61f05 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -165,7 +165,7 @@ public: // when user switched, restore old userdata. void OnUserSwitched(const int32_t userId); // force set app group. - bool SetBundleGroup(const std::string& bundleName, const int32_t newGroup, const int32_t userId); + int32_t SetBundleGroup(const std::string& bundleName, const int32_t newGroup, const int32_t userId); // get all user in device. void GetAllActiveUser(std::vector& activatedOsAccountIds); // when service stop, call it to unregister commen event and shutdown call back. @@ -177,14 +177,14 @@ public: * parameters: observer * return: result of RegisterGroupCallBack, true or false. */ - bool RegisterGroupCallBack(const AccessToken::AccessTokenID& tokenId, + int32_t RegisterGroupCallBack(const AccessToken::AccessTokenID& tokenId, const sptr &observer); /* * function: UnregisterGroupCallBack, remove the observer from groupObservers. * parameters: observer * return: result of UnregisterGroupCallBack, true or false. */ - bool UnregisterGroupCallBack(const AccessToken::AccessTokenID& tokenId, + int32_t UnregisterGroupCallBack(const AccessToken::AccessTokenID& tokenId, const sptr &observer); int32_t currentUsedUser_; void OnBundleGroupChanged(const BundleActiveGroupCallbackInfo& callbackInfo); diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index 1b87a98..954a28b 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -75,7 +75,7 @@ public: * function: SetBundleGroup, set specific bundle of specific user to a priority group. * parameters: bundleName, newGroup, userId */ - bool SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) override; + int32_t SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) override; /* * function: QueryCurrentPackageStats, query bundle usage statistics in specific time span for calling bundle. * parameters: intervalType, beginTime, endTime @@ -128,13 +128,13 @@ public: * parameters: observer * return: result of RegisterGroupCallBack, true or false. */ - bool RegisterGroupCallBack(const sptr &observer) override; + int32_t RegisterGroupCallBack(const sptr &observer) override; /* * function: UnregisterGroupCallBack, remove the observer from groupObservers. * parameters: observer * return: result of UnregisterGroupCallBack, true or false. */ - bool UnregisterGroupCallBack(const sptr &observer) override; + int32_t UnregisterGroupCallBack(const sptr &observer) override; protected: /** diff --git a/services/common/include/ibundle_active_service.h b/services/common/include/ibundle_active_service.h index a9de2d5..9e2ddaf 100644 --- a/services/common/include/ibundle_active_service.h +++ b/services/common/include/ibundle_active_service.h @@ -98,7 +98,7 @@ public: * function: SetBundleGroup, set specific bundle of specific user to a priority group. * parameters: bundleName, newGroup, userId */ - virtual bool SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) = 0; + virtual int32_t SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) = 0; /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, @@ -108,8 +108,8 @@ public: virtual int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId) = 0; - virtual bool RegisterGroupCallBack(const sptr &observer) = 0; - virtual bool UnregisterGroupCallBack(const sptr &observer) = 0; + virtual int32_t RegisterGroupCallBack(const sptr &observer) = 0; + virtual int32_t UnregisterGroupCallBack(const sptr &observer) = 0; /* * function: QueryEventStats, query all from event stats in specific time span for calling user. diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 6eadd99..2bf517b 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -649,7 +649,7 @@ int32_t BundleActiveCore::QueryAppNotificationNumber(int64_t beginTime, int64_t return errCode; } -bool BundleActiveCore::SetBundleGroup(const std::string& bundleName, const int32_t newGroup, const int32_t userId) +int32_t BundleActiveCore::SetBundleGroup(const std::string& bundleName, const int32_t newGroup, const int32_t userId) { int32_t newReason = GROUP_CONTROL_REASON_FORCED; sptr timer = MiscServices::TimeServiceClient::GetInstance(); @@ -717,38 +717,36 @@ void BundleActiveCore::OnBundleGroupChanged(const BundleActiveGroupCallbackInfo& } } -bool BundleActiveCore::RegisterGroupCallBack(const AccessToken::AccessTokenID& tokenId, +int32_t BundleActiveCore::RegisterGroupCallBack(const AccessToken::AccessTokenID& tokenId, const sptr &observer) { BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack enter BundleActiveCore, return"); std::lock_guard lock(callbackMutex_); if (!observer) { - BUNDLE_ACTIVE_LOGI("observer is null, return"); - return false; + return -1; } auto item = groupChangeObservers_.find(tokenId); if (item != groupChangeObservers_.end()) { - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack observer exist, return"); - return false; + return 1; } groupChangeObservers_.emplace(tokenId, observer); AddObserverDeathRecipient(observer); - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack number is %{public}d", static_cast(groupChangeObservers_.size())); - return true; + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack number is %{public}d", groupChangeObservers_.size()); + return 0; } -bool BundleActiveCore::UnregisterGroupCallBack(const AccessToken::AccessTokenID& tokenId, +int32_t BundleActiveCore::UnregisterGroupCallBack(const AccessToken::AccessTokenID& tokenId, const sptr &observer) { std::lock_guard lock(callbackMutex_); auto item = groupChangeObservers_.find(tokenId); if (item == groupChangeObservers_.end()) { BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack observer is not exist, return"); - return false; + return 1; } - groupChangeObservers_.erase(tokenId); RemoveObserverDeathRecipient(item->second); - return true; + groupChangeObservers_.erase(tokenId); + return 0; } void BundleActiveCore::AddObserverDeathRecipient(const sptr &observer) diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 6113387..736aaa2 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -327,10 +327,10 @@ std::vector BundleActiveService::QueryEvents(const int64_t be return result; } -bool BundleActiveService::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, +int32_t BundleActiveService::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) { - bool result = false; + bool result = -1; // get uid int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); @@ -435,25 +435,23 @@ int32_t BundleActiveService::QueryPackageGroup(std::string& bundleName, int32_t std::string g_bundleName = ""; sptrBundleMgr_->GetBundleNameForUid(callingUid, g_bundleName); bundleName = g_bundleName; - } - if (!bundleName.empty()) { + result = bundleActiveCore_->QueryPackageGroup(bundleName, userId); + } else { AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); if (CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId, errCode) || AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) == AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE) { - BUNDLE_ACTIVE_LOGD("QueryPackageGroup bundleName is %{public}s, userId is %{public}d", - bundleName.c_str(), userId); - result = bundleActiveCore_->QueryPackageGroup(bundleName, userId); + result = bundleActiveCore_->QueryPackageGroup(bundleName, userId); } - } + } } return result; } -bool BundleActiveService::RegisterGroupCallBack(const sptr &observer) +int32_t BundleActiveService::RegisterGroupCallBack(const sptr &observer) { BUNDLE_ACTIVE_LOGD("RegisterGroupCallBack enter bundleService"); - int result = false; + int result = -1; if (!bundleActiveCore_) { return result; } @@ -467,9 +465,9 @@ bool BundleActiveService::RegisterGroupCallBack(const sptr &observer) +int32_t BundleActiveService::UnregisterGroupCallBack(const sptr &observer) { - int32_t result = false; + int32_t result = -1; if (!bundleActiveCore_) { return result; } @@ -477,6 +475,7 @@ bool BundleActiveService::UnregisterGroupCallBack(const sptrUnregisterGroupCallBack(tokenId, observer); @@ -531,10 +530,10 @@ bool BundleActiveService::CheckBundleIsSystemAppAndHasPermission(const int32_t u int32_t bundleHasPermission = AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, NEEDED_PERMISSION); if (bundleHasPermission != 0) { errCode = bundleHasPermission; - BUNDLE_ACTIVE_LOGE("%{public}s hasn't permission", bundleName.c_str()); + BUNDLE_ACTIVE_LOGE("UnRegisterGroupCallBack %{public}s hasn't permission", bundleName.c_str()); return false; } else { - BUNDLE_ACTIVE_LOGI(" %{public}s has permission %{public}d", + BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack %{public}s has permission %{public}d", bundleName.c_str(), bundleHasPermission); return true; } diff --git a/services/packagegroup/include/bundle_active_group_controller.h b/services/packagegroup/include/bundle_active_group_controller.h index 0fe896e..6cfa429 100644 --- a/services/packagegroup/include/bundle_active_group_controller.h +++ b/services/packagegroup/include/bundle_active_group_controller.h @@ -63,7 +63,7 @@ public: void OnUserRemoved(const int32_t userId); void OnBundleUninstalled(const int32_t userId, const std::string bundleName); void OnScreenChanged(const bool& isScreenOn, const int64_t bootFromTimeStamp); - bool SetBundleGroup(const std::string& bundleName, const int32_t userId, int32_t newGroup, uint32_t reason, + int32_t SetBundleGroup(const std::string& bundleName, const int32_t userId, int32_t newGroup, uint32_t reason, const int64_t bootBasedTimeStamp); void RestoreToDatabase(const int32_t userId); void RestoreDurationToDatabase(); diff --git a/services/packagegroup/include/bundle_active_user_history.h b/services/packagegroup/include/bundle_active_user_history.h index c7e3e5d..b661701 100644 --- a/services/packagegroup/include/bundle_active_user_history.h +++ b/services/packagegroup/include/bundle_active_user_history.h @@ -51,7 +51,7 @@ public: void ReportUsage(std::shared_ptr oneBundleUsageHistory, const std::string& bundleName, const int32_t newGroup, const uint32_t groupReason, const int64_t bootBasedTimeStamp, const int64_t timeUntilNextCheck, const int32_t userId); - bool SetBundleGroup(const std::string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, + int32_t SetBundleGroup(const std::string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, int32_t newGroup, uint32_t groupReason); int32_t GetLevelIndex(const std::string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, const std::vector screenTimeLeve, const std::vector bootFromTimeLevel); diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index 2f66c2b..36d9e33 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -314,16 +314,16 @@ void BundleActiveGroupController::CheckAndUpdateGroup(const std::string& bundleN } } -bool BundleActiveGroupController::SetBundleGroup(const std::string& bundleName, const int32_t userId, +int32_t BundleActiveGroupController::SetBundleGroup(const std::string& bundleName, const int32_t userId, int32_t newGroup, uint32_t reason, const int64_t bootBasedTimeStamp) { std::lock_guard lock(mutex_); if (!IsBundleInstalled(bundleName, userId)) { - return false; + return -1; } auto oneBundleHistory = bundleUserHistory_->GetUsageHistoryForBundle(bundleName, userId, bootBasedTimeStamp, true); if (!oneBundleHistory) { - return false; + return -1; } return bundleUserHistory_->SetBundleGroup(bundleName, userId, bootBasedTimeStamp, newGroup, reason); } @@ -350,7 +350,10 @@ int32_t BundleActiveGroupController::IsBundleIdle(const std::string& bundleName, int32_t BundleActiveGroupController::QueryPackageGroup(const std::string& bundleName, const int32_t userId) { - BUNDLE_ACTIVE_LOGI("QueryPackageGroup called"); + if (bundleName.empty()) { + BUNDLE_ACTIVE_LOGE("bundleName can not get by userId"); + return -1; + } sptr timer = MiscServices::TimeServiceClient::GetInstance(); if (!IsBundleInstalled(bundleName, userId)) { BUNDLE_ACTIVE_LOGI("QueryPackageGroup is not bundleInstalled"); @@ -362,7 +365,7 @@ int32_t BundleActiveGroupController::QueryPackageGroup(const std::string& bundle if (!oneBundleHistory) { return -1; } - BUNDLE_ACTIVE_LOGI("QueryPackageGroup group is %{public}d ", oneBundleHistory->currentGroup_); + BUNDLE_ACTIVE_LOGI("QueryPackageGroup group is %{public}d, ",oneBundleHistory->currentGroup_); return oneBundleHistory->currentGroup_; } diff --git a/services/packagegroup/src/bundle_active_user_history.cpp b/services/packagegroup/src/bundle_active_user_history.cpp index c166eca..711a3a2 100644 --- a/services/packagegroup/src/bundle_active_user_history.cpp +++ b/services/packagegroup/src/bundle_active_user_history.cpp @@ -194,16 +194,19 @@ void BundleActiveUserHistory::ReportUsage(shared_ptr oneBundleUsageHistory->reasonInGroup_ = GROUP_CONTROL_REASON_USAGE | groupReason; oneBundleUsageHistory->isChanged_ = true; BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack will ReportUsage"); - BundleActiveGroupCallbackInfo callbackInfo( + bool isGroupChanged = (oldGroup == newGroup) ? true : false; + if (isGroupChanged) { + BundleActiveGroupCallbackInfo callbackInfo( userId, oldGroup, newGroup, oneBundleUsageHistory->reasonInGroup_, bundleName); - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack BundleActiveGroupCallbackInfo build success"); - if (!bundleActiveCore_.expired()) { - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack will callback!"); - bundleActiveCore_.lock()->OnBundleGroupChanged(callbackInfo); + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack BundleActiveGroupCallbackInfo build success"); + if (!bundleActiveCore_.expired()) { + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack will callback!"); + bundleActiveCore_.lock()->OnBundleGroupChanged(callbackInfo); + } } } -bool BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int32_t userId, +int32_t BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, int32_t newGroup, uint32_t groupReason) { std::lock_guard lock(setGroupMutex_); @@ -211,16 +214,16 @@ bool BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int bundleName.c_str(), newGroup, groupReason, userId); shared_ptr>> userBundleHistory = GetUserHistory(userId, false); if (!userBundleHistory) { - return false; + return -1; } shared_ptr oneBundleHistory = GetUsageHistoryInUserHistory(userBundleHistory, bundleName, bootBasedTimeStamp, false); if (!oneBundleHistory) { - return false; + return -1; } 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 false; + return 1; } int32_t oldGroup = oneBundleHistory->currentGroup_; oneBundleHistory->currentGroup_ = newGroup; @@ -232,7 +235,7 @@ bool BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int if (!bundleActiveCore_.expired()) { bundleActiveCore_.lock()->OnBundleGroupChanged(callbackInfo); } - return true; + return 0; } void BundleActiveUserHistory::UpdateBootBasedAndScreenTime(const bool& isScreenOn, const int64_t bootBasedTimeStamp, -- Gitee From 5ef452143b0abeeac667e01ceafb93f82d78cd2b Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 31 May 2022 20:55:19 +0800 Subject: [PATCH 25/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E4=BF=AE=E6=94=B92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- frameworks/src/bundle_active_group_observer.cpp | 1 - frameworks/src/bundle_state_common.cpp | 3 +-- frameworks/src/bundle_state_query.cpp | 4 ++-- interfaces/innerkits/src/bundle_active_proxy.cpp | 3 ++- services/common/include/ibundle_active_service.h | 3 ++- services/common/src/bundle_active_service.cpp | 3 +-- services/packagegroup/src/bundle_active_group_controller.cpp | 2 +- 7 files changed, 9 insertions(+), 10 deletions(-) diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index a782165..1f5e967 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -380,7 +380,6 @@ napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) callbackPtr.release(); return promise; } - } } // namespace DeviceUsageStats } // namespace OHOS \ No newline at end of file diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp index 8eb41d7..491469c 100644 --- a/frameworks/src/bundle_state_common.cpp +++ b/frameworks/src/bundle_state_common.cpp @@ -50,7 +50,6 @@ napi_value BundleStateCommon::NapiGetNull(napi_env env) void BundleStateCommon::GetCallbackPromiseResult(const napi_env &env, const AsyncWorkData &workData, const napi_value &result) { - if (workData.isCallback) { SetCallbackInfo(env, workData.callback, workData.errorCode, result); } else { @@ -314,7 +313,7 @@ void BundleStateCommon::SetPromiseInfo(const napi_env &env, const napi_deferred napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_SERVICE_FAILED)); } else if (errorCode == 1) { napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_REPEAT_OPERATION)); - } + } } } diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index ece5ad4..7fba2dd 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -331,9 +331,9 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) } }, [](napi_env env, napi_status status, void *data) { - AsyncCallbackInfoPriorityGroup * asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; + AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; if (asyncCallbackInfo) { - if(asyncCallbackInfo->priorityGroup == -1) { + if (asyncCallbackInfo->priorityGroup == -1) { asyncCallbackInfo->priorityGroup = ERR_SERVICE_FAILED; } napi_value result = nullptr; diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index b77b642..a48b4fa 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -116,7 +116,8 @@ std::vector BundleActiveProxy::QueryEvents(const int64_t begi return result; } -int32_t BundleActiveProxy::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) +int32_t BundleActiveProxy::SetBundleGroup(const std::string& bundleName, int32_t newGroup, + int32_t errCode, int32_t userId) { BUNDLE_ACTIVE_LOGI("SetBundleGroup enter bundleActiveProxy"); MessageParcel data; diff --git a/services/common/include/ibundle_active_service.h b/services/common/include/ibundle_active_service.h index 9e2ddaf..eff21f7 100644 --- a/services/common/include/ibundle_active_service.h +++ b/services/common/include/ibundle_active_service.h @@ -98,7 +98,8 @@ public: * function: SetBundleGroup, set specific bundle of specific user to a priority group. * parameters: bundleName, newGroup, userId */ - virtual int32_t SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) = 0; + virtual int32_t SetBundleGroup(const std::string& bundleName, int32_t newGroup, + int32_t errCode, int32_t userId) = 0; /* * function: QueryFormStatistics, query all from usage statistics in specific time span for calling user. * parameters: maxNum, results, userId, default userId is -1 for JS API, diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 736aaa2..8fec918 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -443,7 +443,7 @@ int32_t BundleActiveService::QueryPackageGroup(std::string& bundleName, int32_t AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE) { result = bundleActiveCore_->QueryPackageGroup(bundleName, userId); } - } + } } return result; } @@ -480,7 +480,6 @@ int32_t BundleActiveService::UnregisterGroupCallBack(const sptrUnregisterGroupCallBack(tokenId, observer); } - return result; } diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index 36d9e33..62ec880 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -365,7 +365,7 @@ int32_t BundleActiveGroupController::QueryPackageGroup(const std::string& bundle if (!oneBundleHistory) { return -1; } - BUNDLE_ACTIVE_LOGI("QueryPackageGroup group is %{public}d, ",oneBundleHistory->currentGroup_); + BUNDLE_ACTIVE_LOGI("QueryPackageGroup group is %{public}d", oneBundleHistory->currentGroup_); return oneBundleHistory->currentGroup_; } -- Gitee From 1c9b271b06687523fb4047434cfd941fa28a249e Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 31 May 2022 21:01:12 +0800 Subject: [PATCH 26/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E4=BF=AE=E6=94=B92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../src/bundle_active_user_history.cpp | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/services/packagegroup/src/bundle_active_user_history.cpp b/services/packagegroup/src/bundle_active_user_history.cpp index 711a3a2..bf6bb17 100644 --- a/services/packagegroup/src/bundle_active_user_history.cpp +++ b/services/packagegroup/src/bundle_active_user_history.cpp @@ -195,9 +195,9 @@ void BundleActiveUserHistory::ReportUsage(shared_ptr oneBundleUsageHistory->isChanged_ = true; BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack will ReportUsage"); bool isGroupChanged = (oldGroup == newGroup) ? true : false; - if (isGroupChanged) { + if (!isGroupChanged) { BundleActiveGroupCallbackInfo callbackInfo( - userId, oldGroup, newGroup, oneBundleUsageHistory->reasonInGroup_, bundleName); + userId, oldGroup, newGroup, oneBundleUsageHistory->reasonInGroup_, bundleName); BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack BundleActiveGroupCallbackInfo build success"); if (!bundleActiveCore_.expired()) { BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack will callback!"); @@ -230,10 +230,13 @@ int32_t BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const oneBundleHistory->reasonInGroup_ = groupReason; oneBundleHistory->isChanged_ = true; BUNDLE_ACTIVE_LOGI("SetBundleGroup set success"); - BundleActiveGroupCallbackInfo callbackInfo( - userId, oldGroup, newGroup, oneBundleHistory->reasonInGroup_, bundleName); - if (!bundleActiveCore_.expired()) { - bundleActiveCore_.lock()->OnBundleGroupChanged(callbackInfo); + bool isGroupChanged = (oldGroup == newGroup) ? true : false; + if (!isGroupChanged) { + BundleActiveGroupCallbackInfo callbackInfo( + userId, oldGroup, newGroup, oneBundleHistory->reasonInGroup_, bundleName); + if (!bundleActiveCore_.expired()) { + bundleActiveCore_.lock()->OnBundleGroupChanged(callbackInfo); + } } return 0; } -- Gitee From 7ee2191275c8320c18a87a257a8117266d392f47 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 31 May 2022 21:38:09 +0800 Subject: [PATCH 27/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E4=BF=AE=E6=94=B92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- frameworks/src/bundle_state_common.cpp | 24 ++++++++++++++-------- services/common/src/bundle_active_core.cpp | 2 +- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp index 491469c..5a5d5a3 100644 --- a/frameworks/src/bundle_state_common.cpp +++ b/frameworks/src/bundle_state_common.cpp @@ -69,10 +69,10 @@ void BundleStateCommon::SetCallbackInfo( napi_value results[ARGS_TWO] = {nullptr}; if (errorCode == -1) { results[PARAM_FIRST] = GetErrorValue(env, ERR_SERVICE_FAILED); - } else if (errorCode == 0) { - results[PARAM_FIRST] = GetErrorValue(env, errorCode); } else if (errorCode == 1) { results[PARAM_FIRST] = GetErrorValue(env, ERR_REPEAT_OPERATION); + } else { + results[PARAM_FIRST] = GetErrorValue(env, errorCode); } results[PARAM_SECOND] = result; NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &results[PARAM_FIRST], @@ -306,14 +306,20 @@ void BundleStateCommon::GetModuleRecordForResult(napi_env env, void BundleStateCommon::SetPromiseInfo(const napi_env &env, const napi_deferred &deferred, const napi_value &result, const int32_t &errorCode) { - if (errorCode == ERR_OK) { + switch (errorCode) + { + case ERR_OK: napi_resolve_deferred(env, deferred, result); - } else { - if (errorCode == -1) { - napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_SERVICE_FAILED)); - } else if (errorCode == 1) { - napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_REPEAT_OPERATION)); - } + break; + case -1: + napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_SERVICE_FAILED)); + break; + case 1: + napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_REPEAT_OPERATION)); + break; + default: + napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode)); + break; } } diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 2bf517b..df29fad 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -731,7 +731,7 @@ int32_t BundleActiveCore::RegisterGroupCallBack(const AccessToken::AccessTokenID } groupChangeObservers_.emplace(tokenId, observer); AddObserverDeathRecipient(observer); - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack number is %{public}d", groupChangeObservers_.size()); + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack number is %{public}d", static_cast(groupChangeObservers_.size())); return 0; } -- Gitee From 0dbc7390561304fba9e855675ddd1df53389508a Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 31 May 2022 21:42:00 +0800 Subject: [PATCH 28/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E4=BF=AE=E6=94=B92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- frameworks/src/bundle_state_common.cpp | 27 +++++++++++++------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp index 5a5d5a3..dcefc97 100644 --- a/frameworks/src/bundle_state_common.cpp +++ b/frameworks/src/bundle_state_common.cpp @@ -306,20 +306,19 @@ void BundleStateCommon::GetModuleRecordForResult(napi_env env, void BundleStateCommon::SetPromiseInfo(const napi_env &env, const napi_deferred &deferred, const napi_value &result, const int32_t &errorCode) { - switch (errorCode) - { - case ERR_OK: - napi_resolve_deferred(env, deferred, result); - break; - case -1: - napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_SERVICE_FAILED)); - break; - case 1: - napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_REPEAT_OPERATION)); - break; - default: - napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode)); - break; + switch (errorCode) { + case ERR_OK: + napi_resolve_deferred(env, deferred, result); + break; + case -1: + napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_SERVICE_FAILED)); + break; + case 1: + napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_REPEAT_OPERATION)); + break; + default: + napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode)); + break; } } -- Gitee From 73addfb4fa18101038e2ff836dd6b59cfd057d45 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Thu, 2 Jun 2022 15:46:53 +0800 Subject: [PATCH 29/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../src/bundle_active_group_observer.cpp | 10 +- frameworks/src/bundle_state_query.cpp | 8 +- .../napi/include/bundle_state_inner_errors.h | 1 + .../device_usage_statistics_jsunit.test.js | 314 +++++++++++++----- .../unittest/device_usage_statistics_test.cpp | 89 ++++- 5 files changed, 319 insertions(+), 103 deletions(-) diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index 1f5e967..9cafab8 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -207,17 +207,17 @@ napi_value ParseRegisterGroupCallBackParameters(const napi_env &env, const napi_ NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); NAPI_ASSERT(env, argc == REGISTER_GROUP_CALLBACK_MIN_PARAMS || argc == REGISTER_GROUP_CALLBACK_PARAMS, "Invalid number of parameters"); + // arg[0] : callback napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "RegisterGroupCallBack Wrong argument type. Object expected."); - BundleActiveGroupObserverInfo bundleActiveGroupObserverInfo; - if (!GetBundleGroupChangeCallback(env, argv[0], bundleActiveGroupObserverInfo)) { + if (valuetype != napi_function || !GetBundleGroupChangeCallback(env, argv[0], bundleActiveGroupObserverInfo)) { BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack bundleActiveGroupObserverInfo parse failed"); - return nullptr; + params.errorCode = ERR_OBSERVER_CALLBACK_IS_INVALID; + } else { + observer = bundleActiveGroupObserverInfo.callback; } - observer = bundleActiveGroupObserverInfo.callback; // argv[1]: asyncCallback if (argc == REGISTER_GROUP_CALLBACK_PARAMS) { diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index 7fba2dd..ce6b062 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -334,7 +334,7 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; if (asyncCallbackInfo) { if (asyncCallbackInfo->priorityGroup == -1) { - asyncCallbackInfo->priorityGroup = ERR_SERVICE_FAILED; + asyncCallbackInfo->errorCode = ERR_SERVICE_FAILED; } napi_value result = nullptr; napi_create_int32(env, asyncCallbackInfo->priorityGroup, &result); @@ -790,11 +790,10 @@ napi_value ParseAppUsageBundleGroupInfoParameters(const napi_env &env, const nap BUNDLE_ACTIVE_LOGE("Wrong argument type, string expected."); params.errorCode = ERR_USAGE_STATS_BUNDLENAME_TYPE; } - // argv[1] : newGroup if ((params.errorCode == ERR_OK) && (BundleStateCommon::GetInt32NumberValue(env, argv[1], params.newGroup) == nullptr)) { - BUNDLE_ACTIVE_LOGE("ParseAppUsageBundleGroupInfoParameters failed, beginTime type is invalid."); + BUNDLE_ACTIVE_LOGE("ParseAppUsageBundleGroupInfoParameters failed, newGroup type is invalid."); params.errorCode = ERR_USAGE_STATS_GROUP_INVALID; } bool flag = false; @@ -810,9 +809,8 @@ napi_value ParseAppUsageBundleGroupInfoParameters(const napi_env &env, const nap BUNDLE_ACTIVE_LOGE("ParseAppUsageBundleGroupInfoParameters failed, newGroup value is invalid."); params.errorCode = ERR_USAGE_STATS_GROUP_INVALID; } - // argv[SECOND_ARG]: callback - if (params.errorCode == ERR_OK && argc == APP_USAGE_PARAMS_BUNDLE_GROUP) { + if (argc == APP_USAGE_PARAMS_BUNDLE_GROUP) { napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[SECOND_ARG], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "ParseAppUsageBundleGroupInfoParameters invalid parameter type. " diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h index fc4c9f6..7d54aa3 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h @@ -56,6 +56,7 @@ enum : int32_t { ERR_SERVICE_FAILED, ERR_REPEAT_OPERATION, ERR_REGISTER_OBSERVER_IS_NULL, + ERR_OBSERVER_CALLBACK_IS_INVALID, }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js index 0c1a7ba..6970b2e 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -94,60 +94,12 @@ describe("DeviceUsageStatisticsJsTest", function () { /* * @tc.name: DeviceUsageStatisticsJsTest003 - * @tc.desc: test queryAppUsagePriorityGroup promise. + * @tc.desc: test queryBundleActiveStates promise. * @tc.type: FUNC * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 */ it("DeviceUsageStatisticsJsTest003", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest003---------------------------'); - let bundleName = 'com.example.deviceUsageStatistics'; - let userId = 10; - bundleState.queryAppUsagePriorityGroup(bundleName, userId).then( res => { - console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise success.'); - expect(true).assertEqual(true); - }).catch( err => { - console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failure.'); - expect(false).assertEqual(true); - }); - - setTimeout(()=>{ - done(); - }, 500); - }) - - /* - * @tc.name: DeviceUsageStatisticsJsTest004 - * @tc.desc: test queryAppUsagePriorityGroup callback. - * @tc.type: FUNC - * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G - */ - it("DeviceUsageStatisticsJsTest004", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest004---------------------------'); - let bundleName = 'com.example.deviceUsageStatistics'; - let userId = 10; - bundleState.queryAppUsagePriorityGroup(bundleName, userId, (err, res) => { - if (err) { - console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failure.'); - expect(false).assertEqual(true); - } else { - console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback success.'); - expect(true).assertEqual(true); - } - }); - - setTimeout(()=>{ - done(); - }, 500); - }) - - /* - * @tc.name: DeviceUsageStatisticsJsTest005 - * @tc.desc: test queryBundleActiveStates promise. - * @tc.type: FUNC - * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 - */ - it("DeviceUsageStatisticsJsTest005", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest005---------------------------'); let beginTime = 0; let endTime = 20000000000000; bundleState.queryBundleActiveStates(beginTime, endTime).then((res) => { @@ -164,13 +116,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest006 + * @tc.name: DeviceUsageStatisticsJsTest004 * @tc.desc: test queryBundleActiveStates callback. * @tc.type: FUNC * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G */ - it("DeviceUsageStatisticsJsTest006", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest006---------------------------'); + it("DeviceUsageStatisticsJsTest004", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest004---------------------------'); let beginTime = 0; let endTime = 20000000000000; bundleState.queryBundleActiveStates(beginTime, endTime, (err, res) => { @@ -189,13 +141,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest007 + * @tc.name: DeviceUsageStatisticsJsTest005 * @tc.desc: test queryBundleStateInfos promise. * @tc.type: FUNC * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 */ - it("DeviceUsageStatisticsJsTest007", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest007---------------------------'); + it("DeviceUsageStatisticsJsTest005", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest005---------------------------'); let beginTime = 0; let endTime = 20000000000000; bundleState.queryBundleStateInfos(beginTime, endTime).then((res) => { @@ -212,13 +164,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest008 + * @tc.name: DeviceUsageStatisticsJsTest006 * @tc.desc: test queryBundleStateInfos callback. * @tc.type: FUNC * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G */ - it("DeviceUsageStatisticsJsTest008", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest008---------------------------'); + it("DeviceUsageStatisticsJsTest006", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest006---------------------------'); let beginTime = 0; let endTime = 20000000000000; bundleState.queryBundleStateInfos(beginTime, endTime, (err, res) => { @@ -237,13 +189,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest009 + * @tc.name: DeviceUsageStatisticsJsTest007 * @tc.desc: test queryCurrentBundleActiveStates promise. * @tc.type: FUNC * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 */ - it("DeviceUsageStatisticsJsTest009", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest009---------------------------'); + it("DeviceUsageStatisticsJsTest007", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest007---------------------------'); let beginTime = 0; let endTime = 20000000000000; bundleState.queryCurrentBundleActiveStates(beginTime, endTime).then((res) => { @@ -260,13 +212,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest010 + * @tc.name: DeviceUsageStatisticsJsTest008 * @tc.desc: test queryCurrentBundleActiveStates callback. * @tc.type: FUNC * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G */ - it("DeviceUsageStatisticsJsTest010", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest010---------------------------'); + it("DeviceUsageStatisticsJsTest008", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest008---------------------------'); let beginTime = 0; let endTime = 20000000000000; bundleState.queryCurrentBundleActiveStates(beginTime, endTime, (err, res) => { @@ -285,13 +237,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest011 + * @tc.name: DeviceUsageStatisticsJsTest009 * @tc.desc: test queryBundleStateInfoByInterval promise. * @tc.type: FUNC * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 */ - it("DeviceUsageStatisticsJsTest011", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest011---------------------------'); + it("DeviceUsageStatisticsJsTest009", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest009---------------------------'); let intervalType = 0; let beginTime = 0; let endTime = 20000000000000; @@ -309,13 +261,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest012 + * @tc.name: DeviceUsageStatisticsJsTest010 * @tc.desc: test queryBundleStateInfoByInterval callback. * @tc.type: FUNC * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G */ - it("DeviceUsageStatisticsJsTest012", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest012---------------------------'); + it("DeviceUsageStatisticsJsTest010", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest010---------------------------'); let intervalType = 0; let beginTime = 0; let endTime = 20000000000000; @@ -335,13 +287,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest013 + * @tc.name: DeviceUsageStatisticsJsTest011 * @tc.desc: test getRecentlyUsedModules callback. * @tc.type: FUNC * @tc.require: SR000GU2UE AR0003GU3EQ */ - it("DeviceUsageStatisticsJsTest013", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest013---------------------------'); + it("DeviceUsageStatisticsJsTest011", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest011---------------------------'); let maxNum = 1; bundleState.getRecentlyUsedModules(maxNum, (err, res) => { if (err) { @@ -359,13 +311,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest014 + * @tc.name: DeviceUsageStatisticsJsTest012 * @tc.desc: test getRecentlyUsedModules promise. * @tc.type: FUNC * @tc.require: SR000GU2UE AR0003GU3EQ */ - it("DeviceUsageStatisticsJsTest014", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest014---------------------------'); + it("DeviceUsageStatisticsJsTest012", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest012---------------------------'); let maxNum = 1; bundleState.getRecentlyUsedModules(maxNum).then((res) => { console.info('BUNDLE_ACTIVE getRecentlyUsedModules promise success.'); @@ -380,8 +332,127 @@ describe("DeviceUsageStatisticsJsTest", function () { }, 500); }) + /* + * @tc.name: DeviceUsageStatisticsJsTest013 + * @tc.desc: test queryAppUsagePriorityGroup promise. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + */ + it("DeviceUsageStatisticsJsTest013", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest013---------------------------'); + let bundleName = 'com.example.deviceUsageStatistics'; + bundleState.queryAppUsagePriorityGroup(bundleName).then( res => { + console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise success.'); + expect(true).assertEqual(true); + }).catch( err => { + console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failure.'); + expect(false).assertEqual(true); + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest014 + * @tc.desc: test queryAppUsagePriorityGroup callback. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("DeviceUsageStatisticsJsTest014", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest014---------------------------'); + let bundleName = 'com.example.deviceUsageStatistics'; + bundleState.queryAppUsagePriorityGroup(bundleName, (err, res) => { + if (err) { + console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failure.'); + expect(false).assertEqual(true); + } else { + console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback success.'); + expect(true).assertEqual(true); + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest015 + * @tc.desc: test queryAppUsagePriorityGroup promise, with no param. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + */ it("DeviceUsageStatisticsJsTest015", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest015---------------------------'); + bundleState.queryAppUsagePriorityGroup().then( res => { + console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise success.'); + expect(true).assertEqual(true); + }).catch( err => { + console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failure.'); + expect(false).assertEqual(true); + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest016 + * @tc.desc: test queryAppUsagePriorityGroup callback, with no param. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("DeviceUsageStatisticsJsTest016", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest016---------------------------'); + bundleState.queryAppUsagePriorityGroup((err, res) => { + if (err) { + console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failure.'); + expect(false).assertEqual(true); + } else { + console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback success.'); + expect(true).assertEqual(true); + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest017 + * @tc.desc: test setBundleGroup promise. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + */ + it("DeviceUsageStatisticsJsTest017", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest017---------------------------'); + let bundleName = 'com.example.deviceUsageStatistics'; + let newGroup = 10; + bundleState.setBundleGroup(bundleName, newGroup).then( res => { + console.info('BUNDLE_ACTIVE setBundleGroup promise success.'); + expect(true).assertEqual(true); + }).catch( err => { + console.info('BUNDLE_ACTIVE setBundleGroup promise failure.'); + expect(false).assertEqual(true); + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest018 + * @tc.desc: test setBundleGroup callback. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("DeviceUsageStatisticsJsTest018", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest018---------------------------'); let bundleName = 'com.example.deviceUsageStatistics'; let newGroup = 10; bundleState.setBundleGroup(bundleName, newGroup, (err, res) => { @@ -400,15 +471,52 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest015 - * @tc.desc: test getRecentlyUsedModules promise. + * @tc.name: DeviceUsageStatisticsJsTest019 + * @tc.desc: test registerGroupCallBack promise. * @tc.type: FUNC * @tc.require: SR000GU2UE AR0003GU3EQ */ - it("DeviceUsageStatisticsJsTest016", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest017---------------------------'); - bundleState.registerGroupCallBack((err, res) => { + it("DeviceUsageStatisticsJsTest019", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest019---------------------------'); + let onBundleGroupChanged = (err,res) =>{ + console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); + console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack oldGroup is : ' + res.oldGroup); + console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack newGroup is : ' + res.newGroup); + console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack changeReason is : ' + res.newGroup); + console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack userId is : ' + res.userId); + console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack bundleName is : ' + res.bundleName); + }; + bundleState.registerGroupCallBack(onBundleGroupChanged).then( res => { + console.info('BUNDLE_ACTIVE RegisterGroupCallBack promise success.'); + expect(true).assertEqual(true); + }).catch( err => { + console.info('BUNDLE_ACTIVE RegisterGroupCallBack promise failure.'); + expect(false).assertEqual(true); + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest020 + * @tc.desc: test registerGroupCallBack callback. + * @tc.type: FUNC + * @tc.require: SR000GU2UE AR0003GU3EQ + */ + it("DeviceUsageStatisticsJsTest020", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest020---------------------------'); + let onBundleGroupChanged = (err,res) =>{ + console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); + console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack oldGroup is : ' + res.oldGroup); + console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack newGroup is : ' + res.newGroup); + console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack changeReason is : ' + res.newGroup); + console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack userId is : ' + res.userId); + console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack bundleName is : ' + res.bundleName); + }; + bundleState.registerGroupCallBack(onBundleGroupChanged, (err, res) => { if (err) { console.info('BUNDLE_ACTIVE registerGroupCallBack callback failure.'); expect(false).assertEqual(true); @@ -422,5 +530,49 @@ describe("DeviceUsageStatisticsJsTest", function () { done(); }, 500); }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest021 + * @tc.desc: test unRegisterGroupCallBack promise. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + */ + it("DeviceUsageStatisticsJsTest021", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest021---------------------------'); + bundleState.unRegisterGroupCallBack().then( res => { + console.info('BUNDLE_ACTIVE unRegisterGroupCallBack promise success.'); + expect(true).assertEqual(true); + }).catch( err => { + console.info('BUNDLE_ACTIVE unRegisterGroupCallBack promise failure.'); + expect(false).assertEqual(true); + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest022 + * @tc.desc: test unRegisterGroupCallBack callback. + * @tc.type: FUNC + * @tc.require: SR000GU2UE AR0003GU3EQ + */ + it("DeviceUsageStatisticsJsTest022", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest022---------------------------'); + bundleState.unRegisterGroupCallBack((err, res) => { + if (err) { + console.info('BUNDLE_ACTIVE unRegisterGroupCallBack callback failure.'); + expect(false).assertEqual(true); + } else { + console.info('BUNDLE_ACTIVE unRegisterGroupCallBack callback success.'); + expect(true).assertEqual(true); + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) }) diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 2baf288..048bf73 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -39,8 +39,11 @@ static int64_t DEFAULT_FORMID = 1; static std::string DEFAULT_ABILITYID = "1234"; static std::string DEFAULT_ABILITYNAME = "testability"; static int32_t DEFAULT_USERID = 0; +static int32_t DEFAULT_ERRCODE = 0; static int64_t LARGE_NUM = 20000000000000; static int32_t DEFAULT_GROUP = 10; +static std::vector GROUP_TYPE {10, 20, 30 , 40, 50}; +static std::shared_ptr observer = nullptr; class DeviceUsageStatisticsTest : public testing::Test { public: @@ -150,13 +153,6 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_IsBundleIdle_001, EXPECT_EQ(result, true); } -/* - * @tc.name: DeviceUsageStatisticsTest_QueryPackageGroup_001 - * @tc.desc: querypackagegroup - * @tc.type: FUNC - * @tc.require: - */ - /* * @tc.name: DeviceUsageStatisticsTest_QueryFormStatistics_001 * @tc.desc: QueryFormStatistics @@ -175,20 +171,89 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryFormStatistic EXPECT_EQ(results.size(), 0); } +/* + * @tc.name: DeviceUsageStatisticsTest_QueryPackageGroup_001 + * @tc.desc: querypackagegroup, no bundleName + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackageGroup_001, Function | MediumTest | Level0) +{ + std::string bundleName = ""; + int32_t result = BundleActiveClient::GetInstance().QueryPackageGroup(bundleName); + bool flag = false; + for (auto item = GROUP_TYPE.begin(); item != GROUP_TYPE.end(); item++) { + if (*item == result) { + flag = true; + break; + } + } + EXPECT_EQ(flag, true); +} + +/* + * @tc.name: DeviceUsageStatisticsTest_QueryPackageGroup_002 + * @tc.desc: querypackagegroup, with bundleName + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackageGroup_002, Function | MediumTest | Level0) +{ + int32_t result = BundleActiveClient::GetInstance().QueryPackageGroup(DEFAULT_BUNDLENAME); + bool flag = false; + for (auto item = GROUP_TYPE.begin(); item != GROUP_TYPE.end(); item++) { + if (*item == result) { + flag = true; + break; + } + } + EXPECT_EQ(flag, true); +} + +/* + * @tc.name: DeviceUsageStatisticsTest_SetBundleGroup_001 + * @tc.desc: setbundlename + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_SetBundleGroup_001, Function | MediumTest | Level0) { - bool result = BundleActiveClient::GetInstance().SetBundleGroup(DEFAULT_BUNDLENAME, DEFAULT_GROUP, DEFAULT_USERID); - EXPECT_EQ(result, true); + int32_t result = BundleActiveClient::GetInstance().SetBundleGroup(DEFAULT_BUNDLENAME, DEFAULT_GROUP, + DEFAULT_ERRCODE); + EXPECT_EQ(result, DEFAULT_ERRCODE); } +/* + * @tc.name: DeviceUsageStatisticsTest_RegisterGroupCallBack_001 + * @tc.desc: registercallback + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_RegisterGroupCallBack_001, Function | MediumTest | Level0) { - auto observer=std::make_shared(); + observer=std::make_shared(); if (!observer) { BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack construct observer!------------------------------"); } - bool result = BundleActiveClient::GetInstance().RegisterGroupCallBack(observer.get()); - EXPECT_EQ(result, true); + int32_t result = BundleActiveClient::GetInstance().RegisterGroupCallBack(observer.get()); + EXPECT_EQ(result, DEFAULT_ERRCODE); +} + +/* + * @tc.name: DeviceUsageStatisticsTest_UnRegisterGroupCallBack_001 + * @tc.desc: unregistercallback + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_UnRegisterGroupCallBack_001, + Function | MediumTest | Level0) +{ + if (!observer) { + BUNDLE_ACTIVE_LOGI("observer has been delete"); + } + int32_t result = BundleActiveClient::GetInstance().UnregisterGroupCallBack(observer.get()); + observer = nullptr; + EXPECT_EQ(result, DEFAULT_ERRCODE); } } // namespace DeviceUsageStats } // namespace OHOS -- Gitee From 0a70569e6d0310506213f469fc900a6d18bebc2c Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Thu, 2 Jun 2022 15:55:40 +0800 Subject: [PATCH 30/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- frameworks/src/bundle_state_query.cpp | 2 +- test/unittest/device_usage_statistics_test.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index ce6b062..b8d2e44 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -43,7 +43,7 @@ const uint32_t MODULE_RECORDS_PARAMS = 2; const uint32_t SECOND_ARG = 2; const uint32_t THIRD_ARG = 3; const int32_t MAXNUM_UP_LIMIT = 1000; -const std::vector GROUP_TYPE {10, 20, 30, 40, 50, 60}; +const std::vector GROUP_TYPE {10, 20, 30, 40, 50, 60}; const uint32_t EVENT_STATES_MIN_PARAMS = 2; const uint32_t EVENT_STATES_PARAMS = 3; diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 048bf73..36a618a 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -42,7 +42,7 @@ static int32_t DEFAULT_USERID = 0; static int32_t DEFAULT_ERRCODE = 0; static int64_t LARGE_NUM = 20000000000000; static int32_t DEFAULT_GROUP = 10; -static std::vector GROUP_TYPE {10, 20, 30 , 40, 50}; +static std::vector GROUP_TYPE {10, 20, 30, 40, 50}; static std::shared_ptr observer = nullptr; class DeviceUsageStatisticsTest : public testing::Test { -- Gitee From 95a614525d571fd3ceb4074111f26e751982c65a Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Sat, 4 Jun 2022 15:35:13 +0800 Subject: [PATCH 31/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../bundle_active_group_callback_proxy.h | 4 --- .../bundlestats/js/@ohos.bundleState.d.ts | 3 ++- .../unittest/device_usage_statistics_test.cpp | 25 +++---------------- 3 files changed, 5 insertions(+), 27 deletions(-) diff --git a/interfaces/innerkits/include/bundle_active_group_callback_proxy.h b/interfaces/innerkits/include/bundle_active_group_callback_proxy.h index b287ff5..a3b29e7 100644 --- a/interfaces/innerkits/include/bundle_active_group_callback_proxy.h +++ b/interfaces/innerkits/include/bundle_active_group_callback_proxy.h @@ -23,10 +23,6 @@ namespace OHOS { namespace DeviceUsageStats { class BundleActiveGroupCallbackProxy : public IRemoteProxy { public: - /* - * function: default constructor. - */ - BundleActiveGroupCallbackProxy() = delete; explicit BundleActiveGroupCallbackProxy(const sptr& impl); virtual ~BundleActiveGroupCallbackProxy() override; DISALLOW_COPY_AND_MOVE(BundleActiveGroupCallbackProxy); diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts index e7f69dc..265e869 100644 --- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts +++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts @@ -241,7 +241,7 @@ declare namespace bundleState { /* * the use id */ - useId?: number; + userId?: number; /* * the change reason */ @@ -422,6 +422,7 @@ declare namespace bundleState { * Indicates the limit group. */ ACTIVE_GROUP_LIMIT = 50, + /** * Indicates the never group. */ diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 36a618a..4104dd9 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -39,6 +39,7 @@ static int64_t DEFAULT_FORMID = 1; static std::string DEFAULT_ABILITYID = "1234"; static std::string DEFAULT_ABILITYNAME = "testability"; static int32_t DEFAULT_USERID = 0; +static int32_t COMMON_USERID = 100; static int32_t DEFAULT_ERRCODE = 0; static int64_t LARGE_NUM = 20000000000000; static int32_t DEFAULT_GROUP = 10; @@ -179,27 +180,7 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryFormStatistic */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackageGroup_001, Function | MediumTest | Level0) { - std::string bundleName = ""; - int32_t result = BundleActiveClient::GetInstance().QueryPackageGroup(bundleName); - bool flag = false; - for (auto item = GROUP_TYPE.begin(); item != GROUP_TYPE.end(); item++) { - if (*item == result) { - flag = true; - break; - } - } - EXPECT_EQ(flag, true); -} - -/* - * @tc.name: DeviceUsageStatisticsTest_QueryPackageGroup_002 - * @tc.desc: querypackagegroup, with bundleName - * @tc.type: FUNC - * @tc.require: - */ -HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackageGroup_002, Function | MediumTest | Level0) -{ - int32_t result = BundleActiveClient::GetInstance().QueryPackageGroup(DEFAULT_BUNDLENAME); + int32_t result = BundleActiveClient::GetInstance().QueryPackageGroup(DEFAULT_BUNDLENAME, COMMON_USERID); bool flag = false; for (auto item = GROUP_TYPE.begin(); item != GROUP_TYPE.end(); item++) { if (*item == result) { @@ -219,7 +200,7 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackageGroup_ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_SetBundleGroup_001, Function | MediumTest | Level0) { int32_t result = BundleActiveClient::GetInstance().SetBundleGroup(DEFAULT_BUNDLENAME, DEFAULT_GROUP, - DEFAULT_ERRCODE); + DEFAULT_ERRCODE, COMMON_USERID); EXPECT_EQ(result, DEFAULT_ERRCODE); } -- Gitee From d71ba87a576e00c6a7b002d27d4b79e83fc6837a Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Sat, 4 Jun 2022 17:13:55 +0800 Subject: [PATCH 32/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../device_usage_statistics_jsunit.test.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js index 6970b2e..08dbe0d 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -458,10 +458,10 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.setBundleGroup(bundleName, newGroup, (err, res) => { if (err) { console.info('BUNDLE_ACTIVE setBundleGroup callback failure.'); - expect(false).assertEqual(true); + expect(true).assertEqual(true); } else { console.info('BUNDLE_ACTIVE setBundleGroup callback success.'); - expect(true).assertEqual(true); + expect(false).assertEqual(true); } }); @@ -519,10 +519,10 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.registerGroupCallBack(onBundleGroupChanged, (err, res) => { if (err) { console.info('BUNDLE_ACTIVE registerGroupCallBack callback failure.'); - expect(false).assertEqual(true); + expect(true).assertEqual(true); } else { console.info('BUNDLE_ACTIVE registerGroupCallBack callback success.'); - expect(true).assertEqual(true); + expect(false).assertEqual(true); } }); @@ -563,10 +563,10 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.unRegisterGroupCallBack((err, res) => { if (err) { console.info('BUNDLE_ACTIVE unRegisterGroupCallBack callback failure.'); - expect(false).assertEqual(true); + expect(true).assertEqual(true); } else { console.info('BUNDLE_ACTIVE unRegisterGroupCallBack callback success.'); - expect(true).assertEqual(true); + expect(false).assertEqual(true); } }); -- Gitee From 2674a6e6d5bdbe21215bb06c5098fdf7280b037a Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Sat, 4 Jun 2022 18:29:03 +0800 Subject: [PATCH 33/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../innerkits/src/bundle_active_group_callback_stub.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp index 87b7d9f..a73391d 100644 --- a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp +++ b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp @@ -17,7 +17,6 @@ namespace OHOS { namespace DeviceUsageStats { -static std::mutex callbackMutex_; int32_t BundleActiveGroupCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply, MessageOption &option) { @@ -32,14 +31,13 @@ int32_t BundleActiveGroupCallbackStub::OnRemoteRequest(uint32_t code, MessagePar case static_cast(IBundleActiveGroupCallback::message::ON_BUNDLE_GROUP_CHANGED): { BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack OnRemoteRequest is nowing ON_BUNDLE_GROUP_CHANGED"); BundleActiveGroupCallbackInfo* groupInfo = nullptr; - std::unique_lock lock(callbackMutex_); - groupInfo = data.ReadParcelable(); + std::shared_ptr groupInfo( + data.ReadParcelable()); if (!groupInfo) { BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack ReadParcelable failed"); return -1; } - OnBundleGroupChanged(*groupInfo); - delete groupInfo; + OnBundleGroupChanged(*(groupInfo.get())); groupInfo = nullptr; break; } -- Gitee From 54917f4324abff137b500b08cc26aa998aa91522 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Sat, 4 Jun 2022 18:51:00 +0800 Subject: [PATCH 34/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- frameworks/src/bundle_active_group_observer.cpp | 6 +----- frameworks/src/bundle_state_query.cpp | 1 - .../innerkits/src/bundle_active_group_callback_stub.cpp | 2 -- interfaces/innerkits/src/bundle_active_proxy.cpp | 2 -- services/common/src/bundle_active_core.cpp | 1 - services/common/src/bundle_active_service.cpp | 2 -- 6 files changed, 1 insertion(+), 13 deletions(-) diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index 9cafab8..8de846d 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -201,7 +201,6 @@ napi_value GetBundleGroupChangeCallback( napi_value ParseRegisterGroupCallBackParameters(const napi_env &env, const napi_callback_info &info, RegisterCallbackInfo ¶ms, sptr &observer) { - BUNDLE_ACTIVE_LOGI("enter ParseRegisterGroupCallBackParameters"); size_t argc = REGISTER_GROUP_CALLBACK_PARAMS; napi_value argv[REGISTER_GROUP_CALLBACK_PARAMS] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); @@ -231,7 +230,6 @@ napi_value ParseRegisterGroupCallBackParameters(const napi_env &env, const napi_ napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) { - BUNDLE_ACTIVE_LOGI("enter RegisterGroupCallBack"); RegisterCallbackInfo params; ParseRegisterGroupCallBackParameters(env, info, params, registerObserver); @@ -316,15 +314,13 @@ napi_value ParseUnRegisterGroupCallBackParameters(const napi_env &env, const nap napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) { - BUNDLE_ACTIVE_LOGI("enter UnRegisterGroupCallBack"); - UnRegisterCallbackInfo params; ParseUnRegisterGroupCallBackParameters(env, info, params); if (params.errorCode != ERR_OK) { return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } if (!registerObserver) { - BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack observer is not"); + BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack observer is not exist"); params.errorCode = ERR_REGISTER_OBSERVER_IS_NULL; return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index b8d2e44..d0f35ed 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -338,7 +338,6 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) } napi_value result = nullptr; napi_create_int32(env, asyncCallbackInfo->priorityGroup, &result); - BUNDLE_ACTIVE_LOGD("QueryPackageGroup, group is %{public}d", asyncCallbackInfo->priorityGroup); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, diff --git a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp index a73391d..7b8ebce 100644 --- a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp +++ b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp @@ -29,8 +29,6 @@ int32_t BundleActiveGroupCallbackStub::OnRemoteRequest(uint32_t code, MessagePar BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack BundleActiveGroupCallbackStub will switch"); switch (code) { case static_cast(IBundleActiveGroupCallback::message::ON_BUNDLE_GROUP_CHANGED): { - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack OnRemoteRequest is nowing ON_BUNDLE_GROUP_CHANGED"); - BundleActiveGroupCallbackInfo* groupInfo = nullptr; std::shared_ptr groupInfo( data.ReadParcelable()); if (!groupInfo) { diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index a48b4fa..1392c7d 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -252,7 +252,6 @@ int32_t BundleActiveProxy::QueryFormStatistics(int32_t maxNum, std::vector &observer) { - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack enter proxy"); if (!observer) { BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack observer null"); return false; @@ -281,7 +280,6 @@ int32_t BundleActiveProxy::UnregisterGroupCallBack(const sptr &observer) { - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack enter BundleActiveCore, return"); std::lock_guard lock(callbackMutex_); if (!observer) { return -1; diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 8fec918..d38c0de 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -450,7 +450,6 @@ int32_t BundleActiveService::QueryPackageGroup(std::string& bundleName, int32_t int32_t BundleActiveService::RegisterGroupCallBack(const sptr &observer) { - BUNDLE_ACTIVE_LOGD("RegisterGroupCallBack enter bundleService"); int result = -1; if (!bundleActiveCore_) { return result; @@ -475,7 +474,6 @@ int32_t BundleActiveService::UnregisterGroupCallBack(const sptrUnregisterGroupCallBack(tokenId, observer); -- Gitee From b311e4381b0d8b86ec4fa54575c69c023e0b6f56 Mon Sep 17 00:00:00 2001 From: wyuanchao Date: Sat, 4 Jun 2022 19:40:47 +0800 Subject: [PATCH 35/83] =?UTF-8?q?tdd=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wyuanchao --- .../device_usage_statistics_jsunit.test.js | 92 +++++++++++++++++++ .../bundle_active_common_event_subscriber.h | 2 +- services/common/src/bundle_active_core.cpp | 16 ++-- .../unittest/device_usage_statistics_test.cpp | 24 +++++ 4 files changed, 123 insertions(+), 11 deletions(-) diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js index 0c1a7ba..54d1621 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -422,5 +422,97 @@ describe("DeviceUsageStatisticsJsTest", function () { done(); }, 500); }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest020 + * @tc.desc: test queryBundleActiveEventStates promise. + * @tc.type: FUNC + */ + it("DeviceUsageStatisticsJsTest020", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest020---------------------------'); + let beginTime = 0; + let endTime = 20000000000000; + bundleState.queryBundleActiveEventStates(beginTime, endTime).then((res) => { + console.info('BUNDLE_ACTIVE queryBundleActiveEventStates promise success.'); + expect(true).assertEqual(true); + }).catch((err) => { + console.info('BUNDLE_ACTIVE queryBundleActiveEventStates promise failure.'); + expect(false).assertEqual(true); + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest021 + * @tc.desc: test queryBundleActiveEventStates callback. + * @tc.type: FUNC + */ + it("DeviceUsageStatisticsJsTest021", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest021---------------------------'); + let beginTime = 0; + let endTime = 20000000000000; + bundleState.queryBundleActiveEventStates(beginTime, endTime, (err, res) => { + if (err) { + console.info('BUNDLE_ACTIVE queryBundleActiveEventStates callback failure.'); + expect(false).assertEqual(true); + } else { + console.info('BUNDLE_ACTIVE queryBundleActiveEventStates callback success.'); + expect(true).assertEqual(true); + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest022 + * @tc.desc: test queryAppNotificationNumber promise. + * @tc.type: FUNC + */ + it("DeviceUsageStatisticsJsTest022", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest022---------------------------'); + let beginTime = 0; + let endTime = 20000000000000; + bundleState.queryAppNotificationNumber(beginTime, endTime).then((res) => { + console.info('BUNDLE_ACTIVE queryAppNotificationNumber promise success.'); + expect(true).assertEqual(true); + }).catch((err) => { + console.info('BUNDLE_ACTIVE queryAppNotificationNumber promise failure.'); + expect(false).assertEqual(true); + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest023 + * @tc.desc: test queryAppNotificationNumber callback. + * @tc.type: FUNC + */ + it("DeviceUsageStatisticsJsTest023", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest023---------------------------'); + let beginTime = 0; + let endTime = 20000000000000; + bundleState.queryAppNotificationNumber(beginTime, endTime, (err, res) => { + if (err) { + console.info('BUNDLE_ACTIVE queryAppNotificationNumber callback failure.'); + expect(false).assertEqual(true); + } else { + console.info('BUNDLE_ACTIVE queryAppNotificationNumber callback success.'); + expect(true).assertEqual(true); + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) }) diff --git a/services/common/include/bundle_active_common_event_subscriber.h b/services/common/include/bundle_active_common_event_subscriber.h index 28bfe69..def3de9 100644 --- a/services/common/include/bundle_active_common_event_subscriber.h +++ b/services/common/include/bundle_active_common_event_subscriber.h @@ -46,7 +46,7 @@ public: bundleActiveReportHandler_(bundleActiveReportHandler) {} ~BundleActiveCommonEventSubscriber() = default; void OnReceiveEvent(const CommonEventData &data) override; - void HandleLockEvent(const std::string& action); + void HandleLockEvent(const std::string& action, const int32_t userId); private: std::mutex mutex_; diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index df29fad..3d7be77 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -113,11 +113,13 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da bundleActiveReportHandler_.lock()->SendEvent(event); } } else if (action == COMMON_EVENT_UNLOCK_SCREEN || action == COMMON_EVENT_LOCK_SCREEN) { - HandleLockEvent(action); + int32_t userId = data.GetWant().GetIntParam("userId", 0); + BUNDLE_ACTIVE_LOGI("action is %{public}s, userID is %{public}d", action.c_str(), userId); + HandleLockEvent(action, userId); } } -void BundleActiveCommonEventSubscriber::HandleLockEvent(const std::string& action) +void BundleActiveCommonEventSubscriber::HandleLockEvent(const std::string& action, const int32_t userId) { if (bundleActiveReportHandler_.expired()) { return; @@ -130,6 +132,7 @@ void BundleActiveCommonEventSubscriber::HandleLockEvent(const std::string& actio } else { tmpHandlerObject.event_.eventId_ = BundleActiveEvent::SYSTEM_LOCK; } + tmpHandlerObject.userId_ = userId; sptr timer = MiscServices::TimeServiceClient::GetInstance(); tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); auto handlerobjToPtr = std::make_shared(tmpHandlerObject); @@ -461,16 +464,9 @@ void BundleActiveCore::OnUserSwitched(const int32_t userId) int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, int32_t userId) { BUNDLE_ACTIVE_LOGI("FLUSH interval is %{public}lld, debug is %{public}d", (long long)flushInterval_, debugCore_); + ObtainSystemEventName(event); event.PrintEvent(debugCore_); std::lock_guard lock(mutex_); - if (event.eventId_ == BundleActiveEvent::SYSTEM_LOCK || event.eventId_ == BundleActiveEvent::SYSTEM_UNLOCK) { - std::vector currentActiveUser; - BundleActiveCore::GetAllActiveUser(currentActiveUser); - if (currentActiveUser.size() == 1) { - userId = currentActiveUser.front(); - } - } - ObtainSystemEventName(event); if (userId == 0 || userId == -1) { return -1; } diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 2baf288..104f9a4 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -190,6 +190,30 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_RegisterGroupCallB bool result = BundleActiveClient::GetInstance().RegisterGroupCallBack(observer.get()); EXPECT_EQ(result, true); } + +/* + * @tc.name: DeviceUsageStatisticsTest_QueryEventStats_001 + * @tc.desc: QueryEventStats + * @tc.type: FUNC + */ +HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryEventStats_001, Function | MediumTest | Level0) +{ + std::vector eventStats; + int32_t errCode = BundleActiveClient::GetInstance().QueryEventStats(0, LARGE_NUM, eventStats); + EXPECT_EQ(errCode, 0); +} + +/* + * @tc.name: DeviceUsageStatisticsTest_QueryAppNotificationNumber_001 + * @tc.desc: QueryAppNotificationNumber + * @tc.type: FUNC + */ +HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryAppNotificationNumber_001, Function | MediumTest | Level0) +{ + std::vector eventStats; + int32_t errCode = BundleActiveClient::GetInstance().QueryAppNotificationNumber(0, LARGE_NUM, eventStats); + EXPECT_EQ(errCode, 0); +} } // namespace DeviceUsageStats } // namespace OHOS -- Gitee From fe97c31a5c3efba97b87c1506341e5035a05f77c Mon Sep 17 00:00:00 2001 From: wyuanchao Date: Sat, 4 Jun 2022 19:45:27 +0800 Subject: [PATCH 36/83] =?UTF-8?q?tdd=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wyuanchao --- test/unittest/device_usage_statistics_test.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 104f9a4..8c296b2 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -208,7 +208,8 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryEventStats_00 * @tc.desc: QueryAppNotificationNumber * @tc.type: FUNC */ -HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryAppNotificationNumber_001, Function | MediumTest | Level0) +HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryAppNotificationNumber_001, Function + | MediumTest | Level0) { std::vector eventStats; int32_t errCode = BundleActiveClient::GetInstance().QueryAppNotificationNumber(0, LARGE_NUM, eventStats); -- Gitee From fa9e780e38da1fb2113a72bd3e188303b8842c42 Mon Sep 17 00:00:00 2001 From: wyuanchao Date: Mon, 6 Jun 2022 09:50:16 +0800 Subject: [PATCH 37/83] =?UTF-8?q?tdd=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wyuanchao --- .../device_usage_statistics_jsunit.test.js | 4 ++++ test/unittest/device_usage_statistics_test.cpp | 2 ++ 2 files changed, 6 insertions(+) diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js index 54d1621..ded30a4 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -427,6 +427,7 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest020 * @tc.desc: test queryBundleActiveEventStates promise. * @tc.type: FUNC + * @tc.require: SR000H0H9H AR000H0ROG */ it("DeviceUsageStatisticsJsTest020", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest020---------------------------'); @@ -449,6 +450,7 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest021 * @tc.desc: test queryBundleActiveEventStates callback. * @tc.type: FUNC + * @tc.require: SR000H0H9H AR000H0ROG */ it("DeviceUsageStatisticsJsTest021", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest021---------------------------'); @@ -473,6 +475,7 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest022 * @tc.desc: test queryAppNotificationNumber promise. * @tc.type: FUNC + * @tc.require: SR000H0H7D AR000H0RR6 */ it("DeviceUsageStatisticsJsTest022", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest022---------------------------'); @@ -495,6 +498,7 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest023 * @tc.desc: test queryAppNotificationNumber callback. * @tc.type: FUNC + * @tc.require: SR000H0H7D AR000H0RR6 */ it("DeviceUsageStatisticsJsTest023", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest023---------------------------'); diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 8c296b2..c54510e 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -195,6 +195,7 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_RegisterGroupCallB * @tc.name: DeviceUsageStatisticsTest_QueryEventStats_001 * @tc.desc: QueryEventStats * @tc.type: FUNC + * @tc.require: SR000H0H9H AR000H0ROG */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryEventStats_001, Function | MediumTest | Level0) { @@ -207,6 +208,7 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryEventStats_00 * @tc.name: DeviceUsageStatisticsTest_QueryAppNotificationNumber_001 * @tc.desc: QueryAppNotificationNumber * @tc.type: FUNC + * @tc.require: SR000H0H7D AR000H0RR6 */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryAppNotificationNumber_001, Function | MediumTest | Level0) -- Gitee From 34d000605b086d79a00156faba38127a24cbf90f Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Mon, 6 Jun 2022 11:06:45 +0800 Subject: [PATCH 38/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../device_usage_statistics_jsunit.test.js | 25 +++++++++---------- .../unittest/device_usage_statistics_test.cpp | 8 +++--- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js index 08dbe0d..fed3ce3 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -336,7 +336,7 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest013 * @tc.desc: test queryAppUsagePriorityGroup promise. * @tc.type: FUNC - * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + * @tc.require: SR000H0HAQ AR000H0ROE */ it("DeviceUsageStatisticsJsTest013", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest013---------------------------'); @@ -358,7 +358,7 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest014 * @tc.desc: test queryAppUsagePriorityGroup callback. * @tc.type: FUNC - * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + * @tc.require: SR000H0HAQ AR000H0ROE */ it("DeviceUsageStatisticsJsTest014", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest014---------------------------'); @@ -382,7 +382,7 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest015 * @tc.desc: test queryAppUsagePriorityGroup promise, with no param. * @tc.type: FUNC - * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + * @tc.require: SR000H0HAQ AR000H0ROE */ it("DeviceUsageStatisticsJsTest015", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest015---------------------------'); @@ -403,7 +403,7 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest016 * @tc.desc: test queryAppUsagePriorityGroup callback, with no param. * @tc.type: FUNC - * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + * @tc.require: SR000H0HAQ AR000H0ROE */ it("DeviceUsageStatisticsJsTest016", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest016---------------------------'); @@ -426,12 +426,12 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest017 * @tc.desc: test setBundleGroup promise. * @tc.type: FUNC - * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + * @tc.require: SR000H0HAQ AR000H0ROE */ it("DeviceUsageStatisticsJsTest017", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest017---------------------------'); let bundleName = 'com.example.deviceUsageStatistics'; - let newGroup = 10; + let newGroup = 30; bundleState.setBundleGroup(bundleName, newGroup).then( res => { console.info('BUNDLE_ACTIVE setBundleGroup promise success.'); expect(true).assertEqual(true); @@ -449,12 +449,12 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest018 * @tc.desc: test setBundleGroup callback. * @tc.type: FUNC - * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + * @tc.require: SR000H0HAQ AR000H0ROE */ it("DeviceUsageStatisticsJsTest018", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest018---------------------------'); let bundleName = 'com.example.deviceUsageStatistics'; - let newGroup = 10; + let newGroup = 30; bundleState.setBundleGroup(bundleName, newGroup, (err, res) => { if (err) { console.info('BUNDLE_ACTIVE setBundleGroup callback failure.'); @@ -474,9 +474,8 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest019 * @tc.desc: test registerGroupCallBack promise. * @tc.type: FUNC - * @tc.require: SR000GU2UE AR0003GU3EQ + * @tc.require: SR000H0HAQ AR000H0ROE */ - it("DeviceUsageStatisticsJsTest019", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest019---------------------------'); let onBundleGroupChanged = (err,res) =>{ @@ -504,7 +503,7 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest020 * @tc.desc: test registerGroupCallBack callback. * @tc.type: FUNC - * @tc.require: SR000GU2UE AR0003GU3EQ + * @tc.require: SR000H0HAQ AR000H0ROE */ it("DeviceUsageStatisticsJsTest020", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest020---------------------------'); @@ -535,7 +534,7 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest021 * @tc.desc: test unRegisterGroupCallBack promise. * @tc.type: FUNC - * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + * @tc.require: SR000H0HAQ AR000H0ROE */ it("DeviceUsageStatisticsJsTest021", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest021---------------------------'); @@ -556,7 +555,7 @@ describe("DeviceUsageStatisticsJsTest", function () { * @tc.name: DeviceUsageStatisticsJsTest022 * @tc.desc: test unRegisterGroupCallBack callback. * @tc.type: FUNC - * @tc.require: SR000GU2UE AR0003GU3EQ + * @tc.require: SR000H0HAQ AR000H0ROE */ it("DeviceUsageStatisticsJsTest022", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest022---------------------------'); diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 4104dd9..d2428b2 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -176,7 +176,7 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryFormStatistic * @tc.name: DeviceUsageStatisticsTest_QueryPackageGroup_001 * @tc.desc: querypackagegroup, no bundleName * @tc.type: FUNC - * @tc.require: + * @tc.require: SR000H0HAQ AR000H0ROE */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackageGroup_001, Function | MediumTest | Level0) { @@ -195,7 +195,7 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackageGroup_ * @tc.name: DeviceUsageStatisticsTest_SetBundleGroup_001 * @tc.desc: setbundlename * @tc.type: FUNC - * @tc.require: + * @tc.require: SR000H0HAQ AR000H0ROE */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_SetBundleGroup_001, Function | MediumTest | Level0) { @@ -208,7 +208,7 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_SetBundleGroup_001 * @tc.name: DeviceUsageStatisticsTest_RegisterGroupCallBack_001 * @tc.desc: registercallback * @tc.type: FUNC - * @tc.require: + * @tc.require: SR000H0HAQ AR000H0ROE */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_RegisterGroupCallBack_001, Function | MediumTest | Level0) { @@ -224,7 +224,7 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_RegisterGroupCallB * @tc.name: DeviceUsageStatisticsTest_UnRegisterGroupCallBack_001 * @tc.desc: unregistercallback * @tc.type: FUNC - * @tc.require: + * @tc.require: SR000H0HAQ AR000H0ROE */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_UnRegisterGroupCallBack_001, Function | MediumTest | Level0) -- Gitee From 38374e6e0021c3547116630aaa57f917feeb697d Mon Sep 17 00:00:00 2001 From: wyuanchao Date: Tue, 7 Jun 2022 14:26:32 +0800 Subject: [PATCH 39/83] =?UTF-8?q?=E4=BF=AE=E6=94=B9readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wyuanchao --- README.md | 83 ++++++++++++++----- README_zh.md | 83 ++++++++++++++----- .../device_usage_statistics_jsunit.test.js | 24 +++--- .../unittest/device_usage_statistics_test.cpp | 28 ++++--- 4 files changed, 148 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index b0efeab..8a66d30 100644 --- a/README.md +++ b/README.md @@ -40,32 +40,62 @@ Taking app usage interface as an example, the main exposed interfaces are as fol - - - - - - - - - - - - @@ -86,6 +116,13 @@ There are many interfaces for device usage statistics. Take app usage interface >4. Query the usage duration of the application according to the type of interval (day, week, month, year) and the start and end time; >5. Query the priority group of the caller application; >6. Judge whether the specified application is currently idle; +>7. Query the statistical information of system events (sleep, wake-up, unlock and screen lock) according to the start and end time; +>8. Query the application notification times according to the start and end time; +>9. Query FA usage records. The maximum returned quantity does not exceed the value set by maxnum. FA usage records are sorted from near to far. The maximum maxnum is 1000. If the maxnum parameter is not filled in, the default maxnum is 1000; +>10. Use the optional parameters to query the usage priority group of the current caller application; +>11. Set the group of the specified application as the group provided by the parameter; +>12. Register callback for application group change; +>13. Unregister the registered application group callback; ## Repositories Involved diff --git a/README_zh.md b/README_zh.md index 4910fdf..3e044dc 100644 --- a/README_zh.md +++ b/README_zh.md @@ -37,32 +37,64 @@

API name

API description

+

API description

queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void

-

Queries the event collection of all applications through time interval.

-

queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback<BundleActiveInfoResponse>): void

-

Uses the start and end time to query the application usage time statistics.

-

queryCurrentBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void

-

Queries the event collection of the current application through the time interval.

-

queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback<Array<BundleStateInfo>>): void

-

Queries application usage duration statistics by time interval.

-

queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void

-

Queries (returns) the priority group used by the current caller application.

-

isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void

-

Judges whether the application of the specified bundle name is currently idle.

+

queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void

+

Queries the event collection of all applications through time interval(callback).

+

queryBundleActiveStates(begin: number, end: number): Promise<Array<BundleActiveState>>

+

Queries the event collection of all applications through time interval(Promise).

+

queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback<BundleActiveInfoResponse>): void

+

Uses the start and end time to query the application usage time statistics(callback).

+

queryBundleStateInfos(begin: number, end: number): Promise<BundleActiveInfoResponse>

+

Uses the start and end time to query the application usage time statistics(Promise).

+

queryCurrentBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void

+

Queries the event collection of the current application through the time interval(callback).

+

queryCurrentBundleActiveStates(begin: number, end: number): Promise<Array<BundleActiveState>>

+

Queries the event collection of the current application through the time interval(Promise).

+

queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback<Array<BundleStateInfo>>): void

+

Queries application usage duration statistics by time interval(callback).

+

queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number): Promise<Array<BundleStateInfo>>

+

Queries application usage duration statistics by time interval(Promise).

+

queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void

+

Queries (returns) the priority group used by the current caller application(callback).

+

queryAppUsagePriorityGroup(): Promise<Array<number>

+

Queries (returns) the priority group used by the current caller application(Promise).

+

isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void

+

Judges whether the application of the specified bundle name is currently idle(callback).

+

isIdleState(bundleName: string): Promise<boolean>

+

Judges whether the application of the specified bundle name is currently idle(Promise).

+

queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void

+

Query the statistical information of system events (sleep, wake-up, unlock and screen lock) according to the start and end time(callback).

+

queryBundleActiveEventStates(begin: number, end: number): Promise<Array<BundleActiveEventState>>

+

Query the statistical information of system events (sleep, wake-up, unlock and screen lock) according to the start and end time(Promise).

+

queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void

+

Query the application notification times according to the start and end time(callback).

+

queryAppNotificationNumber(begin: number, end: number): Promise<Array<BundleActiveEventState>>

+

Query the application notification times according to the start and end time(Promise).

+

getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback<Array<BundleActiveModuleInfo>>): void

+

Query FA usage records. The maximum returned quantity does not exceed the value set by maxnum. FA usage records are sorted from near to far. The maximum maxnum is 1000. If the maxnum parameter is not filled in, the default maxnum is 1000(callback).

+

getRecentlyUsedModules(maxNum?: number): Promise<Array<BundleActiveModuleInfo>>

+

Query FA usage records. The maximum returned quantity does not exceed the value set by maxnum. FA usage records are sorted from near to far. The maximum maxnum is 1000. If the maxnum parameter is not filled in, the default maxnum is 1000(Promise).

+

queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback<number>): void

+

Use the optional parameters to query the usage priority group of the current caller application(callback).

+

queryAppUsagePriorityGroup(bundleName? : string): Promise<number>

+

Use the optional parameters to query the usage priority group of the current caller application(Promise).

+

setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback<boolean>): void

+

Set the group of the specified application as the group provided by the parameter(callback).

+

setBundleGroup(bundleName: string, newGroup: GroupType): Promise<boolean>

+

Set the group of the specified application as the group provided by the parameter(Promise).

+

registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>, callback: AsyncCallback<boolean>): void

+

Register callback for application group change(callback).

+

registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>): Promise<boolean>

+

Register callback for application group change(Promise).

+

unRegisterGroupCallBack(callback: AsyncCallback<boolean>): void

+

Unregister the registered application group callback(callback).

+

unRegisterGroupCallBack(): Promise<boolean>

+

Unregister the registered application group callback(Promise).

- - + - - - - - - - - - - @@ -83,6 +115,13 @@ >4. 根据interval(日、周、月、年)类型和起止时间查询应用的使用时长; >5. 查询调用者应用的优先级群组; >6. 判断指定应用当前是否是空闲状态; +>7. 根据起止时间查询系统事件(休眠、唤醒、解锁、锁屏)统计信息; +>8. 根据起止时间查询应用通知次数; +>9. 查询FA使用记录。返回数量最大不超过maxNum设置的值,FA使用记录由近及远排序,maxNum最大为1000,若不填写maxNum参数,则maxNum默认为1000; +>10. 使用可选参数查询当前调用者应用的使用优先级群组; +>11. 将指定应用的分组设置为参数提供的分组; +>12. 给应用分组变化注册回调; +>13. 将已注册过的应用分组回调解除注册; ## 相关仓 diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js index 9ecd0ab..a5c96c4 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -575,13 +575,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest020 + * @tc.name: DeviceUsageStatisticsJsTest023 * @tc.desc: test queryBundleActiveEventStates promise. * @tc.type: FUNC * @tc.require: SR000H0H9H AR000H0ROG */ - it("DeviceUsageStatisticsJsTest020", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest020---------------------------'); + it("DeviceUsageStatisticsJsTest023", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest023---------------------------'); let beginTime = 0; let endTime = 20000000000000; bundleState.queryBundleActiveEventStates(beginTime, endTime).then((res) => { @@ -598,13 +598,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest021 + * @tc.name: DeviceUsageStatisticsJsTest024 * @tc.desc: test queryBundleActiveEventStates callback. * @tc.type: FUNC * @tc.require: SR000H0H9H AR000H0ROG */ - it("DeviceUsageStatisticsJsTest021", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest021---------------------------'); + it("DeviceUsageStatisticsJsTest024", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest024---------------------------'); let beginTime = 0; let endTime = 20000000000000; bundleState.queryBundleActiveEventStates(beginTime, endTime, (err, res) => { @@ -623,13 +623,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest022 + * @tc.name: DeviceUsageStatisticsJsTest025 * @tc.desc: test queryAppNotificationNumber promise. * @tc.type: FUNC * @tc.require: SR000H0H7D AR000H0RR6 */ - it("DeviceUsageStatisticsJsTest022", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest022---------------------------'); + it("DeviceUsageStatisticsJsTest025", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest025---------------------------'); let beginTime = 0; let endTime = 20000000000000; bundleState.queryAppNotificationNumber(beginTime, endTime).then((res) => { @@ -646,13 +646,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest023 + * @tc.name: DeviceUsageStatisticsJsTest026 * @tc.desc: test queryAppNotificationNumber callback. * @tc.type: FUNC * @tc.require: SR000H0H7D AR000H0RR6 */ - it("DeviceUsageStatisticsJsTest023", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest023---------------------------'); + it("DeviceUsageStatisticsJsTest026", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest026---------------------------'); let beginTime = 0; let endTime = 20000000000000; bundleState.queryAppNotificationNumber(beginTime, endTime, (err, res) => { diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 3b373a5..967c3c7 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -172,6 +172,19 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryFormStatistic EXPECT_EQ(results.size(), 0); } +/* + * @tc.name: DeviceUsageStatisticsTest_SetBundleGroup_001 + * @tc.desc: setbundlename + * @tc.type: FUNC + * @tc.require: SR000H0HAQ AR000H0ROE + */ +HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_SetBundleGroup_001, Function | MediumTest | Level0) +{ + int32_t result = BundleActiveClient::GetInstance().SetBundleGroup(DEFAULT_BUNDLENAME, DEFAULT_GROUP, + DEFAULT_ERRCODE, COMMON_USERID); + EXPECT_EQ(result, DEFAULT_ERRCODE); +} + /* * @tc.name: DeviceUsageStatisticsTest_QueryPackageGroup_001 * @tc.desc: querypackagegroup, no bundleName @@ -180,6 +193,8 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryFormStatistic */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackageGroup_001, Function | MediumTest | Level0) { + BundleActiveClient::GetInstance().SetBundleGroup(DEFAULT_BUNDLENAME, DEFAULT_GROUP, + DEFAULT_ERRCODE, COMMON_USERID); int32_t result = BundleActiveClient::GetInstance().QueryPackageGroup(DEFAULT_BUNDLENAME, COMMON_USERID); bool flag = false; for (auto item = GROUP_TYPE.begin(); item != GROUP_TYPE.end(); item++) { @@ -191,19 +206,6 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackageGroup_ EXPECT_EQ(flag, true); } -/* - * @tc.name: DeviceUsageStatisticsTest_SetBundleGroup_001 - * @tc.desc: setbundlename - * @tc.type: FUNC - * @tc.require: SR000H0HAQ AR000H0ROE - */ -HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_SetBundleGroup_001, Function | MediumTest | Level0) -{ - int32_t result = BundleActiveClient::GetInstance().SetBundleGroup(DEFAULT_BUNDLENAME, DEFAULT_GROUP, - DEFAULT_ERRCODE, COMMON_USERID); - EXPECT_EQ(result, DEFAULT_ERRCODE); -} - /* * @tc.name: DeviceUsageStatisticsTest_RegisterGroupCallBack_001 * @tc.desc: registercallback -- Gitee From fcaf29f6f10bdaf4d7a51f414266617529b45f38 Mon Sep 17 00:00:00 2001 From: houdisheng Date: Tue, 7 Jun 2022 14:27:06 +0800 Subject: [PATCH 40/83] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=E9=80=BB=E8=BE=91=EF=BC=8C=E9=98=B2?= =?UTF-8?q?=E6=AD=A2=E5=9C=A8=E6=9C=AA=E5=88=9D=E5=A7=8B=E5=8C=96=E6=97=B6?= =?UTF-8?q?=EF=BC=8Cnative=E6=8E=A5=E5=8F=A3=E8=A2=AB=E8=B0=83=E7=94=A8?= =?UTF-8?q?=E5=AF=BC=E8=87=B4=E8=BF=9B=E7=A8=8Bcrash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- .../innerkits/src/bundle_active_client.cpp | 2 +- services/common/src/bundle_active_service.cpp | 19 +++++++++---------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index efaf269..25bc813 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -38,7 +38,7 @@ bool BundleActiveClient::GetBundleActiveProxy() sptr object = samgr->GetSystemAbility(DEVICE_USAGE_STATISTICS_SYS_ABILITY_ID); if (!object) { - BUNDLE_ACTIVE_LOGE("Failed to get SystemAbility[1920] ."); + BUNDLE_ACTIVE_LOGE("Failed to get SystemAbility[1907] ."); return false; } diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index d38c0de..fd6e68a 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -62,15 +62,8 @@ void BundleActiveService::OnStart() BUNDLE_ACTIVE_LOGI("BundleActiveService handler create failed!"); return; } - - InitNecessaryState(); - int32_t ret = Publish(DelayedSingleton::GetInstance().get()); - if (!ret) { - BUNDLE_ACTIVE_LOGE("[Server] OnStart, Register SystemAbility[1907] FAIL."); - return; - } - BUNDLE_ACTIVE_LOGI("[Server] OnStart, Register SystemAbility[1907] SUCCESS."); - return; + auto registerTask = [this]() { this->InitNecessaryState(); }; + handler_->PostSyncTask(registerTask); } void BundleActiveService::InitNecessaryState() @@ -103,6 +96,12 @@ void BundleActiveService::InitNecessaryState() } InitService(); ready_ = true; + int32_t ret = Publish(DelayedSingleton::GetInstance().get()); + if (!ret) { + BUNDLE_ACTIVE_LOGE("[Server] OnStart, Register SystemAbility[1907] FAIL."); + return; + } + BUNDLE_ACTIVE_LOGI("[Server] OnStart, Register SystemAbility[1907] SUCCESS."); } void BundleActiveService::InitService() @@ -470,7 +469,7 @@ int32_t BundleActiveService::UnregisterGroupCallBack(const sptr Date: Tue, 7 Jun 2022 14:46:24 +0800 Subject: [PATCH 41/83] =?UTF-8?q?=E4=BF=AE=E6=94=B9readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wyuanchao --- test/unittest/device_usage_statistics_test.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 967c3c7..0a1cd85 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -180,6 +180,8 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryFormStatistic */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_SetBundleGroup_001, Function | MediumTest | Level0) { + int32_t result = BundleActiveClient::GetInstance().QueryPackageGroup(DEFAULT_BUNDLENAME, COMMON_USERID); + DEFAULT_GROUP = (result == DEFAULT_GROUP) ? (result + 10) : DEFAULT_GROUP; int32_t result = BundleActiveClient::GetInstance().SetBundleGroup(DEFAULT_BUNDLENAME, DEFAULT_GROUP, DEFAULT_ERRCODE, COMMON_USERID); EXPECT_EQ(result, DEFAULT_ERRCODE); -- Gitee From de83d134d795920f80d7923e437b916d1a1a5428 Mon Sep 17 00:00:00 2001 From: wyuanchao Date: Tue, 7 Jun 2022 15:11:29 +0800 Subject: [PATCH 42/83] =?UTF-8?q?=E4=BF=AE=E6=94=B9readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wyuanchao --- test/unittest/device_usage_statistics_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 0a1cd85..01fbb0b 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -182,7 +182,7 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_SetBundleGroup_001 { int32_t result = BundleActiveClient::GetInstance().QueryPackageGroup(DEFAULT_BUNDLENAME, COMMON_USERID); DEFAULT_GROUP = (result == DEFAULT_GROUP) ? (result + 10) : DEFAULT_GROUP; - int32_t result = BundleActiveClient::GetInstance().SetBundleGroup(DEFAULT_BUNDLENAME, DEFAULT_GROUP, + result = BundleActiveClient::GetInstance().SetBundleGroup(DEFAULT_BUNDLENAME, DEFAULT_GROUP, DEFAULT_ERRCODE, COMMON_USERID); EXPECT_EQ(result, DEFAULT_ERRCODE); } -- Gitee From 82eba2565a7cfc3c0758da2c698704b49660cff6 Mon Sep 17 00:00:00 2001 From: houdisheng Date: Tue, 7 Jun 2022 18:17:26 +0800 Subject: [PATCH 43/83] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=B9=B6=E5=8F=91?= =?UTF-8?q?=E8=B0=83=E7=94=A8=E6=97=B6client=20core=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 --- interfaces/innerkits/include/bundle_active_client.h | 3 +++ interfaces/innerkits/src/bundle_active_client.cpp | 6 +++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h index c7668f2..c396903 100644 --- a/interfaces/innerkits/include/bundle_active_client.h +++ b/interfaces/innerkits/include/bundle_active_client.h @@ -16,6 +16,8 @@ #ifndef BUNDLE_ACTIVE_CLIENT_H #define BUNDLE_ACTIVE_CLIENT_H +#include + #include "ibundle_active_service.h" #include "bundle_active_package_stats.h" #include "bundle_active_event.h" @@ -135,6 +137,7 @@ public: private: bool GetBundleActiveProxy(); sptr bundleActiveProxy_; + std::mutex mutex_; }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index efaf269..c29ff3b 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -30,6 +30,10 @@ BundleActiveClient& BundleActiveClient::GetInstance() bool BundleActiveClient::GetBundleActiveProxy() { + if (bundleActiveProxy_ != nullptr) { + return true; + } + std::lock_guard lock(mutex_); sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (!samgr) { BUNDLE_ACTIVE_LOGE("Failed to get SystemAbilityManager."); @@ -44,7 +48,7 @@ bool BundleActiveClient::GetBundleActiveProxy() bundleActiveProxy_ = iface_cast(object); if (!bundleActiveProxy_) { - BUNDLE_ACTIVE_LOGE("Failed to get BundleActiveClient."); + BUNDLE_ACTIVE_LOGE("Failed to get BundleActiveProxy."); return false; } return true; -- Gitee From fd3c500d0c4e4469593df833b02dc0b6d210313b Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 7 Jun 2022 18:40:30 +0800 Subject: [PATCH 44/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E5=88=86=E7=BB=84?= =?UTF-8?q?=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- README.md | 22 +++++++++---------- README_zh.md | 19 ++++++---------- services/common/src/bundle_active_core.cpp | 11 +++++++++- services/common/src/bundle_active_service.cpp | 14 ++++++++++-- 4 files changed, 39 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 8a66d30..edb104b 100644 --- a/README.md +++ b/README.md @@ -60,8 +60,6 @@ Taking app usage interface as an example, the main exposed interfaces are as fol

接口名

接口描述

+

接口描述

queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void

+

queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void

+

通过指定起始和结束时间查询所有应用的事件集合(callback形式)。

+

queryBundleActiveStates(begin: number, end: number): Promise<Array<BundleActiveState>>

+

通过指定起始和结束时间查询所有应用的事件集合(Promise形式)。

+

queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback<BundleActiveInfoResponse>): void

+

通过指定起始和结束时间查询应用使用时长统计信息(callback形式)。

+

queryBundleStateInfos(begin: number, end: number): Promise<BundleActiveInfoResponse>

+

通过指定起始和结束时间查询应用使用时长统计信息(Promise形式)。

+

queryCurrentBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void

+

通过指定起始和结束时间查询当前应用的事件集合(callback形式)。

+

queryCurrentBundleActiveStates(begin: number, end: number): Promise<Array<BundleActiveState>>

+

通过指定起始和结束时间查询当前应用的事件集合(Promise形式)。

+

queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback<Array<BundleStateInfo>>): void

+

通过指定时间段间隔(天、周、月、年)查询应用使用时长统计信息(callback形式)。

+

queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number): Promise<Array<BundleStateInfo>>

+

通过指定时间段间隔(天、周、月、年)查询应用使用时长统计信息(Promise形式)。

+

queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void

+

查询(返回)当前调用者应用的使用优先级群组(callback形式)。

+

queryAppUsagePriorityGroup(): Promise<number>

+

查询(返回)当前调用者应用的使用优先级群组(Promise形式)。

+

isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void

+

判断指定Bundle Name的应用当前是否是空闲状态(callback形式)。

+

isIdleState(bundleName: string): Promise<boolean>

+

判断指定Bundle Name的应用当前是否是空闲状态(Promise形式)。

+

queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void

+

根据起止时间查询系统事件(休眠、唤醒、解锁、锁屏)统计信息(callback形式)。

+

queryBundleActiveEventStates(begin: number, end: number): Promise<Array<BundleActiveEventState>>

+

根据起止时间查询系统事件(休眠、唤醒、解锁、锁屏)统计信息(Promise形式)。

+

queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void

+

根据起止时间查询应用通知次数(callback形式)。

+

queryAppNotificationNumber(begin: number, end: number): Promise<Array<BundleActiveEventState>>

+

根据起止时间查询应用通知次数(Promise形式)。

+

getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback<Array<BundleActiveModuleInfo>>): void

+

查询FA使用记录。返回数量最大不超过maxNum设置的值,FA使用记录由近及远排序,maxNum最大为1000,若不填写maxNum参数,则maxNum默认为1000(callback形式)。

+

getRecentlyUsedModules(maxNum?: number): Promise<Array<BundleActiveModuleInfo>>

+

查询FA使用记录。返回数量最大不超过maxNum设置的值,FA使用记录由近及远排序,maxNum最大为1000,若不填写maxNum参数,则maxNum默认为1000(Promise形式)。

+

queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback<number>): void

+

使用可选参数查询当前调用者应用的使用优先级群组(callback形式)。

+

queryAppUsagePriorityGroup(bundleName? : string): Promise<number>

+

使用可选参数查询当前调用者应用的使用优先级群组(Promise形式)。

+

setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback<boolean>): void

+

将指定应用的分组设置为参数提供的分组(callback形式)。

+

setBundleGroup(bundleName: string, newGroup: GroupType): Promise<boolean>

+

将指定应用的分组设置为参数提供的分组(Promise形式)。

+

registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>, callback: AsyncCallback<boolean>): void

+

给应用分组变化注册回调(callback形式)。

+

registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>): Promise<boolean>

+

给应用分组变化注册回调(Promise形式)。

+

unRegisterGroupCallBack(callback: AsyncCallback<boolean>): void

+

将已注册过的应用分组回调解除注册(callback形式)。

+

unRegisterGroupCallBack(): Promise<boolean>

+

将已注册过的应用分组回调解除注册(Promise形式)。

通过指定起始和结束时间查询所有应用的事件集合。

-

queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback<BundleActiveInfoResponse>): void

-

通过指定起始和结束时间查询应用使用时长统计信息。

-

queryCurrentBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void

-

通过指定起始和结束时间查询当前应用的事件集合。

-

queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback<Array<BundleStateInfo>>): void

-

通过指定时间段间隔(天、周、月、年)查询应用使用时长统计信息。

-

queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void

-

查询(返回)当前调用者应用的使用优先级群组。

-

isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void

-

判断指定Bundle Name的应用当前是否是空闲状态。

Queries application usage duration statistics by time interval(callback).

queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number): Promise<Array<BundleStateInfo>>

Queries application usage duration statistics by time interval(Promise).

-

queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void

-

Queries (returns) the priority group used by the current caller application(callback).

queryAppUsagePriorityGroup(): Promise<Array<number>

Queries (returns) the priority group used by the current caller application(Promise).

isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void

@@ -81,9 +79,9 @@ Taking app usage interface as an example, the main exposed interfaces are as fol

getRecentlyUsedModules(maxNum?: number): Promise<Array<BundleActiveModuleInfo>>

Query FA usage records. The maximum returned quantity does not exceed the value set by maxnum. FA usage records are sorted from near to far. The maximum maxnum is 1000. If the maxnum parameter is not filled in, the default maxnum is 1000(Promise).

queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback<number>): void

-

Use the optional parameters to query the usage priority group of the current caller application(callback).

+

Query the current application or the grouping of the application corresponding to the specified bundlename.

queryAppUsagePriorityGroup(bundleName? : string): Promise<number>

-

Use the optional parameters to query the usage priority group of the current caller application(Promise).

+

Query the current application or the grouping of the application corresponding to the specified bundlename.

setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback<boolean>): void

Set the group of the specified application as the group provided by the parameter(callback).

setBundleGroup(bundleName: string, newGroup: GroupType): Promise<boolean>

@@ -101,6 +99,7 @@ Taking app usage interface as an example, the main exposed interfaces are as fol
+ ### Usage Guidelines There are many interfaces for device usage statistics. Take app usage interface as an example to introduce the interface logic. @@ -114,14 +113,13 @@ There are many interfaces for device usage statistics. Take app usage interface >2. Query the usage duration of the application according to the start and end time; >3. Query the event collection of the current application according to the start and end time; >4. Query the usage duration of the application according to the type of interval (day, week, month, year) and the start and end time; ->5. Query the priority group of the caller application; ->6. Judge whether the specified application is currently idle; ->7. Query the statistical information of system events (sleep, wake-up, unlock and screen lock) according to the start and end time; ->8. Query the application notification times according to the start and end time; ->9. Query FA usage records. The maximum returned quantity does not exceed the value set by maxnum. FA usage records are sorted from near to far. The maximum maxnum is 1000. If the maxnum parameter is not filled in, the default maxnum is 1000; ->10. Use the optional parameters to query the usage priority group of the current caller application; ->11. Set the group of the specified application as the group provided by the parameter; ->12. Register callback for application group change; +>5. Judge whether the specified application is currently idle; +>6. Query the statistical information of system events (sleep, wake-up, unlock and screen lock) according to the start and end time; +>7. Query the application notification times according to the start and end time; +>8. Query FA usage records. The maximum returned quantity does not exceed the value set by maxnum. FA usage records are sorted from near to far. The maximum maxnum is 1000. If the maxnum parameter is not filled in, the default maxnum is 1000; +>9. Query the current application or the grouping of the application corresponding to the specified bundlename; +>10. Set the group of the specified application as the group provided by the parameter; +>11. Register callback for application group change; >13. Unregister the registered application group callback; ## Repositories Involved diff --git a/README_zh.md b/README_zh.md index 3e044dc..dd85e86 100644 --- a/README_zh.md +++ b/README_zh.md @@ -58,10 +58,6 @@

通过指定时间段间隔(天、周、月、年)查询应用使用时长统计信息(callback形式)。

queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number): Promise<Array<BundleStateInfo>>

通过指定时间段间隔(天、周、月、年)查询应用使用时长统计信息(Promise形式)。

-

queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void

-

查询(返回)当前调用者应用的使用优先级群组(callback形式)。

-

queryAppUsagePriorityGroup(): Promise<number>

-

查询(返回)当前调用者应用的使用优先级群组(Promise形式)。

isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void

判断指定Bundle Name的应用当前是否是空闲状态(callback形式)。

isIdleState(bundleName: string): Promise<boolean>

@@ -113,14 +109,13 @@ >2. 根据起止时间查询应用的使用时长; >3. 根据起止时间查询当前应用的事件集合; >4. 根据interval(日、周、月、年)类型和起止时间查询应用的使用时长; ->5. 查询调用者应用的优先级群组; ->6. 判断指定应用当前是否是空闲状态; ->7. 根据起止时间查询系统事件(休眠、唤醒、解锁、锁屏)统计信息; ->8. 根据起止时间查询应用通知次数; ->9. 查询FA使用记录。返回数量最大不超过maxNum设置的值,FA使用记录由近及远排序,maxNum最大为1000,若不填写maxNum参数,则maxNum默认为1000; ->10. 使用可选参数查询当前调用者应用的使用优先级群组; ->11. 将指定应用的分组设置为参数提供的分组; ->12. 给应用分组变化注册回调; +>5. 判断指定应用当前是否是空闲状态; +>6. 根据起止时间查询系统事件(休眠、唤醒、解锁、锁屏)统计信息; +>7. 根据起止时间查询应用通知次数; +>8. 查询FA使用记录。返回数量最大不超过maxNum设置的值,FA使用记录由近及远排序,maxNum最大为1000,若不填写maxNum参数,则maxNum默认为1000; +>9. 查询当前应用或指定bundlename对应的应用的分组; +>10. 将指定应用的分组设置为参数提供的分组; +>11. 给应用分组变化注册回调; >13. 将已注册过的应用分组回调解除注册; ## 相关仓 diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index b6b5dad..3ab6237 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -702,13 +702,22 @@ int64_t BundleActiveCore::GetSystemTimeMs() void BundleActiveCore::OnBundleGroupChanged(const BundleActiveGroupCallbackInfo& callbackInfo) { std::lock_guard lock(callbackMutex_); + AccessToken::HapTokenInfo tokenInfo = AccessToken::HapTokenInfo(); for (const auto &item : groupChangeObservers_) { auto observer = item.second; if (observer) { BUNDLE_ACTIVE_LOGI( "RegisterGroupCallBack will OnBundleGroupChanged!,oldGroup is %{public}d, newGroup is %{public}d", callbackInfo.GetOldGroup(), callbackInfo.GetNewGroup()); - observer->OnBundleGroupChanged(callbackInfo); + if (AccessToken::AccessTokenKit::GetTokenType(item.first) == AccessToken::ATokenTypeEnum::TOKEN_NATIVE) { + observer->OnBundleGroupChanged(callbackInfo); + } else if (AccessToken::AccessTokenKit::GetTokenType(item.first) == + AccessToken::ATokenTypeEnum::TOKEN_HAP) { + AccessToken::AccessTokenKit::GetHapTokenInfo(item.first, tokenInfo); + if (tokenInfo.userID == callbackInfo.GetUserId()) { + observer->OnBundleGroupChanged(callbackInfo); + } + } } } } diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index fd6e68a..fbee0e8 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -329,9 +329,19 @@ std::vector BundleActiveService::QueryEvents(const int64_t be int32_t BundleActiveService::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) { - bool result = -1; - // get uid + int32_t result = -1; + int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); + if (!GetBundleMgrProxy()) { + BUNDLE_ACTIVE_LOGE("get bundle manager proxy failed!"); + return result; + } + std::string g_bundleName = ""; + sptrBundleMgr_->GetBundleNameForUid(callingUid, g_bundleName); + if (g_bundleName == bundleName) { + BUNDLE_ACTIVE_LOGI("SetBundleGroup can not set its bundleName"); + return -1; + } AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); if (userId == -1) { OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); -- Gitee From c5ae8abfc50f6e798dbd447dbaa5806d972ad456 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 7 Jun 2022 20:50:43 +0800 Subject: [PATCH 45/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E5=88=86=E7=BB=84?= =?UTF-8?q?=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- services/common/src/bundle_active_service.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index fbee0e8..874148e 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -336,9 +336,9 @@ int32_t BundleActiveService::SetBundleGroup(const std::string& bundleName, int32 BUNDLE_ACTIVE_LOGE("get bundle manager proxy failed!"); return result; } - std::string g_bundleName = ""; - sptrBundleMgr_->GetBundleNameForUid(callingUid, g_bundleName); - if (g_bundleName == bundleName) { + std::string localBundleName = ""; + sptrBundleMgr_->GetBundleNameForUid(callingUid, localBundleName); + if (localBundleName == bundleName) { BUNDLE_ACTIVE_LOGI("SetBundleGroup can not set its bundleName"); return -1; } @@ -441,9 +441,9 @@ int32_t BundleActiveService::QueryPackageGroup(std::string& bundleName, int32_t BUNDLE_ACTIVE_LOGE("get bundle manager proxy failed!"); return result; } - std::string g_bundleName = ""; - sptrBundleMgr_->GetBundleNameForUid(callingUid, g_bundleName); - bundleName = g_bundleName; + std::string localBundleName = ""; + sptrBundleMgr_->GetBundleNameForUid(callingUid, localBundleName); + bundleName = localBundleName; result = bundleActiveCore_->QueryPackageGroup(bundleName, userId); } else { AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); -- Gitee From f149095e330b8f5d378d840d4578bf2a6132c12b Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 7 Jun 2022 21:20:12 +0800 Subject: [PATCH 46/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E5=88=86=E7=BB=84?= =?UTF-8?q?=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- README.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index edb104b..59fc520 100644 --- a/README.md +++ b/README.md @@ -60,8 +60,6 @@ Taking app usage interface as an example, the main exposed interfaces are as fol

Queries application usage duration statistics by time interval(callback).

queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number): Promise<Array<BundleStateInfo>>

Queries application usage duration statistics by time interval(Promise).

-

queryAppUsagePriorityGroup(): Promise<Array<number>

-

Queries (returns) the priority group used by the current caller application(Promise).

isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void

Judges whether the application of the specified bundle name is currently idle(callback).

isIdleState(bundleName: string): Promise<boolean>

@@ -79,9 +77,9 @@ Taking app usage interface as an example, the main exposed interfaces are as fol

getRecentlyUsedModules(maxNum?: number): Promise<Array<BundleActiveModuleInfo>>

Query FA usage records. The maximum returned quantity does not exceed the value set by maxnum. FA usage records are sorted from near to far. The maximum maxnum is 1000. If the maxnum parameter is not filled in, the default maxnum is 1000(Promise).

queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback<number>): void

-

Query the current application or the grouping of the application corresponding to the specified bundlename.

+

Query the group of the current application or the application of specified bundlename.

queryAppUsagePriorityGroup(bundleName? : string): Promise<number>

-

Query the current application or the grouping of the application corresponding to the specified bundlename.

+

Query the group of the current application or the application of specified bundlename.

setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback<boolean>): void

Set the group of the specified application as the group provided by the parameter(callback).

setBundleGroup(bundleName: string, newGroup: GroupType): Promise<boolean>

@@ -117,7 +115,7 @@ There are many interfaces for device usage statistics. Take app usage interface >6. Query the statistical information of system events (sleep, wake-up, unlock and screen lock) according to the start and end time; >7. Query the application notification times according to the start and end time; >8. Query FA usage records. The maximum returned quantity does not exceed the value set by maxnum. FA usage records are sorted from near to far. The maximum maxnum is 1000. If the maxnum parameter is not filled in, the default maxnum is 1000; ->9. Query the current application or the grouping of the application corresponding to the specified bundlename; +>9. Query the group of the current application or the application of specified bundlename; >10. Set the group of the specified application as the group provided by the parameter; >11. Register callback for application group change; >13. Unregister the registered application group callback; -- Gitee From ad62eb47648b46b54bd1eb6143a9a80059bab8e1 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Wed, 8 Jun 2022 09:41:54 +0800 Subject: [PATCH 47/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E5=88=86=E7=BB=84?= =?UTF-8?q?=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- services/common/src/bundle_active_service.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 874148e..4375637 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -536,10 +536,10 @@ bool BundleActiveService::CheckBundleIsSystemAppAndHasPermission(const int32_t u int32_t bundleHasPermission = AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, NEEDED_PERMISSION); if (bundleHasPermission != 0) { errCode = bundleHasPermission; - BUNDLE_ACTIVE_LOGE("UnRegisterGroupCallBack %{public}s hasn't permission", bundleName.c_str()); + BUNDLE_ACTIVE_LOGE("%{public}s hasn't permission", bundleName.c_str()); return false; } else { - BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack %{public}s has permission %{public}d", + BUNDLE_ACTIVE_LOGI("%{public}s has permission %{public}d", bundleName.c_str(), bundleHasPermission); return true; } -- Gitee From bbc6b6e9e02d7f2549c24dbd477bd81803d1ab9a Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Wed, 8 Jun 2022 15:43:18 +0800 Subject: [PATCH 48/83] =?UTF-8?q?d.ts=E6=96=87=E4=BB=B6=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts index 265e869..7f073cb 100644 --- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts +++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts @@ -226,8 +226,8 @@ declare namespace bundleState { stateType?: number; } /** - * @since 7 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + * @since 9 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup */ interface BundleActiveGroupCallbackInfo { /* @@ -433,7 +433,7 @@ declare namespace bundleState { * set bundle group by bundleName and number. * * @since 9 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup * @return Returns the result of setBundleGroup, true of false. */ function setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback): void; @@ -443,7 +443,7 @@ declare namespace bundleState { * register callback to service. * * @since 9 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup * @return Returns BundleActiveGroupCallbackInfo when the group of bundle changed. the result of AsyncCallback is true or false. */ function registerGroupCallBack(callback: Callback, callback: AsyncCallback): void; @@ -453,7 +453,7 @@ declare namespace bundleState { * unRegister callback from service. * * @since 9 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup * @return Returns the result of unRegisterGroupCallBack, true of false. */ function unRegisterGroupCallBack(callback: AsyncCallback): void; -- Gitee From f63c2b4cc9f66ecefc03d06effb26f544554d760 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Wed, 8 Jun 2022 15:52:50 +0800 Subject: [PATCH 49/83] =?UTF-8?q?d.ts=E6=96=87=E4=BB=B6=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts index 7f073cb..889065a 100644 --- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts +++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts @@ -182,7 +182,7 @@ declare namespace bundleState { /** * the bundle name or system event name. */ - name?: string; + name: string; /** * the event id. -- Gitee From d1e55e762eb7301c1bf636a5458e0eaf48e70f15 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Wed, 8 Jun 2022 16:14:48 +0800 Subject: [PATCH 50/83] =?UTF-8?q?d.ts=E6=96=87=E4=BB=B6=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../bundlestats/js/@ohos.bundleState.d.ts | 38 ++++++++++++------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts index 889065a..8c0eeff 100644 --- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts +++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts @@ -233,23 +233,23 @@ declare namespace bundleState { /* * the usage old group of the application */ - appUsageOldGroup?: number; + appUsageOldGroup: number; /* * the usage new group of the application */ - appUsageNewGroup?: number; + appUsageNewGroup: number; /* - * the use id + * the use id */ - userId?: number; + userId: number; /* - * the change reason + * the change reason */ - changeReason?: number; + changeReason: number; /* - * the bundle name + * the bundle name */ - bundleName?: string; + bundleName: string; } /** @@ -366,14 +366,14 @@ declare namespace bundleState { function queryCurrentBundleActiveStates(begin: number, end: number): Promise>; /** - * Queries module usage records. + * Queries recently module usage records. * * @since 9 * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App * @permission ohos.permission.BUNDLE_ACTIVE_INFO * @systemapi Hide this for inner system use. * @param maxNum Indicates max record number in result, max value is 1000, default value is 1000. - * @return Returns the {@link BundleActiveModuleInfo} object Array containing the state data of the current module. + * @return Returns the {@link BundleActiveModuleInfo} object Array containing the usage data of the modules. */ function getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback>): void; function getRecentlyUsedModules(maxNum?: number): Promise>; @@ -386,6 +386,9 @@ declare namespace bundleState { * * @since 9 * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + * @permission ohos.permission.BUNDLE_ACTIVE_INFO + * @systemapi Hide this for inner system use. + * @param bundleName, name of the application. * @return Returns the usage priority group of the calling application. */ function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback): void; @@ -395,7 +398,7 @@ declare namespace bundleState { * Declares group type. * * @since 9 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup */ export enum GroupType { /** @@ -422,7 +425,7 @@ declare namespace bundleState { * Indicates the limit group. */ ACTIVE_GROUP_LIMIT = 50, - + /** * Indicates the never group. */ @@ -434,6 +437,10 @@ declare namespace bundleState { * * @since 9 * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + * @permission ohos.permission.BUNDLE_ACTIVE_INFO + * @systemapi Hide this for inner system use. + * @param bundleName, name of the application. + * @param newGroup,the group of the application whose name is bundleName. * @return Returns the result of setBundleGroup, true of false. */ function setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback): void; @@ -444,16 +451,21 @@ declare namespace bundleState { * * @since 9 * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + * @permission ohos.permission.BUNDLE_ACTIVE_INFO + * @systemapi Hide this for inner system use. + * @param Callback, callback when application group change,return the BundleActiveGroupCallbackInfo. * @return Returns BundleActiveGroupCallbackInfo when the group of bundle changed. the result of AsyncCallback is true or false. */ function registerGroupCallBack(callback: Callback, callback: AsyncCallback): void; function registerGroupCallBack(callback: Callback): Promise; - + /** * unRegister callback from service. * * @since 9 * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + * @permission ohos.permission.BUNDLE_ACTIVE_INFO + * @systemapi Hide this for inner system use. * @return Returns the result of unRegisterGroupCallBack, true of false. */ function unRegisterGroupCallBack(callback: AsyncCallback): void; -- Gitee From a971c9ba06f937a1a2d75106ae21adff457965d7 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Wed, 8 Jun 2022 16:20:20 +0800 Subject: [PATCH 51/83] =?UTF-8?q?d.ts=E6=96=87=E4=BB=B6=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../bundlestats/js/@ohos.bundleState.d.ts | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts index 8c0eeff..f60c425 100644 --- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts +++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts @@ -231,25 +231,25 @@ declare namespace bundleState { */ interface BundleActiveGroupCallbackInfo { /* - * the usage old group of the application - */ - appUsageOldGroup: number; + * the usage old group of the application + */ + appUsageOldGroup: number; + /* + * the usage new group of the application + */ + appUsageNewGroup: number; + /* + * the use id + */ + userId: number; /* - * the usage new group of the application - */ - appUsageNewGroup: number; - /* - * the use id - */ - userId: number; - /* - * the change reason - */ - changeReason: number; - /* - * the bundle name - */ - bundleName: string; + * the change reason + */ + changeReason: number; + /* + * the bundle name + */ + bundleName: string; } /** -- Gitee From eb58855e7853d47421f451b5f94cc31413cbddc5 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Wed, 8 Jun 2022 16:52:32 +0800 Subject: [PATCH 52/83] =?UTF-8?q?d.ts=E6=96=87=E4=BB=B6=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../kits/bundlestats/js/@ohos.bundleState.d.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts index f60c425..0518178 100644 --- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts +++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts @@ -265,6 +265,19 @@ declare namespace bundleState { function isIdleState(bundleName: string, callback: AsyncCallback): void; function isIdleState(bundleName: string): Promise; + /** + * Queries the usage priority group of the calling application. + * + *

The priority defined in a priority group restricts the resource usage of an application, + * for example, restricting the running of background tasks.

+ * + * @since 7 + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + * @return Returns the usage priority group of the calling application. + */ + function queryAppUsagePriorityGroup(callback: AsyncCallback): void; + function queryAppUsagePriorityGroup(): Promise; + /** * @since 7 * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App -- Gitee From 762151f3741c0978e2e820b49d4f4dcc30128842 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Thu, 9 Jun 2022 09:38:37 +0800 Subject: [PATCH 53/83] =?UTF-8?q?=E6=B3=A8=E5=86=8Cdelete=E5=AF=B9?= =?UTF-8?q?=E8=B1=A1=E5=87=BA=E7=8E=B0cppcrash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- frameworks/src/bundle_active_group_observer.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index 8de846d..208e3d8 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -234,10 +234,6 @@ napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) ParseRegisterGroupCallBackParameters(env, info, params, registerObserver); if (params.errorCode != ERR_OK || !registerObserver) { - if (registerObserver) { - delete registerObserver; - registerObserver = nullptr; - } return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } napi_value promise = nullptr; -- Gitee From fdc2fda08d26a02c83b9225c732516c196e6a06a Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Thu, 9 Jun 2022 12:41:54 +0800 Subject: [PATCH 54/83] =?UTF-8?q?=E6=B3=A8=E5=86=8Cdelete=E5=AF=B9?= =?UTF-8?q?=E8=B1=A1=E5=87=BA=E7=8E=B0cppcrash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../src/bundle_active_group_observer.cpp | 24 +++++++++---------- .../innerkits/src/bundle_active_client.cpp | 8 +++++-- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index 208e3d8..e30f620 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -181,25 +181,23 @@ void BundleActiveGroupObserver::OnBundleGroupChanged(const BundleActiveGroupCall } } -napi_value GetBundleGroupChangeCallback( - const napi_env &env, const napi_value &value, BundleActiveGroupObserverInfo &bundleActiveGroupObserverInfo) +napi_value GetBundleGroupChangeCallback(const napi_env &env, const napi_value &value) { napi_ref result = nullptr; - bundleActiveGroupObserverInfo.callback = new (std::nothrow) BundleActiveGroupObserver(); - if (!bundleActiveGroupObserverInfo.callback) { + registerObserver = new (std::nothrow) BundleActiveGroupObserver(); + if (!registerObserver) { BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack callback is null"); return BundleStateCommon::NapiGetNull(env); } - napi_create_reference(env, value, 1, &result); - bundleActiveGroupObserverInfo.callback->SetCallbackInfo(env, result); + registerObserver->SetCallbackInfo(env, result); return BundleStateCommon::NapiGetNull(env); } napi_value ParseRegisterGroupCallBackParameters(const napi_env &env, const napi_callback_info &info, - RegisterCallbackInfo ¶ms, sptr &observer) + RegisterCallbackInfo ¶ms) { size_t argc = REGISTER_GROUP_CALLBACK_PARAMS; napi_value argv[REGISTER_GROUP_CALLBACK_PARAMS] = {nullptr}; @@ -210,12 +208,12 @@ napi_value ParseRegisterGroupCallBackParameters(const napi_env &env, const napi_ // arg[0] : callback napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - BundleActiveGroupObserverInfo bundleActiveGroupObserverInfo; - if (valuetype != napi_function || !GetBundleGroupChangeCallback(env, argv[0], bundleActiveGroupObserverInfo)) { + if (registerObserver) { + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack repeat!"); + params.errorCode = ERR_REPEAT_OPERATION; + } else if (valuetype != napi_function || !GetBundleGroupChangeCallback(env, argv[0])) { BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack bundleActiveGroupObserverInfo parse failed"); params.errorCode = ERR_OBSERVER_CALLBACK_IS_INVALID; - } else { - observer = bundleActiveGroupObserverInfo.callback; } // argv[1]: asyncCallback @@ -231,9 +229,9 @@ napi_value ParseRegisterGroupCallBackParameters(const napi_env &env, const napi_ napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) { RegisterCallbackInfo params; - ParseRegisterGroupCallBackParameters(env, info, params, registerObserver); + ParseRegisterGroupCallBackParameters(env, info, params); - if (params.errorCode != ERR_OK || !registerObserver) { + if (params.errorCode != ERR_OK) { return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } napi_value promise = nullptr; diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 763f4fe..9153983 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -143,7 +143,12 @@ int32_t BundleActiveClient::RegisterGroupCallBack(const sptrRegisterGroupCallBack(observer); + int32_t result = bundleActiveProxy_->RegisterGroupCallBack(observer); + if (/* condition */) { + /* code */ + } + + return result; } int32_t BundleActiveClient::UnregisterGroupCallBack(const sptr &observer) @@ -219,7 +224,6 @@ int32_t BundleActiveClient::ShellDump(const std::vector &dumpOption } } } - return ret; } } // namespace DeviceUsageStats -- Gitee From 81e19b4140b71c750d6c9511bf364b114650c256 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Thu, 9 Jun 2022 12:44:24 +0800 Subject: [PATCH 55/83] =?UTF-8?q?=E6=B3=A8=E5=86=8Cdelete=E5=AF=B9?= =?UTF-8?q?=E8=B1=A1=E5=87=BA=E7=8E=B0cppcrash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- interfaces/innerkits/src/bundle_active_client.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 9153983..58478d4 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -144,10 +144,6 @@ int32_t BundleActiveClient::RegisterGroupCallBack(const sptrRegisterGroupCallBack(observer); - if (/* condition */) { - /* code */ - } - return result; } -- Gitee From f095f6d6f4da13323fe9067cfe589d70785e966e Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Fri, 10 Jun 2022 16:03:12 +0800 Subject: [PATCH 56/83] =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E4=BB=A5=E5=8F=8Atdd=E4=BF=AE=E6=94=B9=E5=92=8Creadme=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- README.md | 6 +++ README_zh.md | 6 +++ .../src/bundle_active_group_observer.cpp | 46 ++++++++++--------- frameworks/src/bundle_state_query.cpp | 3 +- .../bundlestats/js/@ohos.bundleState.d.ts | 13 +++--- 5 files changed, 45 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 59fc520..1e6eb13 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,10 @@ Taking app usage interface as an example, the main exposed interfaces are as fol

Queries application usage duration statistics by time interval(callback).

queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number): Promise<Array<BundleStateInfo>>

Queries application usage duration statistics by time interval(Promise).

+

queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void

+

Query the priority group of the application.

+

queryAppUsagePriorityGroup(): Promise<number>

+

Query the priority group of the application.

isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void

Judges whether the application of the specified bundle name is currently idle(callback).

isIdleState(bundleName: string): Promise<boolean>

@@ -98,6 +102,7 @@ Taking app usage interface as an example, the main exposed interfaces are as fol + ### Usage Guidelines There are many interfaces for device usage statistics. Take app usage interface as an example to introduce the interface logic. @@ -111,6 +116,7 @@ There are many interfaces for device usage statistics. Take app usage interface >2. Query the usage duration of the application according to the start and end time; >3. Query the event collection of the current application according to the start and end time; >4. Query the usage duration of the application according to the type of interval (day, week, month, year) and the start and end time; +>4. Query the priority group of the application; >5. Judge whether the specified application is currently idle; >6. Query the statistical information of system events (sleep, wake-up, unlock and screen lock) according to the start and end time; >7. Query the application notification times according to the start and end time; diff --git a/README_zh.md b/README_zh.md index dd85e86..e94f60a 100644 --- a/README_zh.md +++ b/README_zh.md @@ -58,6 +58,10 @@

通过指定时间段间隔(天、周、月、年)查询应用使用时长统计信息(callback形式)。

queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number): Promise<Array<BundleStateInfo>>

通过指定时间段间隔(天、周、月、年)查询应用使用时长统计信息(Promise形式)。

+

queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void

+

查询当前应用的优先级分组(callback形式)。

+

queryAppUsagePriorityGroup(): Promise<number>

+

查询当前应用的优先级分组(Promise形式)。

isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void

判断指定Bundle Name的应用当前是否是空闲状态(callback形式)。

isIdleState(bundleName: string): Promise<boolean>

@@ -96,6 +100,7 @@ + ### 使用说明 设备使用信息统计接口众多,以应用使用详情(app usage)接口为例,介绍接口逻辑。 @@ -109,6 +114,7 @@ >2. 根据起止时间查询应用的使用时长; >3. 根据起止时间查询当前应用的事件集合; >4. 根据interval(日、周、月、年)类型和起止时间查询应用的使用时长; +>4. 查询当前应用的优先级分组; >5. 判断指定应用当前是否是空闲状态; >6. 根据起止时间查询系统事件(休眠、唤醒、解锁、锁屏)统计信息; >7. 根据起止时间查询应用通知次数; diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index e30f620..1a15740 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -48,6 +48,27 @@ void BundleActiveGroupObserver::SetCallbackInfo(const napi_env &env, const napi_ bundleGroupCallbackInfo_.ref = ref; } +template +napi_value AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) +{ + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + asyncCallbackInfo = new (std::nothrow) ASYNCT(env); + if (!asyncCallbackInfo) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) + != EOK) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + return BundleStateCommon::NapiGetNull(env); +} + napi_value SetBundleGroupChangedData(const CallbackReceiveDataWorker *commonEventDataWorkerData, napi_value &result) { BUNDLE_ACTIVE_LOGI("enter"); @@ -269,8 +290,7 @@ napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) AsyncRegisterCallbackInfo *asyncCallbackInfo = (AsyncRegisterCallbackInfo *)data; if (asyncCallbackInfo) { napi_value result = nullptr; - asyncCallbackInfo->state = (asyncCallbackInfo->errorCode == ERR_OK) ? true : false; - napi_get_boolean(env, asyncCallbackInfo->state, &result); + napi_get_null(env, &result); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, @@ -310,32 +330,17 @@ napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) { UnRegisterCallbackInfo params; ParseUnRegisterGroupCallBackParameters(env, info, params); - if (params.errorCode != ERR_OK) { - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } if (!registerObserver) { BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack observer is not exist"); params.errorCode = ERR_REGISTER_OBSERVER_IS_NULL; return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } napi_value promise = nullptr; - AsyncUnRegisterCallbackInfo *asyncCallbackInfo = - new (std::nothrow) AsyncUnRegisterCallbackInfo(env); - if (!asyncCallbackInfo) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } - if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) - != EOK) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } + AsyncUnRegisterCallbackInfo *asyncCallbackInfo = nullptr; + AsyncInit(env, params, asyncCallbackInfo); std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->observer = registerObserver; BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); - BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack will Async"); napi_value resourceName = nullptr; NAPI_CALL(env, napi_create_string_latin1(env, "UnRegisterGroupCallBack", NAPI_AUTO_LENGTH, &resourceName)); NAPI_CALL(env, napi_create_async_work(env, @@ -354,8 +359,7 @@ napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) AsyncUnRegisterCallbackInfo *asyncCallbackInfo = (AsyncUnRegisterCallbackInfo *)data; if (asyncCallbackInfo != nullptr) { napi_value result = nullptr; - asyncCallbackInfo->state = (asyncCallbackInfo->errorCode == ERR_OK) ? true : false; - napi_get_boolean(env, asyncCallbackInfo->state, &result); + napi_get_null(env, &result); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index d0f35ed..b604db1 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -865,8 +865,7 @@ napi_value SetBundleGroup(napi_env env, napi_callback_info info) AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = (AsyncCallbackInfoSetBundleGroup *)data; if (asyncCallbackInfo) { napi_value result = nullptr; - asyncCallbackInfo->state = (asyncCallbackInfo->errorCode == ERR_OK) ? true : false; - napi_get_boolean(env, asyncCallbackInfo->state, &result); + napi_get_null(env, &result); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts index 0518178..2def292 100644 --- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts +++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts @@ -177,6 +177,7 @@ declare namespace bundleState { /** * @since 9 * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App + * @systemapi Hide this for inner system use. */ interface BundleActiveEventState { /** @@ -456,8 +457,8 @@ declare namespace bundleState { * @param newGroup,the group of the application whose name is bundleName. * @return Returns the result of setBundleGroup, true of false. */ - function setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback): void; - function setBundleGroup(bundleName: string, newGroup: GroupType): Promise; + function setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback): void; + function setBundleGroup(bundleName: string, newGroup: GroupType): Promise; /** * register callback to service. @@ -469,8 +470,8 @@ declare namespace bundleState { * @param Callback, callback when application group change,return the BundleActiveGroupCallbackInfo. * @return Returns BundleActiveGroupCallbackInfo when the group of bundle changed. the result of AsyncCallback is true or false. */ - function registerGroupCallBack(callback: Callback, callback: AsyncCallback): void; - function registerGroupCallBack(callback: Callback): Promise; + function registerGroupCallBack(callback: Callback, callback: AsyncCallback): void; + function registerGroupCallBack(callback: Callback): Promise; /** * unRegister callback from service. @@ -481,8 +482,8 @@ declare namespace bundleState { * @systemapi Hide this for inner system use. * @return Returns the result of unRegisterGroupCallBack, true of false. */ - function unRegisterGroupCallBack(callback: AsyncCallback): void; - function unRegisterGroupCallBack(): Promise; + function unRegisterGroupCallBack(callback: AsyncCallback): void; + function unRegisterGroupCallBack(): Promise; /* * Queries system event states data within a specified period identified by the start and end time. -- Gitee From d11fadb221b56912264abdd921ab3772cee8ec0a Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Fri, 10 Jun 2022 17:19:41 +0800 Subject: [PATCH 57/83] =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E4=BB=A5=E5=8F=8Atdd=E4=BF=AE=E6=94=B9=E5=92=8Creadme=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- README.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 1e6eb13..27262a6 100644 --- a/README.md +++ b/README.md @@ -84,17 +84,17 @@ Taking app usage interface as an example, the main exposed interfaces are as fol

Query the group of the current application or the application of specified bundlename.

queryAppUsagePriorityGroup(bundleName? : string): Promise<number>

Query the group of the current application or the application of specified bundlename.

-

setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback<boolean>): void

+

setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback<void>): void

Set the group of the specified application as the group provided by the parameter(callback).

-

setBundleGroup(bundleName: string, newGroup: GroupType): Promise<boolean>

+

setBundleGroup(bundleName: string, newGroup: GroupType): Promise<void>

Set the group of the specified application as the group provided by the parameter(Promise).

-

registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>, callback: AsyncCallback<boolean>): void

+

registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>, callback: AsyncCallback<void>): void

Register callback for application group change(callback).

-

registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>): Promise<boolean>

+

registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>): Promise<void>

Register callback for application group change(Promise).

-

unRegisterGroupCallBack(callback: AsyncCallback<boolean>): void

+

unRegisterGroupCallBack(callback: AsyncCallback<void>): void

Unregister the registered application group callback(callback).

-

unRegisterGroupCallBack(): Promise<boolean>

+

unRegisterGroupCallBack(): Promise<void>

Unregister the registered application group callback(Promise).

@@ -116,14 +116,14 @@ There are many interfaces for device usage statistics. Take app usage interface >2. Query the usage duration of the application according to the start and end time; >3. Query the event collection of the current application according to the start and end time; >4. Query the usage duration of the application according to the type of interval (day, week, month, year) and the start and end time; ->4. Query the priority group of the application; ->5. Judge whether the specified application is currently idle; ->6. Query the statistical information of system events (sleep, wake-up, unlock and screen lock) according to the start and end time; ->7. Query the application notification times according to the start and end time; ->8. Query FA usage records. The maximum returned quantity does not exceed the value set by maxnum. FA usage records are sorted from near to far. The maximum maxnum is 1000. If the maxnum parameter is not filled in, the default maxnum is 1000; ->9. Query the group of the current application or the application of specified bundlename; ->10. Set the group of the specified application as the group provided by the parameter; ->11. Register callback for application group change; +>5. Query the priority group of the application; +>6. Judge whether the specified application is currently idle; +>7. Query the statistical information of system events (sleep, wake-up, unlock and screen lock) according to the start and end time; +>8. Query the application notification times according to the start and end time; +>9. Query FA usage records. The maximum returned quantity does not exceed the value set by maxnum. FA usage records are sorted from near to far. The maximum maxnum is 1000. If the maxnum parameter is not filled in, the default maxnum is 1000; +>10. Query the group of the current application or the application of specified bundlename; +>11. Set the group of the specified application as the group provided by the parameter; +>12. Register callback for application group change; >13. Unregister the registered application group callback; ## Repositories Involved -- Gitee From aa8da10b3d348d2f2c86568cdfe9de309388ca72 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Fri, 10 Jun 2022 17:21:37 +0800 Subject: [PATCH 58/83] =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E4=BB=A5=E5=8F=8Atdd=E4=BF=AE=E6=94=B9=E5=92=8Creadme=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- README_zh.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/README_zh.md b/README_zh.md index e94f60a..9fabc00 100644 --- a/README_zh.md +++ b/README_zh.md @@ -82,17 +82,17 @@

使用可选参数查询当前调用者应用的使用优先级群组(callback形式)。

queryAppUsagePriorityGroup(bundleName? : string): Promise<number>

使用可选参数查询当前调用者应用的使用优先级群组(Promise形式)。

-

setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback<boolean>): void

+

setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback<void>): void

将指定应用的分组设置为参数提供的分组(callback形式)。

-

setBundleGroup(bundleName: string, newGroup: GroupType): Promise<boolean>

+

setBundleGroup(bundleName: string, newGroup: GroupType): Promise<void>

将指定应用的分组设置为参数提供的分组(Promise形式)。

-

registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>, callback: AsyncCallback<boolean>): void

+

registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>, callback: AsyncCallback<void>): void

给应用分组变化注册回调(callback形式)。

-

registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>): Promise<boolean>

+

registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>): Promise<void>

给应用分组变化注册回调(Promise形式)。

-

unRegisterGroupCallBack(callback: AsyncCallback<boolean>): void

+

unRegisterGroupCallBack(callback: AsyncCallback<void>): void

将已注册过的应用分组回调解除注册(callback形式)。

-

unRegisterGroupCallBack(): Promise<boolean>

+

unRegisterGroupCallBack(): Promise<void>

将已注册过的应用分组回调解除注册(Promise形式)。

@@ -114,14 +114,14 @@ >2. 根据起止时间查询应用的使用时长; >3. 根据起止时间查询当前应用的事件集合; >4. 根据interval(日、周、月、年)类型和起止时间查询应用的使用时长; ->4. 查询当前应用的优先级分组; ->5. 判断指定应用当前是否是空闲状态; ->6. 根据起止时间查询系统事件(休眠、唤醒、解锁、锁屏)统计信息; ->7. 根据起止时间查询应用通知次数; ->8. 查询FA使用记录。返回数量最大不超过maxNum设置的值,FA使用记录由近及远排序,maxNum最大为1000,若不填写maxNum参数,则maxNum默认为1000; ->9. 查询当前应用或指定bundlename对应的应用的分组; ->10. 将指定应用的分组设置为参数提供的分组; ->11. 给应用分组变化注册回调; +>5. 查询当前应用的优先级分组; +>6. 判断指定应用当前是否是空闲状态; +>7. 根据起止时间查询系统事件(休眠、唤醒、解锁、锁屏)统计信息; +>8. 根据起止时间查询应用通知次数; +>9. 查询FA使用记录。返回数量最大不超过maxNum设置的值,FA使用记录由近及远排序,maxNum最大为1000,若不填写maxNum参数,则maxNum默认为1000; +>10. 查询当前应用或指定bundlename对应的应用的分组; +>11. 将指定应用的分组设置为参数提供的分组; +>12. 给应用分组变化注册回调; >13. 将已注册过的应用分组回调解除注册; ## 相关仓 -- Gitee From c507823275885f1c6f70a707fb962c6acee01ab3 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Mon, 13 Jun 2022 21:44:43 +0800 Subject: [PATCH 59/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E5=88=86=E7=BB=84?= =?UTF-8?q?=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- BUILD.gn | 38 +----- bundle.json | 3 +- .../src/bundle_active_group_observer.cpp | 64 ++++----- frameworks/src/bundle_state_query.cpp | 85 ++++++------ .../innerkits/include/bundle_active_client.h | 42 ++++-- .../innerkits/src/bundle_active_client.cpp | 101 +++++++-------- .../src/bundle_active_group_callback_stub.cpp | 5 +- .../innerkits/src/bundle_active_proxy.cpp | 23 ++-- .../napi/include/bundle_state_inner_errors.h | 2 + .../common/include/bundle_active_service.h | 5 + services/common/src/bundle_active_core.cpp | 40 +++--- services/common/src/bundle_active_service.cpp | 122 ++++++++++++++++-- test/unittest/BUILD.gn | 1 + 13 files changed, 299 insertions(+), 232 deletions(-) diff --git a/BUILD.gn b/BUILD.gn index 90d85f3..40d9abc 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -41,6 +41,7 @@ ohos_shared_library("usagestatsinner") { public_configs = [ ":usagestatsinner_public_config" ] public_deps = [ ":usagestatservice" ] external_deps = [ + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", @@ -80,6 +81,7 @@ ohos_shared_library("bundlestate") { ] external_deps = [ + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "napi:ace_napi", @@ -136,6 +138,7 @@ ohos_shared_library("usagestatservice") { "services/packageusage/include", "services/packagegroup/include", "interfaces/innerkits/include", + "interfaces/kits/bundlestats/napi/include", ] external_deps = [ @@ -168,37 +171,4 @@ ohos_shared_library("usagestatservice") { part_name = "${device_usage_statistics_part_name}" subsystem_name = "resourceschedule" -} - -ohos_executable("deviceusagestats") { - include_dirs = [ - "services/common/include", - "services/packageusage/include", - "services/packagegroup/include", - "interfaces/innerkits/include", - "utils/dump/include", - ] - - sources = [ - "utils/dump/src/bundle_active_shell_command.cpp", - "utils/dump/src/main.cpp", - "utils/dump/src/shell_command.cpp", - ] - - deps = [ ":usagestatsinner" ] - - configs = [] - - external_deps = [ - "ability_base:want", - "ability_runtime:wantagent_innerkits", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", - "utils_base:utils", - ] - - install_enable = true - part_name = "${device_usage_statistics_part_name}" -} +} \ No newline at end of file diff --git a/bundle.json b/bundle.json index cccf5f4..d389347 100644 --- a/bundle.json +++ b/bundle.json @@ -51,8 +51,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:bundlestate", - "//foundation/resourceschedule/device_usage_statistics:deviceusagestats" + "//foundation/resourceschedule/device_usage_statistics:bundlestate" ], "inner_kits": [ { diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index 1a15740..5654d31 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -49,30 +49,27 @@ void BundleActiveGroupObserver::SetCallbackInfo(const napi_env &env, const napi_ } template -napi_value AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) +void AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) { if (params.errorCode != ERR_OK) { - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + return ; } asyncCallbackInfo = new (std::nothrow) ASYNCT(env); if (!asyncCallbackInfo) { params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + return ; } if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) != EOK) { params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; delete asyncCallbackInfo; asyncCallbackInfo = nullptr; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + return ; } - return BundleStateCommon::NapiGetNull(env); } napi_value SetBundleGroupChangedData(const CallbackReceiveDataWorker *commonEventDataWorkerData, napi_value &result) { - BUNDLE_ACTIVE_LOGI("enter"); - if (!commonEventDataWorkerData) { BUNDLE_ACTIVE_LOGE("commonEventDataWorkerData is null"); return nullptr; @@ -98,7 +95,7 @@ napi_value SetBundleGroupChangedData(const CallbackReceiveDataWorker *commonEven napi_create_string_utf8( commonEventDataWorkerData->env, commonEventDataWorkerData->bundleName.c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(commonEventDataWorkerData->env, result, "bundleName", value); - BUNDLE_ACTIVE_LOGI( + BUNDLE_ACTIVE_LOGD( "RegisterGroupCallBack oldGroup=%{public}d, newGroup=%{public}d, userId=%{public}d, " "changeReason=%{public}d, bundleName=%{public}s", commonEventDataWorkerData->oldGroup, commonEventDataWorkerData->newGroup, commonEventDataWorkerData->userId, @@ -109,7 +106,7 @@ napi_value SetBundleGroupChangedData(const CallbackReceiveDataWorker *commonEven void UvQueueWorkOnBundleGroupChanged(uv_work_t *work, int status) { - BUNDLE_ACTIVE_LOGI("OnBundleGroupChanged uv_work_t start"); + BUNDLE_ACTIVE_LOGD("OnBundleGroupChanged uv_work_t start"); if (!work) { return; } @@ -154,15 +151,13 @@ void UvQueueWorkOnBundleGroupChanged(uv_work_t *work, int status) */ void BundleActiveGroupObserver::OnBundleGroupChanged(const BundleActiveGroupCallbackInfo &bundleActiveGroupCallbackInfo) { - BUNDLE_ACTIVE_LOGI("OnBundleGroupChanged start"); - + BUNDLE_ACTIVE_LOGD("OnBundleGroupChanged start"); uv_loop_s *loop = nullptr; napi_get_uv_event_loop(bundleGroupCallbackInfo_.env, &loop); if (!loop) { BUNDLE_ACTIVE_LOGE("loop instance is nullptr"); return; } - uv_work_t* work = new (std::nothrow) uv_work_t; if (!work) { BUNDLE_ACTIVE_LOGE("work is null"); @@ -185,14 +180,10 @@ void BundleActiveGroupObserver::OnBundleGroupChanged(const BundleActiveGroupCall callbackReceiveDataWorker->changeReason = callBackInfo->GetChangeReason(); callbackReceiveDataWorker->userId = callBackInfo->GetUserId(); callbackReceiveDataWorker->bundleName = callBackInfo->GetBundleName(); - callbackReceiveDataWorker->env = bundleGroupCallbackInfo_.env; callbackReceiveDataWorker->ref = bundleGroupCallbackInfo_.ref; work->data = (void *)callbackReceiveDataWorker; - - BUNDLE_ACTIVE_LOGI("OnReceiveEvent this = %{public}p", this); - int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnBundleGroupChanged); if (ret != 0) { delete callbackReceiveDataWorker; @@ -218,7 +209,7 @@ napi_value GetBundleGroupChangeCallback(const napi_env &env, const napi_value &v } napi_value ParseRegisterGroupCallBackParameters(const napi_env &env, const napi_callback_info &info, - RegisterCallbackInfo ¶ms) + RegisterCallbackInfo ¶ms, AsyncRegisterCallbackInfo* &asyncCallbackInfo) { size_t argc = REGISTER_GROUP_CALLBACK_PARAMS; napi_value argv[REGISTER_GROUP_CALLBACK_PARAMS] = {nullptr}; @@ -244,34 +235,22 @@ napi_value ParseRegisterGroupCallBackParameters(const napi_env &env, const napi_ NAPI_ASSERT(env, valuetype == napi_function, "ParseStatesParameters invalid parameter type. Function expected"); napi_create_reference(env, argv[1], 1, ¶ms.callback); } + AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); } napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) { RegisterCallbackInfo params; - ParseRegisterGroupCallBackParameters(env, info, params); - + AsyncRegisterCallbackInfo *asyncCallbackInfo = nullptr; + ParseRegisterGroupCallBackParameters(env, info, params, asyncCallbackInfo); if (params.errorCode != ERR_OK) { return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; - AsyncRegisterCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncRegisterCallbackInfo(env); - if (!asyncCallbackInfo) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } - if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) - != EOK) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->observer = registerObserver; + napi_value promise = nullptr; BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); - napi_value resourceName = nullptr; NAPI_CALL(env, napi_create_string_latin1(env, "RegisterGroupCallBack", NAPI_AUTO_LENGTH, &resourceName)); NAPI_CALL(env, napi_create_async_work(env, @@ -307,7 +286,7 @@ napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info) } napi_value ParseUnRegisterGroupCallBackParameters(const napi_env &env, const napi_callback_info &info, - UnRegisterCallbackInfo ¶ms) + UnRegisterCallbackInfo ¶ms, AsyncUnRegisterCallbackInfo* &asyncCallbackInfo) { size_t argc = UN_REGISTER_GROUP_CALLBACK_PARAMS; napi_value argv[UN_REGISTER_GROUP_CALLBACK_PARAMS] = {nullptr}; @@ -323,23 +302,26 @@ napi_value ParseUnRegisterGroupCallBackParameters(const napi_env &env, const nap "Function expected."); napi_create_reference(env, argv[0], 1, ¶ms.callback); } + if (!registerObserver) { + BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack observer is not exist"); + params.errorCode = ERR_REGISTER_OBSERVER_IS_NULL; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + } + AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); } napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info) { UnRegisterCallbackInfo params; - ParseUnRegisterGroupCallBackParameters(env, info, params); - if (!registerObserver) { - BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack observer is not exist"); - params.errorCode = ERR_REGISTER_OBSERVER_IS_NULL; + AsyncUnRegisterCallbackInfo *asyncCallbackInfo = nullptr; + ParseUnRegisterGroupCallBackParameters(env, info, params, asyncCallbackInfo); + if (params.errorCode != ERR_OK) { return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; - AsyncUnRegisterCallbackInfo *asyncCallbackInfo = nullptr; - AsyncInit(env, params, asyncCallbackInfo); std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->observer = registerObserver; + napi_value promise = nullptr; BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); napi_value resourceName = nullptr; NAPI_CALL(env, napi_create_string_latin1(env, "UnRegisterGroupCallBack", NAPI_AUTO_LENGTH, &resourceName)); diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index b604db1..6f33292 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -47,6 +47,26 @@ const std::vector GROUP_TYPE {10, 20, 30, 40, 50, 60}; const uint32_t EVENT_STATES_MIN_PARAMS = 2; const uint32_t EVENT_STATES_PARAMS = 3; +template +void AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) +{ + if (params.errorCode != ERR_OK) { + return ; + } + asyncCallbackInfo = new (std::nothrow) ASYNCT(env); + if (!asyncCallbackInfo) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return ; + } + if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) + != EOK) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + return ; + } +} + napi_value ParseModuleRecordsParameters(const napi_env &env, const napi_callback_info &info, ModuleRecordParamsInfo ¶ms) { @@ -247,7 +267,7 @@ napi_value IsIdleState(napi_env env, napi_callback_info info) } napi_value ParsePriorityGroupParameters(const napi_env &env, const napi_callback_info &info, - PriorityGroupParamsInfo ¶ms) + PriorityGroupParamsInfo ¶ms, AsyncCallbackInfoPriorityGroup* &asyncCallbackInfo) { size_t argc = PRIORITY_GROUP_PARAMS; napi_value argv[PRIORITY_GROUP_PARAMS] = {nullptr}; @@ -288,33 +308,23 @@ napi_value ParsePriorityGroupParameters(const napi_env &env, const napi_callback napi_create_reference(env, argv[1], 1, ¶ms.callback); } } + AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); } napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) { PriorityGroupParamsInfo params; - ParsePriorityGroupParameters(env, info, params); + AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = nullptr; + ParsePriorityGroupParameters(env, info, params, asyncCallbackInfo); if (params.errorCode != ERR_OK) { return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; - AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = - new (std::nothrow) AsyncCallbackInfoPriorityGroup(env); - if (!asyncCallbackInfo) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } - if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) != EOK) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->bundleName = params.bundleName; - BUNDLE_ACTIVE_LOGI("QueryPackageGroup callbackPtr->bundleName: %{public}s", + BUNDLE_ACTIVE_LOGD("QueryPackageGroup callbackPtr->bundleName: %{public}s", callbackPtr->bundleName.c_str()); + napi_value promise = nullptr; BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); napi_value resourceName = nullptr; NAPI_CALL(env, napi_create_string_latin1(env, "QueryAppUsagePriorityGroup", NAPI_AUTO_LENGTH, &resourceName)); @@ -422,10 +432,10 @@ napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info) } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->beginTime = params.beginTime; - BUNDLE_ACTIVE_LOGI("QueryCurrentBundleActiveStates callbackPtr->beginTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryCurrentBundleActiveStates callbackPtr->beginTime: %{public}lld", (long long)callbackPtr->beginTime); callbackPtr->endTime = params.endTime; - BUNDLE_ACTIVE_LOGI("QueryCurrentBundleActiveStates callbackPtr->endTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryCurrentBundleActiveStates callbackPtr->endTime: %{public}lld", (long long)callbackPtr->endTime); BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); @@ -487,10 +497,10 @@ napi_value QueryBundleActiveStates(napi_env env, napi_callback_info info) } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->beginTime = params.beginTime; - BUNDLE_ACTIVE_LOGI("QueryBundleActiveStates callbackPtr->beginTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryBundleActiveStates callbackPtr->beginTime: %{public}lld", (long long)callbackPtr->beginTime); callbackPtr->endTime = params.endTime; - BUNDLE_ACTIVE_LOGI("QueryBundleActiveStates callbackPtr->endTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryBundleActiveStates callbackPtr->endTime: %{public}lld", (long long)callbackPtr->endTime); BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); @@ -613,13 +623,13 @@ napi_value QueryBundleStateInfoByInterval(napi_env env, napi_callback_info info) } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->intervalType = params.intervalType; - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval callbackPtr->intervalType: %{public}d", + BUNDLE_ACTIVE_LOGD("QueryBundleStateInfoByInterval callbackPtr->intervalType: %{public}d", callbackPtr->intervalType); callbackPtr->beginTime = params.beginTime; - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval callbackPtr->beginTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryBundleStateInfoByInterval callbackPtr->beginTime: %{public}lld", (long long)callbackPtr->beginTime); callbackPtr->endTime = params.endTime; - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval callbackPtr->endTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryBundleStateInfoByInterval callbackPtr->endTime: %{public}lld", (long long)callbackPtr->endTime); BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); napi_value resourceName = nullptr; @@ -725,10 +735,10 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->beginTime = params.beginTime; - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos callbackPtr->beginTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryBundleStateInfos callbackPtr->beginTime: %{public}lld", (long long)callbackPtr->beginTime); callbackPtr->endTime = params.endTime; - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos callbackPtr->endTime: %{public}lld", + BUNDLE_ACTIVE_LOGD("QueryBundleStateInfos callbackPtr->endTime: %{public}lld", (long long)callbackPtr->endTime); BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); napi_value resourceName = nullptr; @@ -767,9 +777,8 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) } napi_value ParseAppUsageBundleGroupInfoParameters(const napi_env &env, const napi_callback_info &info, - ParamsBundleGroupInfo ¶ms) + ParamsBundleGroupInfo ¶ms, AsyncCallbackInfoSetBundleGroup* &asyncCallbackInfo) { - BUNDLE_ACTIVE_LOGD("enter ParseAppUsageBundleGroupInfoParameters"); size_t argc = APP_USAGE_PARAMS_BUNDLE_GROUP; napi_value argv[APP_USAGE_PARAMS_BUNDLE_GROUP] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); @@ -816,36 +825,24 @@ napi_value ParseAppUsageBundleGroupInfoParameters(const napi_env &env, const nap "Function expected."); napi_create_reference(env, argv[SECOND_ARG], 1, ¶ms.callback); } + AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); } napi_value SetBundleGroup(napi_env env, napi_callback_info info) { - BUNDLE_ACTIVE_LOGI("enter SetBundleGroup"); ParamsBundleGroupInfo params; - ParseAppUsageBundleGroupInfoParameters(env, info, params); + AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = nullptr; + ParseAppUsageBundleGroupInfoParameters(env, info, params, asyncCallbackInfo); if (params.errorCode != ERR_OK) { return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; - AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = - new (std::nothrow) AsyncCallbackInfoSetBundleGroup(env); - if (!asyncCallbackInfo) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } - if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) - != EOK) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); - } std::unique_ptr callbackPtr {asyncCallbackInfo}; callbackPtr->newGroup = params.newGroup; callbackPtr->bundleName = params.bundleName; - BUNDLE_ACTIVE_LOGI("SetBundleGroup, bundleName is %{public}s, newGroup is %{public}d", + BUNDLE_ACTIVE_LOGD("SetBundleGroup, bundleName is %{public}s, newGroup is %{public}d", callbackPtr->bundleName.c_str(), callbackPtr->newGroup); + napi_value promise = nullptr; BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise); napi_value resourceName = nullptr; NAPI_CALL(env, napi_create_string_latin1(env, "SetBundleGroup", NAPI_AUTO_LENGTH, &resourceName)); diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h index c396903..d20785d 100644 --- a/interfaces/innerkits/include/bundle_active_client.h +++ b/interfaces/innerkits/include/bundle_active_client.h @@ -24,6 +24,8 @@ #include "bundle_active_event_stats.h" #include "bundle_active_package_stats.h" #include "bundle_active_module_record.h" +#include "event_handler.h" +#include "event_runner.h" namespace OHOS { namespace DeviceUsageStats { @@ -124,19 +126,41 @@ public: * return: object of BundleActiveClient. */ static BundleActiveClient& GetInstance(); - /* - * function: BundleActiveClient, default constructor. - */ - BundleActiveClient() {} - /* - * function: ~BundleActiveClient, default destructor. - */ - ~BundleActiveClient() {} +private: + class BundleActiveClientDeathRecipient : public IRemoteObject::DeathRecipient { + public: + /* + * function: BundleActiveClientDeathRecipient, default constructor. + */ + explicit BundleActiveClientDeathRecipient() = default; + /* + * function: ~BundleActiveClientDeathRecipient, default destructor. + */ + ~BundleActiveClientDeathRecipient() = default; + /* + * function: setObserver. + */ + void setObserver(const sptr &observer); + /* + * function: OnRemoteDied, PostTask when service(bundleActiveProxy_) is died. + */ + void OnRemoteDied(const wptr &object) override; + /* + * function: OnServiceDiedInner, get bundleActiveProxy_ and registerGroupCallBack again. + */ + void OnServiceDiedInner(const wptr &object); - int32_t ShellDump(const std::vector &dumpOption, std::vector &dumpInfo); + private: + sptr observer_ = nullptr; + }; private: bool GetBundleActiveProxy(); + BundleActiveClient() {} + ~BundleActiveClient() {} sptr bundleActiveProxy_; + sptr recipient_; + std::shared_ptr bundleClientRunner_ {nullptr}; + std::shared_ptr bundleClientHandler_ {nullptr}; std::mutex mutex_; }; } // namespace DeviceUsageStats diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 58478d4..6c3e625 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -18,9 +18,7 @@ namespace OHOS { namespace DeviceUsageStats { namespace { - const int32_t EVENTS_PARAM = 5; - const int32_t PACKAGE_USAGE_PARAM = 6; - const int32_t MODULE_USAGE_PARAM = 4; + const std::string BUNDLE_ACTIVE_CLIENT_NAME = "bundleActiveName"; } BundleActiveClient& BundleActiveClient::GetInstance() { @@ -51,6 +49,19 @@ bool BundleActiveClient::GetBundleActiveProxy() BUNDLE_ACTIVE_LOGE("Failed to get BundleActiveProxy."); return false; } + if (!recipient_) { + recipient_ = new (std::nothrow) BundleActiveClientDeathRecipient(); + } + bundleClientRunner_ = AppExecFwk::EventRunner::Create(BUNDLE_ACTIVE_CLIENT_NAME); + if (!bundleClientRunner_) { + BUNDLE_ACTIVE_LOGE("BundleActiveClient runner create failed!"); + return false; + } + bundleClientHandler_ = std::make_shared(bundleClientRunner_); + if (!bundleClientHandler_) { + BUNDLE_ACTIVE_LOGE("BundleActiveClient handler create failed!"); + return false; + } return true; } @@ -140,20 +151,27 @@ int32_t BundleActiveClient::QueryFormStatistics(int32_t maxNum, std::vector &observer) { if (!GetBundleActiveProxy()) { - BUNDLE_ACTIVE_LOGE("GetBackgroundTaskManagerProxy failed."); - return false; + return -1; } int32_t result = bundleActiveProxy_->RegisterGroupCallBack(observer); + //AddDeathRecipient when RegisterGroupCallBack success + if (recipient_ && result == ERR_OK) { + recipient_->setObserver(observer); + bundleActiveProxy_->AsObject()->AddDeathRecipient(recipient_); + } return result; } int32_t BundleActiveClient::UnregisterGroupCallBack(const sptr &observer) { if (!GetBundleActiveProxy()) { - BUNDLE_ACTIVE_LOGE("GetBackgroundTaskManagerProxy failed."); - return false; + return -1; } - return bundleActiveProxy_->UnregisterGroupCallBack(observer); + int32_t result = bundleActiveProxy_->UnregisterGroupCallBack(observer); + if (recipient_) { + bundleActiveProxy_->AsObject()->RemoveDeathRecipient(recipient_); + } + return result; } int32_t BundleActiveClient::QueryEventStats(int64_t beginTime, int64_t endTime, @@ -174,53 +192,26 @@ int32_t BundleActiveClient::QueryAppNotificationNumber(int64_t beginTime, int64_ return bundleActiveProxy_->QueryAppNotificationNumber(beginTime, endTime, eventStats, userId); } -int32_t BundleActiveClient::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) -{ - int32_t ret = -1; - - if (dumpOption[1] == "Events") { - std::vector eventResult; - if (static_cast(dumpOption.size()) != EVENTS_PARAM) { - return ret; - } - int64_t beginTime = std::stoll(dumpOption[2]); - int64_t endTime = std::stoll(dumpOption[3]); - int32_t userId = std::stoi(dumpOption[4]); - eventResult = this->QueryEvents(beginTime, endTime, ret, userId); - for (auto& oneEvent : eventResult) { - dumpInfo.emplace_back(oneEvent.ToString()); - } - } else if (dumpOption[1] == "PackageUsage") { - std::vector packageUsageResult; - if (static_cast(dumpOption.size()) != PACKAGE_USAGE_PARAM) { - return ret; - } - int32_t intervalType = std::stoi(dumpOption[2]); - int64_t beginTime = std::stoll(dumpOption[3]); - int64_t endTime = std::stoll(dumpOption[4]); - int32_t userId = std::stoi(dumpOption[5]); - packageUsageResult = this->QueryPackageStats(intervalType, beginTime, endTime, ret, userId); - for (auto& onePackageRecord : packageUsageResult) { - dumpInfo.emplace_back(onePackageRecord.ToString()); - } - } else if (dumpOption[1] == "ModuleUsage") { - std::vector moduleResult; - if (static_cast(dumpOption.size()) != MODULE_USAGE_PARAM) { - return ret; - } - int32_t maxNum = std::stoi(dumpOption[2]); - int32_t userId = std::stoi(dumpOption[3]); - BUNDLE_ACTIVE_LOGI("M is %{public}d, u is %{public}d", maxNum, userId); - ret = this->QueryFormStatistics(maxNum, moduleResult, userId); - for (auto& oneModuleRecord : moduleResult) { - dumpInfo.emplace_back(oneModuleRecord.ToString()); - for (uint32_t i = 0; i < oneModuleRecord.formRecords_.size(); i++) { - std::string oneFormInfo = "form " + std::to_string(static_cast(i) + 1) + ", "; - dumpInfo.emplace_back(oneFormInfo + oneModuleRecord.formRecords_[i].ToString()); - } - } - } - return ret; +void BundleActiveClient::BundleActiveClientDeathRecipient::setObserver(const sptr &observer) +{ + if (observer) { + observer_ = observer; + } +} +void BundleActiveClient::BundleActiveClientDeathRecipient::OnRemoteDied(const wptr &object) +{ + if (object == nullptr) { + BUNDLE_ACTIVE_LOGE("remote object is null."); + return; + } + BundleActiveClient::GetInstance().bundleActiveProxy_ = nullptr; + BundleActiveClient::GetInstance().bundleClientHandler_->PostTask([this, &object]() { this->OnServiceDiedInner(object); }); +} + +void BundleActiveClient::BundleActiveClientDeathRecipient::OnServiceDiedInner(const wptr &object) +{ + while (!BundleActiveClient::GetInstance().GetBundleActiveProxy()) { } + BundleActiveClient::GetInstance().RegisterGroupCallBack(observer_); } } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp index 7b8ebce..266ff17 100644 --- a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp +++ b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp @@ -23,16 +23,15 @@ int32_t BundleActiveGroupCallbackStub::OnRemoteRequest(uint32_t code, MessagePar std::u16string descriptor = BundleActiveGroupCallbackStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack OnRemoteRequest cannot get power mgr service"); + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack OnRemoteRequest cannot get power mgr service"); return -1; } - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack BundleActiveGroupCallbackStub will switch"); switch (code) { case static_cast(IBundleActiveGroupCallback::message::ON_BUNDLE_GROUP_CHANGED): { std::shared_ptr groupInfo( data.ReadParcelable()); if (!groupInfo) { - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack ReadParcelable failed"); + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack ReadParcelable failed"); return -1; } OnBundleGroupChanged(*(groupInfo.get())); diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index 1392c7d..69d4cd1 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -44,7 +44,7 @@ bool BundleActiveProxy::IsBundleIdle(const std::string& bundleName) data.WriteString(bundleName); Remote() -> SendRequest(IS_BUNDLE_IDLE, data, reply, option); int32_t result = reply.ReadInt32(); - BUNDLE_ACTIVE_LOGI("result is %{public}d", result); + BUNDLE_ACTIVE_LOGD("result is %{public}d", result); return result; } @@ -75,7 +75,7 @@ std::vector BundleActiveProxy::QueryPackageStats(const result.push_back(*tmp); } for (uint32_t i = 0; i < result.size(); i++) { - BUNDLE_ACTIVE_LOGI("QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, " + BUNDLE_ACTIVE_LOGD("QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, " "lastTimeUsed_ is %{public}lld, lastContiniousTaskUsed_ is %{public}lld, " "totalInFrontTime_ is %{public}lld, totalContiniousTaskUsedTime_ is %{public}lld", i + 1, result[i].bundleName_.c_str(), @@ -119,7 +119,6 @@ std::vector BundleActiveProxy::QueryEvents(const int64_t begi int32_t BundleActiveProxy::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) { - BUNDLE_ACTIVE_LOGI("SetBundleGroup enter bundleActiveProxy"); MessageParcel data; MessageParcel reply; MessageOption option; @@ -159,7 +158,7 @@ std::vector BundleActiveProxy::QueryCurrentPackageStat result.push_back(*tmp); } for (uint32_t i = 0; i < result.size(); i++) { - BUNDLE_ACTIVE_LOGI("QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, " + BUNDLE_ACTIVE_LOGD("QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, " "lastTimeUsed_ is %{public}lld, lastContiniousTaskUsed_ is %{public}lld, " "totalInFrontTime_ is %{public}lld, totalContiniousTaskUsedTime_ is %{public}lld", i + 1, result[i].bundleName_.c_str(), @@ -191,7 +190,7 @@ std::vector BundleActiveProxy::QueryCurrentEvents(const int64 result.push_back(*tmp); } for (uint32_t i = 0; i < result.size(); i++) { - BUNDLE_ACTIVE_LOGI("QueryCurrentEvents event id is %{public}d, bundle name is %{public}s," + BUNDLE_ACTIVE_LOGD("QueryCurrentEvents event id is %{public}d, bundle name is %{public}s," "time stamp is %{public}lld", result[i].eventId_, result[i].bundleName_.c_str(), (long long)result[i].timeStamp_); } @@ -237,11 +236,11 @@ int32_t BundleActiveProxy::QueryFormStatistics(int32_t maxNum, std::vector &observer) { if (!observer) { - BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack observer null"); + BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack observer is nullptr"); return false; } MessageParcel data; @@ -277,7 +276,7 @@ int32_t BundleActiveProxy::RegisterGroupCallBack(const sptr &observer) { if (!observer) { - BUNDLE_ACTIVE_LOGE("observer null"); + BUNDLE_ACTIVE_LOGE("UnregisterGroupCallBack observer is nullptr"); return false; } MessageParcel data; @@ -287,7 +286,7 @@ int32_t BundleActiveProxy::UnregisterGroupCallBack(const sptrAsObject())) { - BUNDLE_ACTIVE_LOGE("observer write failed."); + BUNDLE_ACTIVE_LOGE("UnregisterGroupCallBack observer write failed."); return false; } Remote()->SendRequest(UNREGISTER_GROUP_CALLBACK, data, reply, option); @@ -299,7 +298,7 @@ int32_t BundleActiveProxy::QueryEventStats(int64_t beginTime, int64_t endTime, { int32_t errCode = IPCCommunication(beginTime, endTime, eventStats, userId, QUERY_EVENT_STATS); for (const auto& singleEvent : eventStats) { - BUNDLE_ACTIVE_LOGI("name is %{public}s, eventId is %{public}d, count is %{public}d", + BUNDLE_ACTIVE_LOGD("QueryEventStats name is %{public}s, eventId is %{public}d, count is %{public}d", singleEvent.name_.c_str(), singleEvent.eventId_, singleEvent.count_); } return errCode; @@ -310,7 +309,7 @@ int32_t BundleActiveProxy::QueryAppNotificationNumber(int64_t beginTime, int64_t { int32_t errCode = IPCCommunication(beginTime, endTime, eventStats, userId, QUERY_APP_NOTIFICATION_NUMBER); for (const auto& singleEvent : eventStats) { - BUNDLE_ACTIVE_LOGI("name is %{public}s, eventId is %{public}d, count is %{public}d", + BUNDLE_ACTIVE_LOGD("QueryAppNotificationNumber name is %{public}s, eventId is %{public}d, count is %{public}d", singleEvent.name_.c_str(), singleEvent.eventId_, singleEvent.count_); } return errCode; diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h index 7d54aa3..7261d2b 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h @@ -57,6 +57,8 @@ enum : int32_t { ERR_REPEAT_OPERATION, ERR_REGISTER_OBSERVER_IS_NULL, ERR_OBSERVER_CALLBACK_IS_INVALID, + ERR_USAGE_STATS_METHOD_CALLED_FAILED, + ERR_USAGE_STATS_INVALID_PARAM, }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index 954a28b..ca7a6de 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -28,6 +28,8 @@ #include "bundle_active_app_state_observer.h" #include "bundle_active_continuous_task_observer.h" #include "bundle_active_account_helper.h" +#include "file_ex.h" +#include "string_ex.h" namespace OHOS { namespace DeviceUsageStats { @@ -135,6 +137,7 @@ public: * return: result of UnregisterGroupCallBack, true or false. */ int32_t UnregisterGroupCallBack(const sptr &observer) override; + int32_t Dump(int32_t fd, const std::vector &args) override; protected: /** @@ -171,6 +174,8 @@ private: void QueryModuleRecordInfos(BundleActiveModuleRecord& moduleRecord); void SerModuleProperties(const HapModuleInfo& hapModuleInfo, const ApplicationInfo& appInfo, const AbilityInfo& abilityInfo, BundleActiveModuleRecord& moduleRecord); + void DumpUsage(std::string &result); + int32_t ShellDump(const std::vector &dumpOption, std::vector &dumpInfo); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 3ab6237..b60270f 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -70,7 +70,7 @@ 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()); + BUNDLE_ACTIVE_LOGD("OnReceiveEvent action is %{public}s", action.c_str()); if (action == CommonEventSupport::COMMON_EVENT_SCREEN_OFF || action == CommonEventSupport::COMMON_EVENT_SCREEN_ON) { if (!activeGroupController_.expired()) { @@ -157,7 +157,7 @@ void BundleActiveCore::RegisterSubscriber() commonEventSubscriber_ = std::make_shared(subscriberInfo, bundleGroupController_, handler_); bool subscribeResult = CommonEventManager::SubscribeCommonEvent(commonEventSubscriber_); - BUNDLE_ACTIVE_LOGI("Register for events result is %{public}d", subscribeResult); + BUNDLE_ACTIVE_LOGD("Register for events result is %{public}d", subscribeResult); } void BundleActiveCore::UnRegisterSubscriber() @@ -175,12 +175,12 @@ void BundleActiveCore::Init() realTimeShot_ = timer->GetBootTimeMs(); systemTimeShot_ = GetSystemTimeMs(); bundleGroupController_ = std::make_shared(debugCore_); - BUNDLE_ACTIVE_LOGI("system time shot is %{public}lld", (long long)systemTimeShot_); + BUNDLE_ACTIVE_LOGD("system time shot is %{public}lld", (long long)systemTimeShot_); } void BundleActiveCore::InitBundleGroupController() { - BUNDLE_ACTIVE_LOGI("InitBundleGroupController called"); + BUNDLE_ACTIVE_LOGD("InitBundleGroupController called"); std::string threadName = "bundle_active_group_handler"; auto runner = AppExecFwk::EventRunner::Create(threadName); if (runner == nullptr) { @@ -219,7 +219,7 @@ void BundleActiveCore::SetHandler(const std::shared_ptr BundleActiveCore::GetUserDataAndInitializeIfNeeded(const int32_t userId, const int64_t timeStamp, const bool debug) { - BUNDLE_ACTIVE_LOGI("GetUserDataAndInitializeIfNeeded called"); + BUNDLE_ACTIVE_LOGD("GetUserDataAndInitializeIfNeeded called"); std::map>::iterator it = userStatServices_.find(userId); if (it == userStatServices_.end()) { BUNDLE_ACTIVE_LOGI("first initialize user service"); @@ -238,7 +238,7 @@ std::shared_ptr BundleActiveCore::GetUserDataAndInitial void BundleActiveCore::OnBundleUninstalled(const int32_t userId, const std::string& bundleName) { - BUNDLE_ACTIVE_LOGI("OnBundleUninstalled CALLED"); + BUNDLE_ACTIVE_LOGD("OnBundleUninstalled CALLED"); std::lock_guard lock(mutex_); int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); if (timeNow == -1) { @@ -293,7 +293,7 @@ void BundleActiveCore::RestoreAllData() void BundleActiveCore::RestoreToDatabase(const int32_t userId) { - BUNDLE_ACTIVE_LOGI("RestoreToDatabase called"); + BUNDLE_ACTIVE_LOGD("RestoreToDatabase called"); sptr timer = MiscServices::TimeServiceClient::GetInstance(); BundleActiveEvent event; event.eventId_ = BundleActiveEvent::FLUSH; @@ -308,7 +308,7 @@ void BundleActiveCore::RestoreToDatabase(const int32_t userId) void BundleActiveCore::RestoreToDatabaseLocked(const int32_t userId) { - BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked called"); + BUNDLE_ACTIVE_LOGD("RestoreToDatabaseLocked called"); auto it = userStatServices_.find(userId); if (it != userStatServices_.end()) { it->second->RestoreStats(false); @@ -347,7 +347,7 @@ void BundleActiveCore::PreservePowerStateInfo(const int32_t eventId) void BundleActiveCore::ShutDown() { std::lock_guard lock(mutex_); - BUNDLE_ACTIVE_LOGI("ShutDown called"); + BUNDLE_ACTIVE_LOGD("ShutDown called"); sptr timer = MiscServices::TimeServiceClient::GetInstance(); int64_t timeStamp = timer->GetBootTimeMs(); BundleActiveEvent event(BundleActiveEvent::SHUTDOWN, timeStamp); @@ -367,7 +367,7 @@ void BundleActiveCore::ShutDown() void BundleActiveCore::OnStatsReload() { - BUNDLE_ACTIVE_LOGI("OnStatsReload called"); + BUNDLE_ACTIVE_LOGD("OnStatsReload called"); bundleGroupController_->CheckIdleStatsOneTime(); } @@ -377,7 +377,7 @@ void BundleActiveCore::OnSystemUpdate(int32_t userId) int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime(int32_t userId) { - BUNDLE_ACTIVE_LOGI("CheckTimeChangeAndGetWallTime called, userId is %{public}d", userId); + BUNDLE_ACTIVE_LOGD("CheckTimeChangeAndGetWallTime called, userId is %{public}d", userId); sptr timer = MiscServices::TimeServiceClient::GetInstance(); int64_t actualSystemTime = GetSystemTimeMs(); int64_t actualRealTime = timer->GetBootTimeMs(); @@ -386,7 +386,7 @@ int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime(int32_t userId) if (actualSystemTime == -1 || actualRealTime == -1) { return -1; } - BUNDLE_ACTIVE_LOGI("asystime is %{public}lld, artime is %{public}lld, esystime is %{public}lld, " + BUNDLE_ACTIVE_LOGD("asystime is %{public}lld, artime is %{public}lld, esystime is %{public}lld, " "diff is %{public}lld", (long long)actualSystemTime, (long long)actualRealTime, (long long)expectedSystemTime, (long long)diffSystemTime); if (std::abs(diffSystemTime) > TIME_CHANGE_THRESHOLD_MILLIS) { @@ -421,7 +421,7 @@ void BundleActiveCore::ConvertToSystemTimeLocked(BundleActiveEvent& event) void BundleActiveCore::OnUserRemoved(const int32_t userId) { - BUNDLE_ACTIVE_LOGI("OnUserRemoved called"); + BUNDLE_ACTIVE_LOGD("OnUserRemoved called"); std::lock_guard lock(mutex_); auto it = userStatServices_.find(userId); if (it == userStatServices_.end()) { @@ -463,7 +463,7 @@ void BundleActiveCore::OnUserSwitched(const int32_t userId) int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, int32_t userId) { - BUNDLE_ACTIVE_LOGI("FLUSH interval is %{public}lld, debug is %{public}d", (long long)flushInterval_, debugCore_); + BUNDLE_ACTIVE_LOGD("FLUSH interval is %{public}lld, debug is %{public}d", (long long)flushInterval_, debugCore_); ObtainSystemEventName(event); event.PrintEvent(debugCore_); std::lock_guard lock(mutex_); @@ -481,7 +481,7 @@ int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, int32_t userId) bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId); return 0; } - BUNDLE_ACTIVE_LOGI("report event called, bundle name %{public}s time %{public}lld userId %{public}d, " + BUNDLE_ACTIVE_LOGD("report event called, bundle name %{public}s time %{public}lld userId %{public}d, " "eventid %{public}d, in lock range", event.bundleName_.c_str(), (long long)event.timeStamp_, userId, event.eventId_); int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); @@ -527,7 +527,7 @@ void BundleActiveCore::ObtainSystemEventName(BundleActiveEvent& event) int32_t BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event) { - BUNDLE_ACTIVE_LOGI("ReportEventToAllUserId called"); + BUNDLE_ACTIVE_LOGD("ReportEventToAllUserId called"); int64_t timeNow = CheckTimeChangeAndGetWallTime(); if (timeNow == -1) { return -1; @@ -554,14 +554,14 @@ int32_t BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event) std::vector BundleActiveCore::QueryPackageStats(const int32_t userId, const int32_t intervalType, const int64_t beginTime, const int64_t endTime, std::string bundleName) { - BUNDLE_ACTIVE_LOGI("QueryPackageStats called"); + BUNDLE_ACTIVE_LOGD("QueryPackageStats called"); std::lock_guard lock(mutex_); std::vector result; int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); if (timeNow == -1) { return result; } - BUNDLE_ACTIVE_LOGI("QueryPackageStats begin time is %{public}lld, end time is %{public}lld, " + BUNDLE_ACTIVE_LOGD("QueryPackageStats begin time is %{public}lld, end time is %{public}lld, " "intervaltype is %{public}d", (long long)beginTime, (long long)endTime, intervalType); if (beginTime > timeNow || beginTime >= endTime) { BUNDLE_ACTIVE_LOGI("QueryPackageStats time span illegal"); @@ -579,7 +579,7 @@ std::vector BundleActiveCore::QueryPackageStats(const std::vector BundleActiveCore::QueryEvents(const int32_t userId, const int64_t beginTime, const int64_t endTime, std::string bundleName) { - BUNDLE_ACTIVE_LOGI("QueryEvents called"); + BUNDLE_ACTIVE_LOGD("QueryEvents called"); std::vector result; std::lock_guard lock(mutex_); int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); @@ -735,7 +735,7 @@ int32_t BundleActiveCore::RegisterGroupCallBack(const AccessToken::AccessTokenID } groupChangeObservers_.emplace(tokenId, observer); AddObserverDeathRecipient(observer); - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack number is %{public}d", static_cast(groupChangeObservers_.size())); + BUNDLE_ACTIVE_LOGD("RegisterGroupCallBack number is %{public}d", static_cast(groupChangeObservers_.size())); return 0; } diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 4375637..2903643 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -19,6 +19,7 @@ #include "accesstoken_kit.h" #include "app_mgr_interface.h" +#include "bundle_state_inner_errors.h" #include "bundle_active_event.h" #include "bundle_active_package_stats.h" #include "bundle_active_account_helper.h" @@ -33,6 +34,11 @@ static const int32_t PERIOD_BEST_SERVICE = 4; static const int32_t DELAY_TIME = 2000; static const std::string PERMITTED_PROCESS_NAME = "foundation"; static const int32_t MAXNUM_UP_LIMIT = 1000; +const int32_t EVENTS_PARAM = 5; +static constexpr int32_t NO_DUMP_PARAM_NUMS = 0; +static constexpr int32_t MIN_DUMP_PARAM_NUMS = 1; +const int32_t PACKAGE_USAGE_PARAM = 6; +const int32_t MODULE_USAGE_PARAM = 4; const std::string NEEDED_PERMISSION = "ohos.permission.BUNDLE_ACTIVE_INFO"; const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); @@ -364,17 +370,16 @@ int32_t BundleActiveService::SetBundleGroup(const std::string& bundleName, int32 std::vector BundleActiveService::QueryCurrentPackageStats(const int32_t intervalType, const int64_t beginTime, const int64_t endTime) { - BUNDLE_ACTIVE_LOGI("QueryCurrentPackageStats stats called"); std::vector result; // get uid int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); - BUNDLE_ACTIVE_LOGI("UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("UID is %{public}d", callingUid); // get userid int32_t userId = -1; OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); if (ret == ERR_OK && userId != -1) { - BUNDLE_ACTIVE_LOGI("QueryCurrentPackageStats userid is %{public}d", userId); + BUNDLE_ACTIVE_LOGD("QueryCurrentPackageStats userid is %{public}d", userId); if (!GetBundleMgrProxy()) { BUNDLE_ACTIVE_LOGE("get bundle manager proxy failed!"); return result; @@ -396,11 +401,10 @@ std::vector BundleActiveService::QueryCurrentPackageSt std::vector BundleActiveService::QueryCurrentEvents(const int64_t beginTime, const int64_t endTime) { - BUNDLE_ACTIVE_LOGI("QueryCurrentEvents stats called"); std::vector result; // get uid int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("QueryCurrentEvents UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("QueryCurrentEvents UID is %{public}d", callingUid); // get userid int32_t userId = -1; OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); @@ -417,7 +421,7 @@ std::vector BundleActiveService::QueryCurrentEvents(const int result = bundleActiveCore_->QueryEvents(userId, beginTime, endTime, bundleName); } } - BUNDLE_ACTIVE_LOGI("QueryCurrentEvents result size is %{public}zu", result.size()); + BUNDLE_ACTIVE_LOGD("QueryCurrentEvents result size is %{public}zu", result.size()); return result; } @@ -555,7 +559,7 @@ int32_t BundleActiveService::QueryFormStatistics(int32_t maxNum, std::vector& eventStats, int32_t userId) { int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("QueryEventStats UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("QueryEventStats UID is %{public}d", callingUid); // get userid when userId is -1 int32_t errCode = 0; if (userId == -1) { @@ -603,7 +607,7 @@ int32_t BundleActiveService::QueryEventStats(int64_t beginTime, int64_t endTime, errCode = bundleActiveCore_->QueryEventStats(beginTime, endTime, eventStats, userId); } } - BUNDLE_ACTIVE_LOGI("QueryEventStats result size is %{public}zu", eventStats.size()); + BUNDLE_ACTIVE_LOGD("QueryEventStats result size is %{public}zu", eventStats.size()); return errCode; } @@ -611,7 +615,7 @@ int32_t BundleActiveService::QueryAppNotificationNumber(int64_t beginTime, int64 std::vector& eventStats, int32_t userId) { int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("QueryAppNotificationNumber UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("QueryAppNotificationNumber UID is %{public}d", callingUid); // get userid when userId is -1 int32_t errCode = 0; if (userId == -1) { @@ -642,13 +646,13 @@ void BundleActiveService::QueryModuleRecordInfos(BundleActiveModuleRecord& modul ApplicationInfo appInfo; if (!sptrBundleMgr_->GetApplicationInfo(moduleRecord.bundleName_, ApplicationFlag::GET_BASIC_APPLICATION_INFO, moduleRecord.userId_, appInfo)) { - BUNDLE_ACTIVE_LOGW("GetApplicationInfo failed!"); + BUNDLE_ACTIVE_LOGE("GetApplicationInfo failed!"); return; } BundleInfo bundleInfo; if (!sptrBundleMgr_->GetBundleInfo(moduleRecord.bundleName_, BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO, bundleInfo, moduleRecord.userId_)) { - BUNDLE_ACTIVE_LOGW("GetBundleInfo failed!"); + BUNDLE_ACTIVE_LOGE("GetBundleInfo failed!"); return; } for (const auto & oneModuleInfo : bundleInfo.hapModuleInfos) { @@ -679,6 +683,100 @@ void BundleActiveService::SerModuleProperties(const HapModuleInfo& hapModuleInfo moduleRecord.abilityIconId_ = abilityInfo.iconId; moduleRecord.installFreeSupported_ = hapModuleInfo.installationFree; } + +int32_t BundleActiveService::Dump(int32_t fd, const std::vector &args) +{ + std::vector argsInStr; + std::transform(args.begin(), args.end(), std::back_inserter(argsInStr), + [](const std::u16string &arg) { + return Str16ToStr8(arg); + }); + std::string result; + int32_t ret = ERR_OK; + if (argsInStr.size() == NO_DUMP_PARAM_NUMS) { + DumpUsage(result); + } else if (argsInStr.size() >= MIN_DUMP_PARAM_NUMS) { + std::vector infos; + if (argsInStr[0] == "-h") { + DumpUsage(result); + } else if (argsInStr[0] == "-A") { + ret = ShellDump(argsInStr, infos); + } else { + infos.emplace_back("BundleActiveService Error params.\n"); + ret = ERR_USAGE_STATS_INVALID_PARAM; + } + for (auto info : infos) { + result.append(info); + } + } + if (!SaveStringToFd(fd, result)) { + BUNDLE_ACTIVE_LOGE("BundleActiveService dump save string to fd failed!"); + ret = ERR_USAGE_STATS_METHOD_CALLED_FAILED; + } + return ret; +} + +int32_t BundleActiveService::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo) +{ + int32_t ret = -1; + + if (dumpOption[1] == "Events") { + std::vector eventResult; + if (static_cast(dumpOption.size()) != EVENTS_PARAM) { + return ret; + } + int64_t beginTime = std::stoll(dumpOption[2]); + int64_t endTime = std::stoll(dumpOption[3]); + int32_t userId = std::stoi(dumpOption[4]); + eventResult = this->QueryEvents(beginTime, endTime, ret, userId); + for (auto& oneEvent : eventResult) { + dumpInfo.emplace_back(oneEvent.ToString()); + } + } else if (dumpOption[1] == "PackageUsage") { + std::vector packageUsageResult; + if (static_cast(dumpOption.size()) != PACKAGE_USAGE_PARAM) { + return ret; + } + int32_t intervalType = std::stoi(dumpOption[2]); + int64_t beginTime = std::stoll(dumpOption[3]); + int64_t endTime = std::stoll(dumpOption[4]); + int32_t userId = std::stoi(dumpOption[5]); + packageUsageResult = this->QueryPackageStats(intervalType, beginTime, endTime, ret, userId); + for (auto& onePackageRecord : packageUsageResult) { + dumpInfo.emplace_back(onePackageRecord.ToString()); + } + } else if (dumpOption[1] == "ModuleUsage") { + std::vector moduleResult; + if (static_cast(dumpOption.size()) != MODULE_USAGE_PARAM) { + return ret; + } + int32_t maxNum = std::stoi(dumpOption[2]); + int32_t userId = std::stoi(dumpOption[3]); + BUNDLE_ACTIVE_LOGI("M is %{public}d, u is %{public}d", maxNum, userId); + ret = this->QueryFormStatistics(maxNum, moduleResult, userId); + for (auto& oneModuleRecord : moduleResult) { + dumpInfo.emplace_back(oneModuleRecord.ToString()); + for (uint32_t i = 0; i < oneModuleRecord.formRecords_.size(); i++) { + std::string oneFormInfo = "form " + std::to_string(static_cast(i) + 1) + ", "; + dumpInfo.emplace_back(oneFormInfo + oneModuleRecord.formRecords_[i].ToString()); + } + } + } + return ret; +} + +void BundleActiveService::DumpUsage(std::string &result) +{ + std::string dumpHelpMsg = + "usage: bundleactive dump []\n" + "options list:\n" + " -h help menu\n" + " -A \n" + " Events [beginTime] [endTime] [userId] get events for one user\n" + " PackageUsage [intervalType] [beginTime] [endTime] [userId] get package usage for one user\n" + " ModuleUsage [maxNum] [userId] get module usage for one user\n"; + result.append(dumpHelpMsg); +} } // namespace DeviceUsageStats } // namespace OHOS diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index e5e9811..6507430 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -38,6 +38,7 @@ ohos_unittest("DeviceUsageStatsTest") { ] external_deps = [ + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "power_manager_native:powermgr_client", -- Gitee From ca48c704989d6f4b2dc4c54696b65df78fee3e8a Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 14 Jun 2022 09:01:12 +0800 Subject: [PATCH 60/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E5=88=86=E7=BB=84?= =?UTF-8?q?=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- BUILD.gn | 2 +- interfaces/innerkits/include/bundle_active_client.h | 2 +- interfaces/innerkits/src/bundle_active_client.cpp | 5 +++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/BUILD.gn b/BUILD.gn index 40d9abc..f812895 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -171,4 +171,4 @@ ohos_shared_library("usagestatservice") { part_name = "${device_usage_statistics_part_name}" subsystem_name = "resourceschedule" -} \ No newline at end of file +} diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h index d20785d..9076576 100644 --- a/interfaces/innerkits/include/bundle_active_client.h +++ b/interfaces/innerkits/include/bundle_active_client.h @@ -132,7 +132,7 @@ private: /* * function: BundleActiveClientDeathRecipient, default constructor. */ - explicit BundleActiveClientDeathRecipient() = default; + BundleActiveClientDeathRecipient() = default; /* * function: ~BundleActiveClientDeathRecipient, default destructor. */ diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 6c3e625..68706e8 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -154,7 +154,7 @@ int32_t BundleActiveClient::RegisterGroupCallBack(const sptrRegisterGroupCallBack(observer); - //AddDeathRecipient when RegisterGroupCallBack success + // AddDeathRecipient when RegisterGroupCallBack success if (recipient_ && result == ERR_OK) { recipient_->setObserver(observer); bundleActiveProxy_->AsObject()->AddDeathRecipient(recipient_); @@ -205,7 +205,8 @@ void BundleActiveClient::BundleActiveClientDeathRecipient::OnRemoteDied(const wp return; } BundleActiveClient::GetInstance().bundleActiveProxy_ = nullptr; - BundleActiveClient::GetInstance().bundleClientHandler_->PostTask([this, &object]() { this->OnServiceDiedInner(object); }); + BundleActiveClient::GetInstance().bundleClientHandler_->PostTask([this, &object]() { + this->OnServiceDiedInner(object); }); } void BundleActiveClient::BundleActiveClientDeathRecipient::OnServiceDiedInner(const wptr &object) -- Gitee From 38a82d5ba4924f0bf8de97c7ef6b5dd958c63950 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 14 Jun 2022 09:03:14 +0800 Subject: [PATCH 61/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E5=88=86=E7=BB=84?= =?UTF-8?q?=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- services/common/src/bundle_active_core.cpp | 2 +- services/common/src/bundle_active_service.cpp | 13 +++++-------- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index b60270f..723dd8b 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -415,7 +415,7 @@ int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime(int32_t userId) void BundleActiveCore::ConvertToSystemTimeLocked(BundleActiveEvent& event) { - BUNDLE_ACTIVE_LOGI("ConvertToSystemTimeLocked called"); + BUNDLE_ACTIVE_LOGD("ConvertToSystemTimeLocked called"); event.timeStamp_ = std::max((int64_t)0, event.timeStamp_ - realTimeShot_) + systemTimeShot_; } diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 2903643..204bbf5 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -180,7 +180,6 @@ void BundleActiveService::InitContinuousSubscriber(const std::shared_ptr appManager = GetAppManagerInstance(); if (appStateObserver_ == nullptr || appManager == nullptr) { BUNDLE_ACTIVE_LOGE("SubscribeAppState appstateobserver is null, return"); @@ -191,7 +190,7 @@ bool BundleActiveService::SubscribeAppState() BUNDLE_ACTIVE_LOGE("RegisterApplicationStateObserver failed. err:%{public}d", err); return false; } - BUNDLE_ACTIVE_LOGI("RegisterApplicationStateObserver success."); + BUNDLE_ACTIVE_LOGD("RegisterApplicationStateObserver success."); return true; } @@ -253,9 +252,8 @@ int32_t BundleActiveService::ReportEvent(BundleActiveEvent& event, const int32_t bool BundleActiveService::IsBundleIdle(const std::string& bundleName) { // get uid - BUNDLE_ACTIVE_LOGI("Is bundle active called"); int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("UID is %{public}d", callingUid); // get user id int32_t userId = -1; int32_t result = -1; @@ -272,12 +270,12 @@ bool BundleActiveService::IsBundleIdle(const std::string& bundleName) std::vector BundleActiveService::QueryPackageStats(const int32_t intervalType, const int64_t beginTime, const int64_t endTime, int32_t& errCode, int32_t userId) { - BUNDLE_ACTIVE_LOGI("QueryPackageStats stats called, intervaltype is %{public}d", intervalType); + BUNDLE_ACTIVE_LOGD("QueryPackageStats stats called, intervaltype is %{public}d", intervalType); std::vector result; // get uid int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); - BUNDLE_ACTIVE_LOGI("QueryPackageStats UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("QueryPackageStats UID is %{public}d", callingUid); if (userId == -1) { // get userid OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); @@ -304,12 +302,11 @@ std::vector BundleActiveService::QueryPackageStats(con std::vector BundleActiveService::QueryEvents(const int64_t beginTime, const int64_t endTime, int32_t& errCode, int32_t userId) { - BUNDLE_ACTIVE_LOGI("QueryEvents stats called"); std::vector result; // get uid int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); - BUNDLE_ACTIVE_LOGI("QueryEvents UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGD("QueryEvents UID is %{public}d", callingUid); if (userId == -1) { // get userid OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); -- Gitee From d19d4579b4f0fe21feef6df64728c697892f40f5 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 14 Jun 2022 09:15:30 +0800 Subject: [PATCH 62/83] =?UTF-8?q?=E5=BA=94=E7=94=A8=E5=88=86=E7=BB=84?= =?UTF-8?q?=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- interfaces/innerkits/src/bundle_active_client.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 68706e8..889b719 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -206,7 +206,8 @@ void BundleActiveClient::BundleActiveClientDeathRecipient::OnRemoteDied(const wp } BundleActiveClient::GetInstance().bundleActiveProxy_ = nullptr; BundleActiveClient::GetInstance().bundleClientHandler_->PostTask([this, &object]() { - this->OnServiceDiedInner(object); }); + this->OnServiceDiedInner(object); + }); } void BundleActiveClient::BundleActiveClientDeathRecipient::OnServiceDiedInner(const wptr &object) -- Gitee From ed4a29268e669758246684607de01812ebac5888 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 14 Jun 2022 12:08:05 +0800 Subject: [PATCH 63/83] =?UTF-8?q?=E5=BB=B6=E8=BF=9F5=E7=A7=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../src/bundle_active_group_observer.cpp | 24 ++----------------- frameworks/src/bundle_state_common.cpp | 1 - frameworks/src/bundle_state_query.cpp | 5 ++-- .../innerkits/src/bundle_active_client.cpp | 2 +- .../napi/include/bundle_state_common.h | 23 ++++++++++++++++++ 5 files changed, 28 insertions(+), 27 deletions(-) diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index 5654d31..f988374 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -48,26 +48,6 @@ void BundleActiveGroupObserver::SetCallbackInfo(const napi_env &env, const napi_ bundleGroupCallbackInfo_.ref = ref; } -template -void AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) -{ - if (params.errorCode != ERR_OK) { - return ; - } - asyncCallbackInfo = new (std::nothrow) ASYNCT(env); - if (!asyncCallbackInfo) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; - return ; - } - if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) - != EOK) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - return ; - } -} - napi_value SetBundleGroupChangedData(const CallbackReceiveDataWorker *commonEventDataWorkerData, napi_value &result) { if (!commonEventDataWorkerData) { @@ -235,7 +215,7 @@ napi_value ParseRegisterGroupCallBackParameters(const napi_env &env, const napi_ NAPI_ASSERT(env, valuetype == napi_function, "ParseStatesParameters invalid parameter type. Function expected"); napi_create_reference(env, argv[1], 1, ¶ms.callback); } - AsyncInit(env, params, asyncCallbackInfo); + BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); } @@ -307,7 +287,7 @@ napi_value ParseUnRegisterGroupCallBackParameters(const napi_env &env, const nap params.errorCode = ERR_REGISTER_OBSERVER_IS_NULL; return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - AsyncInit(env, params, asyncCallbackInfo); + BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); } diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp index dcefc97..9bcc0a8 100644 --- a/frameworks/src/bundle_state_common.cpp +++ b/frameworks/src/bundle_state_common.cpp @@ -16,7 +16,6 @@ #include "securec.h" #include "bundle_active_log.h" -#include "bundle_state_inner_errors.h" #include "bundle_state_common.h" namespace OHOS { diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index 6f33292..d3741c4 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -63,7 +63,6 @@ void AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; delete asyncCallbackInfo; asyncCallbackInfo = nullptr; - return ; } } @@ -308,7 +307,7 @@ napi_value ParsePriorityGroupParameters(const napi_env &env, const napi_callback napi_create_reference(env, argv[1], 1, ¶ms.callback); } } - AsyncInit(env, params, asyncCallbackInfo); + BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); } @@ -825,7 +824,7 @@ napi_value ParseAppUsageBundleGroupInfoParameters(const napi_env &env, const nap "Function expected."); napi_create_reference(env, argv[SECOND_ARG], 1, ¶ms.callback); } - AsyncInit(env, params, asyncCallbackInfo); + BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); } diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 889b719..217889a 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -207,7 +207,7 @@ void BundleActiveClient::BundleActiveClientDeathRecipient::OnRemoteDied(const wp BundleActiveClient::GetInstance().bundleActiveProxy_ = nullptr; BundleActiveClient::GetInstance().bundleClientHandler_->PostTask([this, &object]() { this->OnServiceDiedInner(object); - }); + }, 5000); } void BundleActiveClient::BundleActiveClientDeathRecipient::OnServiceDiedInner(const wptr &object) diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h index a0f5512..59a8f9d 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h @@ -21,6 +21,7 @@ #include "bundle_state_query.h" #include "napi/native_api.h" #include "napi/native_node_api.h" +#include "bundle_state_inner_errors.h" namespace OHOS { namespace DeviceUsageStats { @@ -83,7 +84,29 @@ public: static std::unique_ptr HandleEventStatsInfo( AsyncCallbackInfoEventStats *asyncCallbackInfo, EventStatesParamsInfo ¶ms); + + template + void AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) }; + +template +void BundleStateCommon::AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) +{ + if (params.errorCode != ERR_OK) { + return ; + } + asyncCallbackInfo = new (std::nothrow) ASYNCT(env); + if (!asyncCallbackInfo) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return ; + } + if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) + != EOK) { + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } +} } // namespace DeviceUsageStats } // namespace OHOS #endif // FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_COMMON_H -- Gitee From a1bf65f3b9987aabacda7d3551cd52a77b40f57e Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 14 Jun 2022 12:10:42 +0800 Subject: [PATCH 64/83] =?UTF-8?q?=E5=BB=B6=E8=BF=9F5=E7=A7=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- frameworks/src/bundle_active_group_observer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index f988374..7dce5a3 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -285,7 +285,7 @@ napi_value ParseUnRegisterGroupCallBackParameters(const napi_env &env, const nap if (!registerObserver) { BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack observer is not exist"); params.errorCode = ERR_REGISTER_OBSERVER_IS_NULL; - return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); + return BundleStateCommon::NapiGetNull(env); } BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); -- Gitee From 2e30b11fd4f1611d2b81c65e42506115d35e6a63 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 14 Jun 2022 12:14:54 +0800 Subject: [PATCH 65/83] =?UTF-8?q?=E5=BB=B6=E8=BF=9F5=E7=A7=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- frameworks/src/bundle_state_query.cpp | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index d3741c4..f472641 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -47,25 +47,6 @@ const std::vector GROUP_TYPE {10, 20, 30, 40, 50, 60}; const uint32_t EVENT_STATES_MIN_PARAMS = 2; const uint32_t EVENT_STATES_PARAMS = 3; -template -void AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) -{ - if (params.errorCode != ERR_OK) { - return ; - } - asyncCallbackInfo = new (std::nothrow) ASYNCT(env); - if (!asyncCallbackInfo) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; - return ; - } - if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) - != EOK) { - params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED; - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - } -} - napi_value ParseModuleRecordsParameters(const napi_env &env, const napi_callback_info &info, ModuleRecordParamsInfo ¶ms) { -- Gitee From ec86ef2d9117930171525876d74c2be981f65c3a Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 14 Jun 2022 12:21:05 +0800 Subject: [PATCH 66/83] =?UTF-8?q?=E5=BB=B6=E8=BF=9F5=E7=A7=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- interfaces/innerkits/src/bundle_active_client.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 217889a..646cf0d 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -19,6 +19,7 @@ namespace OHOS { namespace DeviceUsageStats { namespace { const std::string BUNDLE_ACTIVE_CLIENT_NAME = "bundleActiveName"; + static const int32_t DELAY_TIME = 5000; } BundleActiveClient& BundleActiveClient::GetInstance() { @@ -206,8 +207,9 @@ void BundleActiveClient::BundleActiveClientDeathRecipient::OnRemoteDied(const wp } BundleActiveClient::GetInstance().bundleActiveProxy_ = nullptr; BundleActiveClient::GetInstance().bundleClientHandler_->PostTask([this, &object]() { - this->OnServiceDiedInner(object); - }, 5000); + this->OnServiceDiedInner(object); + }, + DELAY_TIME); } void BundleActiveClient::BundleActiveClientDeathRecipient::OnServiceDiedInner(const wptr &object) -- Gitee From 687785a2b8ae11be220bec75c662ac1e596de70f Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 14 Jun 2022 12:26:52 +0800 Subject: [PATCH 67/83] =?UTF-8?q?=E5=BB=B6=E8=BF=9F5=E7=A7=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- interfaces/innerkits/src/bundle_active_client.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 646cf0d..af44281 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -207,9 +207,9 @@ void BundleActiveClient::BundleActiveClientDeathRecipient::OnRemoteDied(const wp } BundleActiveClient::GetInstance().bundleActiveProxy_ = nullptr; BundleActiveClient::GetInstance().bundleClientHandler_->PostTask([this, &object]() { - this->OnServiceDiedInner(object); - }, - DELAY_TIME); + this->OnServiceDiedInner(object); + }, + DELAY_TIME); } void BundleActiveClient::BundleActiveClientDeathRecipient::OnServiceDiedInner(const wptr &object) -- Gitee From cfb5fe678636ccadfa603293d90ae92d02fe693b Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 14 Jun 2022 13:37:05 +0800 Subject: [PATCH 68/83] =?UTF-8?q?=E5=BB=B6=E8=BF=9F5=E7=A7=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- interfaces/kits/bundlestats/napi/include/bundle_state_common.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h index 59a8f9d..8187de3 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h @@ -86,7 +86,7 @@ public: AsyncCallbackInfoEventStats *asyncCallbackInfo, EventStatesParamsInfo ¶ms); template - void AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) + static void AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) }; template -- Gitee From 59fdedb4879ed88791a6594edd8a262254bc8693 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 14 Jun 2022 13:37:50 +0800 Subject: [PATCH 69/83] =?UTF-8?q?=E5=BB=B6=E8=BF=9F5=E7=A7=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- interfaces/kits/bundlestats/napi/include/bundle_state_common.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h index 8187de3..3ac5015 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h @@ -86,7 +86,7 @@ public: AsyncCallbackInfoEventStats *asyncCallbackInfo, EventStatesParamsInfo ¶ms); template - static void AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo) + static void AsyncInit(napi_env env, PARAMT ¶ms, ASYNCT* &asyncCallbackInfo); }; template -- Gitee From 49b9f0e74c6cbada60b31902db2008b08ba072b6 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Tue, 14 Jun 2022 13:57:26 +0800 Subject: [PATCH 70/83] =?UTF-8?q?=E5=BB=B6=E8=BF=9F5=E7=A7=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../device_usage_statistics_jsunit.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js index a5c96c4..84079ea 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -434,10 +434,10 @@ describe("DeviceUsageStatisticsJsTest", function () { let newGroup = 30; bundleState.setBundleGroup(bundleName, newGroup).then( res => { console.info('BUNDLE_ACTIVE setBundleGroup promise success.'); - expect(true).assertEqual(true); + expect(false).assertEqual(true); }).catch( err => { console.info('BUNDLE_ACTIVE setBundleGroup promise failure.'); - expect(false).assertEqual(true); + expect(true).assertEqual(true); }); setTimeout(()=>{ -- Gitee From 61d7e391aeade6fa8da644ac6682ad85a4339302 Mon Sep 17 00:00:00 2001 From: houdisheng Date: Tue, 14 Jun 2022 15:25:23 +0800 Subject: [PATCH 71/83] =?UTF-8?q?isIdleState=E6=9D=83=E9=99=90=E6=A0=A1?= =?UTF-8?q?=E9=AA=8C=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 --- frameworks/src/bundle_state_query.cpp | 2 +- .../innerkits/include/bundle_active_client.h | 2 +- .../innerkits/include/bundle_active_proxy.h | 2 +- .../innerkits/src/bundle_active_client.cpp | 4 +-- .../innerkits/src/bundle_active_proxy.cpp | 6 ++-- .../napi/include/bundle_state_data.h | 2 +- .../device_usage_statistics_jsunit.test.js | 8 ++--- .../common/include/bundle_active_service.h | 2 +- .../common/include/ibundle_active_service.h | 4 +-- services/common/src/bundle_active_service.cpp | 36 +++++++++++++++---- services/common/src/bundle_active_stub.cpp | 6 ++-- .../unittest/device_usage_statistics_test.cpp | 6 ++-- 12 files changed, 53 insertions(+), 27 deletions(-) diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index b604db1..112b881 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -221,7 +221,7 @@ napi_value IsIdleState(napi_env env, napi_callback_info info) AsyncCallbackInfoIsIdleState *asyncCallbackInfo = (AsyncCallbackInfoIsIdleState *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->state = BundleActiveClient::GetInstance().IsBundleIdle( - asyncCallbackInfo->bundleName); + asyncCallbackInfo->bundleName, asyncCallbackInfo->errorCode); } else { BUNDLE_ACTIVE_LOGE("IsIdleState, asyncCallbackInfo == nullptr"); } diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h index c396903..6e186ba 100644 --- a/interfaces/innerkits/include/bundle_active_client.h +++ b/interfaces/innerkits/include/bundle_active_client.h @@ -42,7 +42,7 @@ public: * parameters: bundleName * return: if bundle is idle, return true. if bundle is not idle, return false. */ - bool IsBundleIdle(const std::string& bundleName); + bool IsBundleIdle(const std::string& bundleName, int32_t& errCode); /* * function: QueryPackageStats, query all bundle usage statistics in specific time span for calling user. * parameters: intervalType, beginTime, endTime, errCode diff --git a/interfaces/innerkits/include/bundle_active_proxy.h b/interfaces/innerkits/include/bundle_active_proxy.h index a0b90b3..5adce7c 100644 --- a/interfaces/innerkits/include/bundle_active_proxy.h +++ b/interfaces/innerkits/include/bundle_active_proxy.h @@ -38,7 +38,7 @@ public: * parameters: bundleName * return: if bundle is idle, return true. if bundle is not idle, return false. */ - bool IsBundleIdle(const std::string& bundleName) override; + bool IsBundleIdle(const std::string& bundleName, int32_t& errCode) override; /* * function: QueryPackageStats, query all bundle usage statistics in specific time span for calling user. * parameters: intervalType, beginTime, endTime, errCode diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 58478d4..2b635de 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -63,12 +63,12 @@ int32_t BundleActiveClient::ReportEvent(BundleActiveEvent event, const int32_t u return bundleActiveProxy_->ReportEvent(event, userId); } -bool BundleActiveClient::IsBundleIdle(const std::string& bundleName) +bool BundleActiveClient::IsBundleIdle(const std::string& bundleName, int32_t& errCode) { if (!GetBundleActiveProxy()) { return -1; } - return bundleActiveProxy_->IsBundleIdle(bundleName); + return bundleActiveProxy_->IsBundleIdle(bundleName, errCode); } std::vector BundleActiveClient::QueryPackageStats(const int32_t intervalType, diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index 1392c7d..93bc327 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -33,7 +33,7 @@ int32_t BundleActiveProxy::ReportEvent(BundleActiveEvent& event, const int32_t u return result; } -bool BundleActiveProxy::IsBundleIdle(const std::string& bundleName) +bool BundleActiveProxy::IsBundleIdle(const std::string& bundleName, int32_t& errCode) { MessageParcel data; MessageParcel reply; @@ -43,8 +43,8 @@ bool BundleActiveProxy::IsBundleIdle(const std::string& bundleName) } data.WriteString(bundleName); Remote() -> SendRequest(IS_BUNDLE_IDLE, data, reply, option); - int32_t result = reply.ReadInt32(); - BUNDLE_ACTIVE_LOGI("result is %{public}d", result); + bool result = reply.ReadInt32(); + errCode = reply.ReadInt32(); return result; } diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h index 6856cf0..8118aab 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h @@ -71,7 +71,7 @@ struct CallbackReceiveDataWorker { struct AsyncCallbackInfoIsIdleState : public AsyncWorkData { explicit AsyncCallbackInfoIsIdleState(napi_env env) : AsyncWorkData(env) {} std::string bundleName = ""; - bool state = true; + bool state = false; }; struct AsyncCallbackInfoPriorityGroup : public AsyncWorkData { diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js index a5c96c4..284a809 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -467,7 +467,7 @@ describe("DeviceUsageStatisticsJsTest", function () { setTimeout(()=>{ done(); - }, 500); + }, 500); }) /* @@ -498,7 +498,7 @@ describe("DeviceUsageStatisticsJsTest", function () { done(); }, 500); }) - + /* * @tc.name: DeviceUsageStatisticsJsTest020 * @tc.desc: test registerGroupCallBack callback. @@ -527,7 +527,7 @@ describe("DeviceUsageStatisticsJsTest", function () { setTimeout(()=>{ done(); - }, 500); + }, 500); }) /* @@ -571,7 +571,7 @@ describe("DeviceUsageStatisticsJsTest", function () { setTimeout(()=>{ done(); - }, 500); + }, 500); }) /* diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index 954a28b..7e45ef2 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -56,7 +56,7 @@ public: * parameters: bundleName * return: if bundle is idle, return true. if bundle is not idle, return false. */ - bool IsBundleIdle(const std::string& bundleName) override; + bool IsBundleIdle(const std::string& bundleName, int32_t& errCode) override; /* * function: QueryPackageStats, query all bundle usage statistics in specific time span for calling user. * parameters: intervalType, beginTime, endTime, errCode diff --git a/services/common/include/ibundle_active_service.h b/services/common/include/ibundle_active_service.h index eff21f7..ee37510 100644 --- a/services/common/include/ibundle_active_service.h +++ b/services/common/include/ibundle_active_service.h @@ -61,7 +61,7 @@ public: * parameters: bundleName * return: if bundle is idle, return true. if bundle is not idle, return false. */ - virtual bool IsBundleIdle(const std::string& bundleName) = 0; + virtual bool IsBundleIdle(const std::string& bundleName, int32_t& errCode) = 0; /* * function: QueryPackageStats, query all bundle usage statistics in specific time span for calling user. * parameters: intervalType, beginTime, endTime, errCode @@ -120,7 +120,7 @@ public: */ virtual int32_t QueryEventStats(int64_t beginTime, int64_t endTime, std::vector& eventStats, int32_t userId) = 0; - + /* * function: QueryAppNotificationNumber, query all app notification number in specific time span for calling user. * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API, diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 4375637..de701d7 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -244,20 +244,42 @@ int32_t BundleActiveService::ReportEvent(BundleActiveEvent& event, const int32_t } } -bool BundleActiveService::IsBundleIdle(const std::string& bundleName) +bool BundleActiveService::IsBundleIdle(const std::string& bundleName, int32_t& errCode) { // get uid - BUNDLE_ACTIVE_LOGI("Is bundle active called"); int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("UID is %{public}d", callingUid); + AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + if (!GetBundleMgrProxy()) { + BUNDLE_ACTIVE_LOGE("get bundle manager proxy failed!"); + return false; + } + std::string callingBundleName = ""; + sptrBundleMgr_->GetBundleNameForUid(callingUid, callingBundleName); + BUNDLE_ACTIVE_LOGI("UID is %{public}d, bundle name is %{public}s", callingUid, callingBundleName.c_str()); // get user id int32_t userId = -1; int32_t result = -1; - OHOS::ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); - if (ret == ERR_OK && userId != -1) { - result = bundleActiveCore_->IsBundleIdle(bundleName, userId); + BundleActiveAccountHelper::GetUserId(callingUid, userId); + if (userId != -1 && !callingBundleName.empty()) { + if (callingBundleName == bundleName) { + BUNDLE_ACTIVE_LOGI("%{public}s check its own idle state", bundleName.c_str()); + result = bundleActiveCore_->IsBundleIdle(bundleName, userId); + } else { + bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId, errCode); + BUNDLE_ACTIVE_LOGI("check other bundle idle state"); + if (isSystemAppAndHasPermission) { + errCode = 0; + result = bundleActiveCore_->IsBundleIdle(bundleName, userId); + } else { + errCode = -1; + return false; + } + } + } else { + errCode = -1; + return false; } - if (result == 0) { + if (result == 0 || result == -1) { return false; } return true; diff --git a/services/common/src/bundle_active_stub.cpp b/services/common/src/bundle_active_stub.cpp index 25fe267..3dae350 100644 --- a/services/common/src/bundle_active_stub.cpp +++ b/services/common/src/bundle_active_stub.cpp @@ -40,8 +40,10 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me } case IS_BUNDLE_IDLE: { std::string bundleName = data.ReadString(); - int32_t result = IsBundleIdle(bundleName); - return reply.WriteInt32(result); + int32_t errCode = data.ReadInt32(); + int32_t result = IsBundleIdle(bundleName, errCode); + reply.WriteInt32(result); + return reply.WriteInt32(errCode); } case QUERY_USAGE_STATS: { std::vector result; diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 01fbb0b..2748693 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -150,8 +150,10 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackagesStats */ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_IsBundleIdle_001, Function | MediumTest | Level0) { - bool result = BundleActiveClient::GetInstance().IsBundleIdle(DEFAULT_BUNDLENAME); - EXPECT_EQ(result, true); + int32_t errCode = 0; + bool result = BundleActiveClient::GetInstance().IsBundleIdle(DEFAULT_BUNDLENAME, errCode); + EXPECT_EQ(result, false); + EXPECT_EQ(errCode, -1); } /* -- Gitee From 9be9804d027fd808e4835327a949645a64a4b3c1 Mon Sep 17 00:00:00 2001 From: houdisheng Date: Wed, 15 Jun 2022 10:49:39 +0800 Subject: [PATCH 72/83] =?UTF-8?q?=E6=B7=BB=E5=8A=A0isbundleidle=E5=AF=B9na?= =?UTF-8?q?tive=E8=BF=9B=E7=A8=8B=E7=9A=84=E6=9D=83=E9=99=90=E6=A0=A1?= =?UTF-8?q?=E9=AA=8C?= 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 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index de701d7..4a6612a 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -260,14 +260,16 @@ bool BundleActiveService::IsBundleIdle(const std::string& bundleName, int32_t& e int32_t userId = -1; int32_t result = -1; BundleActiveAccountHelper::GetUserId(callingUid, userId); - if (userId != -1 && !callingBundleName.empty()) { + if (userId != -1) { if (callingBundleName == bundleName) { BUNDLE_ACTIVE_LOGI("%{public}s check its own idle state", bundleName.c_str()); result = bundleActiveCore_->IsBundleIdle(bundleName, userId); } else { bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId, errCode); BUNDLE_ACTIVE_LOGI("check other bundle idle state"); - if (isSystemAppAndHasPermission) { + if (isSystemAppAndHasPermission || + AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) == + AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE) { errCode = 0; result = bundleActiveCore_->IsBundleIdle(bundleName, userId); } else { -- Gitee From bf86d4cbc51bb7d5be8e8eb989aa37b89ef6851a Mon Sep 17 00:00:00 2001 From: houdisheng Date: Wed, 15 Jun 2022 11:06:19 +0800 Subject: [PATCH 73/83] =?UTF-8?q?isbundleidle=E6=8E=A5=E5=8F=A3=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0native=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- interfaces/innerkits/include/bundle_active_client.h | 2 +- interfaces/innerkits/include/bundle_active_proxy.h | 2 +- interfaces/innerkits/src/bundle_active_client.cpp | 4 ++-- interfaces/innerkits/src/bundle_active_proxy.cpp | 4 +++- services/common/include/bundle_active_service.h | 2 +- services/common/include/ibundle_active_service.h | 2 +- services/common/src/bundle_active_service.cpp | 7 ++++--- services/common/src/bundle_active_stub.cpp | 3 ++- 8 files changed, 15 insertions(+), 11 deletions(-) diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h index 6e186ba..772000c 100644 --- a/interfaces/innerkits/include/bundle_active_client.h +++ b/interfaces/innerkits/include/bundle_active_client.h @@ -42,7 +42,7 @@ public: * parameters: bundleName * return: if bundle is idle, return true. if bundle is not idle, return false. */ - bool IsBundleIdle(const std::string& bundleName, int32_t& errCode); + bool IsBundleIdle(const std::string& bundleName, int32_t& errCode, int32_t userId = -1); /* * function: QueryPackageStats, query all bundle usage statistics in specific time span for calling user. * parameters: intervalType, beginTime, endTime, errCode diff --git a/interfaces/innerkits/include/bundle_active_proxy.h b/interfaces/innerkits/include/bundle_active_proxy.h index 5adce7c..9e0a205 100644 --- a/interfaces/innerkits/include/bundle_active_proxy.h +++ b/interfaces/innerkits/include/bundle_active_proxy.h @@ -38,7 +38,7 @@ public: * parameters: bundleName * return: if bundle is idle, return true. if bundle is not idle, return false. */ - bool IsBundleIdle(const std::string& bundleName, int32_t& errCode) override; + bool IsBundleIdle(const std::string& bundleName, int32_t& errCode, int32_t userId = -1) override; /* * function: QueryPackageStats, query all bundle usage statistics in specific time span for calling user. * parameters: intervalType, beginTime, endTime, errCode diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 2b635de..4c0441d 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -63,12 +63,12 @@ int32_t BundleActiveClient::ReportEvent(BundleActiveEvent event, const int32_t u return bundleActiveProxy_->ReportEvent(event, userId); } -bool BundleActiveClient::IsBundleIdle(const std::string& bundleName, int32_t& errCode) +bool BundleActiveClient::IsBundleIdle(const std::string& bundleName, int32_t& errCode, int32_t userId) { if (!GetBundleActiveProxy()) { return -1; } - return bundleActiveProxy_->IsBundleIdle(bundleName, errCode); + return bundleActiveProxy_->IsBundleIdle(bundleName, errCode, userId); } std::vector BundleActiveClient::QueryPackageStats(const int32_t intervalType, diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index 93bc327..d4b64f7 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -33,7 +33,7 @@ int32_t BundleActiveProxy::ReportEvent(BundleActiveEvent& event, const int32_t u return result; } -bool BundleActiveProxy::IsBundleIdle(const std::string& bundleName, int32_t& errCode) +bool BundleActiveProxy::IsBundleIdle(const std::string& bundleName, int32_t& errCode, int32_t userId) { MessageParcel data; MessageParcel reply; @@ -42,6 +42,8 @@ bool BundleActiveProxy::IsBundleIdle(const std::string& bundleName, int32_t& err return false; } data.WriteString(bundleName); + data.WriteInt32(errCode); + data.WriteInt32(userId); Remote() -> SendRequest(IS_BUNDLE_IDLE, data, reply, option); bool result = reply.ReadInt32(); errCode = reply.ReadInt32(); diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index 7e45ef2..92ad34e 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -56,7 +56,7 @@ public: * parameters: bundleName * return: if bundle is idle, return true. if bundle is not idle, return false. */ - bool IsBundleIdle(const std::string& bundleName, int32_t& errCode) override; + bool IsBundleIdle(const std::string& bundleName, int32_t& errCode, int32_t userId = -1) override; /* * function: QueryPackageStats, query all bundle usage statistics in specific time span for calling user. * parameters: intervalType, beginTime, endTime, errCode diff --git a/services/common/include/ibundle_active_service.h b/services/common/include/ibundle_active_service.h index ee37510..4935160 100644 --- a/services/common/include/ibundle_active_service.h +++ b/services/common/include/ibundle_active_service.h @@ -61,7 +61,7 @@ public: * parameters: bundleName * return: if bundle is idle, return true. if bundle is not idle, return false. */ - virtual bool IsBundleIdle(const std::string& bundleName, int32_t& errCode) = 0; + virtual bool IsBundleIdle(const std::string& bundleName, int32_t& errCode, int32_t userId) = 0; /* * function: QueryPackageStats, query all bundle usage statistics in specific time span for calling user. * parameters: intervalType, beginTime, endTime, errCode diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 4a6612a..0d13b45 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -244,7 +244,7 @@ int32_t BundleActiveService::ReportEvent(BundleActiveEvent& event, const int32_t } } -bool BundleActiveService::IsBundleIdle(const std::string& bundleName, int32_t& errCode) +bool BundleActiveService::IsBundleIdle(const std::string& bundleName, int32_t& errCode, int32_t userId) { // get uid int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); @@ -257,9 +257,10 @@ bool BundleActiveService::IsBundleIdle(const std::string& bundleName, int32_t& e sptrBundleMgr_->GetBundleNameForUid(callingUid, callingBundleName); BUNDLE_ACTIVE_LOGI("UID is %{public}d, bundle name is %{public}s", callingUid, callingBundleName.c_str()); // get user id - int32_t userId = -1; int32_t result = -1; - BundleActiveAccountHelper::GetUserId(callingUid, userId); + if (userId == -1) { + BundleActiveAccountHelper::GetUserId(callingUid, userId); + } if (userId != -1) { if (callingBundleName == bundleName) { BUNDLE_ACTIVE_LOGI("%{public}s check its own idle state", bundleName.c_str()); diff --git a/services/common/src/bundle_active_stub.cpp b/services/common/src/bundle_active_stub.cpp index 3dae350..4745fe8 100644 --- a/services/common/src/bundle_active_stub.cpp +++ b/services/common/src/bundle_active_stub.cpp @@ -41,7 +41,8 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me case IS_BUNDLE_IDLE: { std::string bundleName = data.ReadString(); int32_t errCode = data.ReadInt32(); - int32_t result = IsBundleIdle(bundleName, errCode); + int32_t userId = data.ReadInt32(); + int32_t result = IsBundleIdle(bundleName, errCode, userId); reply.WriteInt32(result); return reply.WriteInt32(errCode); } -- Gitee From 3a1f13aa2867ea407ae6ab1cd2cf295d3ff97cde Mon Sep 17 00:00:00 2001 From: houdisheng Date: Wed, 15 Jun 2022 13:56:22 +0800 Subject: [PATCH 74/83] =?UTF-8?q?=E9=80=82=E9=85=8Dtdd=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- test/unittest/device_usage_statistics_test.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 2748693..7c8142b 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -151,9 +151,9 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackagesStats HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_IsBundleIdle_001, Function | MediumTest | Level0) { int32_t errCode = 0; - bool result = BundleActiveClient::GetInstance().IsBundleIdle(DEFAULT_BUNDLENAME, errCode); + bool result = BundleActiveClient::GetInstance().IsBundleIdle(DEFAULT_BUNDLENAME, errCode, DEFAULT_USERID); EXPECT_EQ(result, false); - EXPECT_EQ(errCode, -1); + EXPECT_EQ(errCode, 0); } /* -- Gitee From 28387759245b928c4fc20cca5e272fc28f2980b8 Mon Sep 17 00:00:00 2001 From: houdisheng Date: Wed, 15 Jun 2022 15:10:53 +0800 Subject: [PATCH 75/83] =?UTF-8?q?=E4=BF=AE=E6=94=B9proxyipc=E9=80=9A?= =?UTF-8?q?=E8=AE=AF=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- interfaces/innerkits/src/bundle_active_proxy.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index 3161b35..f984489 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -38,12 +38,12 @@ bool BundleActiveProxy::IsBundleIdle(const std::string& bundleName, int32_t& err MessageParcel data; MessageParcel reply; MessageOption option; - if (!data.WriteInterfaceToken(GetDescriptor())) { + if (!data.WriteInterfaceToken(GetDescriptor()) || + !data.WriteString(bundleName) || + !data.WriteInt32(errCode) || + !data.WriteInt32(userId)) { return false; } - data.WriteString(bundleName); - data.WriteInt32(errCode); - data.WriteInt32(userId); Remote() -> SendRequest(IS_BUNDLE_IDLE, data, reply, option); bool result = reply.ReadInt32(); errCode = reply.ReadInt32(); -- Gitee From 0645b276bda8f701d5547f0a9e7953244e8233f8 Mon Sep 17 00:00:00 2001 From: xbingle Date: Fri, 17 Jun 2022 21:36:39 +0800 Subject: [PATCH 76/83] =?UTF-8?q?=E5=88=A0=E9=99=A4=E4=B8=8D=E7=94=A8?= =?UTF-8?q?=E7=9A=84=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xbingle --- BUILD.gn | 1 - 1 file changed, 1 deletion(-) diff --git a/BUILD.gn b/BUILD.gn index f812895..76c8b31 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -154,7 +154,6 @@ ohos_shared_library("usagestatservice") { "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "permission_standard:libpermissionsdk_standard", "power_manager_native:powermgr_client", "relational_store:native_rdb", "safwk:system_ability_fwk", -- Gitee From d603f4232f19fd13619668ea34a331cd04cf9956 Mon Sep 17 00:00:00 2001 From: xbingle Date: Sat, 18 Jun 2022 10:59:30 +0800 Subject: [PATCH 77/83] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=97=A0=E7=94=A8?= =?UTF-8?q?=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xbingle --- test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn | 1 - 1 file changed, 1 deletion(-) diff --git a/test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn b/test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn index 45aaa50..d3eebd5 100644 --- a/test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn +++ b/test/fuzztest/bundleactiveonremoterequest_fuzzer/BUILD.gn @@ -54,7 +54,6 @@ ohos_fuzztest("BundleActiveOnRemoteRequestFuzzTest") { "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "permission_standard:libpermissionsdk_standard", "power_manager_native:powermgr_client", "relational_store:native_rdb", "safwk:system_ability_fwk", -- Gitee From be1c0b1fd0d5bedd5fa9286e9aa7ba339bcfcaec Mon Sep 17 00:00:00 2001 From: xbingle Date: Mon, 20 Jun 2022 14:44:11 +0800 Subject: [PATCH 78/83] =?UTF-8?q?=E5=88=A0=E9=99=A4=E4=B8=8D=E7=94=A8?= =?UTF-8?q?=E7=9A=84=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xbingle --- bundle.json | 1 - 1 file changed, 1 deletion(-) diff --git a/bundle.json b/bundle.json index d389347..6d1739a 100644 --- a/bundle.json +++ b/bundle.json @@ -24,7 +24,6 @@ "deps": { "components": [ "libhilog", - "libpermissionsdk_standard", "powermgr_client", "cesfwk_innerkits", "wantagent_innerkits", -- Gitee From e01bb57a48a6e3c7bd93347742648468b53d5c50 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Thu, 23 Jun 2022 11:03:40 +0800 Subject: [PATCH 79/83] =?UTF-8?q?=E6=A0=B9=E6=8D=AEdocs=E4=BB=93=E5=8F=98?= =?UTF-8?q?=E5=8C=96=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../src/bundle_active_group_observer.cpp | 6 ++--- .../device_usage_statistics_jsunit.test.js | 22 +++++++++---------- services/common/include/bundle_active_log.h | 2 +- .../unittest/device_usage_statistics_test.cpp | 2 +- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp index 7dce5a3..15aefc4 100644 --- a/frameworks/src/bundle_active_group_observer.cpp +++ b/frameworks/src/bundle_active_group_observer.cpp @@ -58,11 +58,11 @@ napi_value SetBundleGroupChangedData(const CallbackReceiveDataWorker *commonEven // oldGroup napi_create_int32(commonEventDataWorkerData->env, commonEventDataWorkerData->oldGroup, &value); - napi_set_named_property(commonEventDataWorkerData->env, result, "oldGroup", value); + napi_set_named_property(commonEventDataWorkerData->env, result, "appUsageOldGroup", value); // newGroup napi_create_int32(commonEventDataWorkerData->env, commonEventDataWorkerData->newGroup, &value); - napi_set_named_property(commonEventDataWorkerData->env, result, "newGroup", value); + napi_set_named_property(commonEventDataWorkerData->env, result, "appUsageNewGroup", value); // userId napi_create_int32(commonEventDataWorkerData->env, commonEventDataWorkerData->userId, &value); @@ -76,7 +76,7 @@ napi_value SetBundleGroupChangedData(const CallbackReceiveDataWorker *commonEven commonEventDataWorkerData->env, commonEventDataWorkerData->bundleName.c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(commonEventDataWorkerData->env, result, "bundleName", value); BUNDLE_ACTIVE_LOGD( - "RegisterGroupCallBack oldGroup=%{public}d, newGroup=%{public}d, userId=%{public}d, " + "RegisterGroupCallBack appUsageOldGroup = %{public}d, appUsageNewGroup = %{public}d, userId=%{public}d, " "changeReason=%{public}d, bundleName=%{public}s", commonEventDataWorkerData->oldGroup, commonEventDataWorkerData->newGroup, commonEventDataWorkerData->userId, commonEventDataWorkerData->changeReason, commonEventDataWorkerData->bundleName.c_str()); diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js index 37027dc..1ee0731 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -479,12 +479,12 @@ describe("DeviceUsageStatisticsJsTest", function () { it("DeviceUsageStatisticsJsTest019", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest019---------------------------'); let onBundleGroupChanged = (err,res) =>{ - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack oldGroup is : ' + res.oldGroup); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack newGroup is : ' + res.newGroup); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack changeReason is : ' + res.newGroup); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack userId is : ' + res.userId); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack bundleName is : ' + res.bundleName); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback success.'); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack appUsageOldGroup is : ' + res.appUsageOldGroup); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack appUsageNewGroup is : ' + res.appUsageNewGroup); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack changeReason is : ' + res.changeReason); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack userId is : ' + res.userId); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack bundleName is : ' + res.bundleName); }; bundleState.registerGroupCallBack(onBundleGroupChanged).then( res => { console.info('BUNDLE_ACTIVE RegisterGroupCallBack promise success.'); @@ -509,11 +509,11 @@ describe("DeviceUsageStatisticsJsTest", function () { console.info('----------------------DeviceUsageStatisticsJsTest020---------------------------'); let onBundleGroupChanged = (err,res) =>{ console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack oldGroup is : ' + res.oldGroup); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack newGroup is : ' + res.newGroup); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack changeReason is : ' + res.newGroup); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack userId is : ' + res.userId); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack bundleName is : ' + res.bundleName); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack appUsageOldGroup is : ' + res.appUsageOldGroup); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack appUsageNewGroup is : ' + res.appUsageNewGroup); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack changeReason is : ' + res.changeReason); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack userId is : ' + res.userId); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack bundleName is : ' + res.bundleName); }; bundleState.registerGroupCallBack(onBundleGroupChanged, (err, res) => { if (err) { diff --git a/services/common/include/bundle_active_log.h b/services/common/include/bundle_active_log.h index 4a19c08..68f5282 100644 --- a/services/common/include/bundle_active_log.h +++ b/services/common/include/bundle_active_log.h @@ -22,7 +22,7 @@ namespace OHOS { namespace DeviceUsageStats { #ifndef LOG_TAG_DOMAIN_ID_BUNDLE_ACTIVE -#define LOG_TAG_DOMAIN_ID_BUNDLE_ACTIVE 0xD001701 +#define LOG_TAG_DOMAIN_ID_BUNDLE_ACTIVE 0xD001710 #endif #ifndef LOG_TAG_BUNDLE_ACTIVE diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 7c8142b..922bd7a 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -220,7 +220,7 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_RegisterGroupCallB { observer=std::make_shared(); if (!observer) { - BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack construct observer!------------------------------"); + BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack construct observer!"); } int32_t result = BundleActiveClient::GetInstance().RegisterGroupCallBack(observer.get()); EXPECT_EQ(result, DEFAULT_ERRCODE); -- Gitee From 212240102235de1570ff5c5579effb4066d51554 Mon Sep 17 00:00:00 2001 From: wyuanchao Date: Sat, 25 Jun 2022 17:30:38 +0800 Subject: [PATCH 80/83] =?UTF-8?q?=E4=BF=AE=E6=94=B9xts=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wyuanchao --- .../device_usage_statistics_jsunit.test.js | 156 ++++++------------ 1 file changed, 52 insertions(+), 104 deletions(-) diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js index 1ee0731..cb8ec05 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -58,14 +58,12 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.isIdleState(bundleName).then((res) => { console.info('BUNDLE_ACTIVE isIdleState promise success.'); expect(true).assertEqual(true); + done(); }).catch((err) => { console.info('BUNDLE_ACTIVE isIdleState promise failure.'); expect(false).assertEqual(true); - }); - - setTimeout(()=>{ done(); - }, 500); + }); }) /* @@ -81,15 +79,13 @@ describe("DeviceUsageStatisticsJsTest", function () { if (err) { console.info('BUNDLE_ACTIVE isIdleState callback failure.'); expect(false).assertEqual(true); + done(); } else { console.info('BUNDLE_ACTIVE isIdleState callback success.'); expect(true).assertEqual(true); + done(); } }); - - setTimeout(()=>{ - done(); - }, 500); }) /* @@ -105,14 +101,12 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.queryBundleActiveStates(beginTime, endTime).then((res) => { console.info('BUNDLE_ACTIVE queryBundleActiveStates promise success.'); expect(true).assertEqual(true); + done(); }).catch((err) => { console.info('BUNDLE_ACTIVE queryBundleActiveStates promise failure.'); expect(false).assertEqual(true); - }); - - setTimeout(()=>{ done(); - }, 500); + }); }) /* @@ -129,15 +123,13 @@ describe("DeviceUsageStatisticsJsTest", function () { if (err) { console.info('BUNDLE_ACTIVE queryBundleActiveStates callback failure.'); expect(false).assertEqual(true); + done(); } else { console.info('BUNDLE_ACTIVE queryBundleActiveStates callback success.'); expect(true).assertEqual(true); + done(); } }); - - setTimeout(()=>{ - done(); - }, 500); }) /* @@ -153,14 +145,12 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.queryBundleStateInfos(beginTime, endTime).then((res) => { console.info('BUNDLE_ACTIVE queryBundleStateInfos promise success.'); expect(true).assertEqual(true); + done(); }).catch((err) => { console.info('BUNDLE_ACTIVE queryBundleStateInfos promise failure.'); expect(false).assertEqual(true); - }); - - setTimeout(()=>{ done(); - }, 500); + }); }) /* @@ -177,15 +167,13 @@ describe("DeviceUsageStatisticsJsTest", function () { if (err) { console.info('BUNDLE_ACTIVE queryBundleStateInfos callback failure.'); expect(false).assertEqual(true); + done(); } else { console.info('BUNDLE_ACTIVE queryBundleStateInfos callback success.'); expect(true).assertEqual(true); + done(); } }); - - setTimeout(()=>{ - done(); - }, 500); }) /* @@ -201,14 +189,12 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.queryCurrentBundleActiveStates(beginTime, endTime).then((res) => { console.info('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.'); expect(true).assertEqual(true); + done(); }).catch((err) => { console.info('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failure.'); expect(false).assertEqual(true); - }); - - setTimeout(()=>{ done(); - }, 500); + }); }) /* @@ -225,15 +211,13 @@ describe("DeviceUsageStatisticsJsTest", function () { if (err) { console.info('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback failure.'); expect(false).assertEqual(true); + done(); } else { console.info('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback success.'); expect(true).assertEqual(true); + done(); } }); - - setTimeout(()=>{ - done(); - }, 500); }) /* @@ -250,14 +234,12 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.queryBundleStateInfoByInterval(intervalType, beginTime, endTime).then((res) => { console.info('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.'); expect(true).assertEqual(true); + done(); }).catch((err) => { console.info('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failure.'); expect(false).assertEqual(true); - }); - - setTimeout(()=>{ done(); - }, 500); + }); }) /* @@ -275,15 +257,13 @@ describe("DeviceUsageStatisticsJsTest", function () { if (err) { console.info('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback failure.'); expect(false).assertEqual(true); + done(); } else { console.info('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback success.'); expect(true).assertEqual(true); + done(); } }); - - setTimeout(()=>{ - done(); - }, 500); }) /* @@ -299,15 +279,13 @@ describe("DeviceUsageStatisticsJsTest", function () { if (err) { console.info('BUNDLE_ACTIVE getRecentlyUsedModules callback failure.'); expect(false).assertEqual(true); + done(); } else { console.info('BUNDLE_ACTIVE getRecentlyUsedModules callback success.'); expect(true).assertEqual(true); + done(); } }); - - setTimeout(()=>{ - done(); - }, 500); }) /* @@ -322,14 +300,12 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.getRecentlyUsedModules(maxNum).then((res) => { console.info('BUNDLE_ACTIVE getRecentlyUsedModules promise success.'); expect(true).assertEqual(true); + done(); }).catch((err) => { console.info('BUNDLE_ACTIVE getRecentlyUsedModules promise failure.'); expect(false).assertEqual(true); - }); - - setTimeout(()=>{ done(); - }, 500); + }); }) /* @@ -344,14 +320,12 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.queryAppUsagePriorityGroup(bundleName).then( res => { console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise success.'); expect(true).assertEqual(true); + done(); }).catch( err => { console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failure.'); expect(false).assertEqual(true); - }); - - setTimeout(()=>{ done(); - }, 500); + }); }) /* @@ -367,15 +341,13 @@ describe("DeviceUsageStatisticsJsTest", function () { if (err) { console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failure.'); expect(false).assertEqual(true); + done(); } else { console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback success.'); expect(true).assertEqual(true); + done(); } }); - - setTimeout(()=>{ - done(); - }, 500); }) /* @@ -389,14 +361,12 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.queryAppUsagePriorityGroup().then( res => { console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise success.'); expect(true).assertEqual(true); + done(); }).catch( err => { console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failure.'); expect(false).assertEqual(true); - }); - - setTimeout(()=>{ done(); - }, 500); + }); }) /* @@ -411,15 +381,13 @@ describe("DeviceUsageStatisticsJsTest", function () { if (err) { console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failure.'); expect(false).assertEqual(true); + done(); } else { console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback success.'); expect(true).assertEqual(true); + done(); } }); - - setTimeout(()=>{ - done(); - }, 500); }) /* @@ -435,14 +403,12 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.setBundleGroup(bundleName, newGroup).then( res => { console.info('BUNDLE_ACTIVE setBundleGroup promise success.'); expect(false).assertEqual(true); + done(); }).catch( err => { console.info('BUNDLE_ACTIVE setBundleGroup promise failure.'); expect(true).assertEqual(true); - }); - - setTimeout(()=>{ done(); - }, 500); + }); }) /* @@ -459,15 +425,13 @@ describe("DeviceUsageStatisticsJsTest", function () { if (err) { console.info('BUNDLE_ACTIVE setBundleGroup callback failure.'); expect(true).assertEqual(true); + done(); } else { console.info('BUNDLE_ACTIVE setBundleGroup callback success.'); expect(false).assertEqual(true); + done(); } }); - - setTimeout(()=>{ - done(); - }, 500); }) /* @@ -489,14 +453,12 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.registerGroupCallBack(onBundleGroupChanged).then( res => { console.info('BUNDLE_ACTIVE RegisterGroupCallBack promise success.'); expect(true).assertEqual(true); + done(); }).catch( err => { console.info('BUNDLE_ACTIVE RegisterGroupCallBack promise failure.'); expect(false).assertEqual(true); - }); - - setTimeout(()=>{ done(); - }, 500); + }); }) /* @@ -519,15 +481,13 @@ describe("DeviceUsageStatisticsJsTest", function () { if (err) { console.info('BUNDLE_ACTIVE registerGroupCallBack callback failure.'); expect(true).assertEqual(true); + done(); } else { console.info('BUNDLE_ACTIVE registerGroupCallBack callback success.'); expect(false).assertEqual(true); + done(); } }); - - setTimeout(()=>{ - done(); - }, 500); }) /* @@ -541,14 +501,12 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.unRegisterGroupCallBack().then( res => { console.info('BUNDLE_ACTIVE unRegisterGroupCallBack promise success.'); expect(true).assertEqual(true); + done(); }).catch( err => { console.info('BUNDLE_ACTIVE unRegisterGroupCallBack promise failure.'); expect(false).assertEqual(true); - }); - - setTimeout(()=>{ done(); - }, 500); + }); }) /* @@ -563,15 +521,13 @@ describe("DeviceUsageStatisticsJsTest", function () { if (err) { console.info('BUNDLE_ACTIVE unRegisterGroupCallBack callback failure.'); expect(true).assertEqual(true); + done(); } else { console.info('BUNDLE_ACTIVE unRegisterGroupCallBack callback success.'); expect(false).assertEqual(true); + done(); } }); - - setTimeout(()=>{ - done(); - }, 500); }) /* @@ -587,14 +543,12 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.queryBundleActiveEventStates(beginTime, endTime).then((res) => { console.info('BUNDLE_ACTIVE queryBundleActiveEventStates promise success.'); expect(true).assertEqual(true); + done(); }).catch((err) => { console.info('BUNDLE_ACTIVE queryBundleActiveEventStates promise failure.'); expect(false).assertEqual(true); - }); - - setTimeout(()=>{ done(); - }, 500); + }); }) /* @@ -611,15 +565,13 @@ describe("DeviceUsageStatisticsJsTest", function () { if (err) { console.info('BUNDLE_ACTIVE queryBundleActiveEventStates callback failure.'); expect(false).assertEqual(true); + done(); } else { console.info('BUNDLE_ACTIVE queryBundleActiveEventStates callback success.'); expect(true).assertEqual(true); + done(); } }); - - setTimeout(()=>{ - done(); - }, 500); }) /* @@ -635,14 +587,12 @@ describe("DeviceUsageStatisticsJsTest", function () { bundleState.queryAppNotificationNumber(beginTime, endTime).then((res) => { console.info('BUNDLE_ACTIVE queryAppNotificationNumber promise success.'); expect(true).assertEqual(true); + done(); }).catch((err) => { console.info('BUNDLE_ACTIVE queryAppNotificationNumber promise failure.'); expect(false).assertEqual(true); - }); - - setTimeout(()=>{ done(); - }, 500); + }); }) /* @@ -659,15 +609,13 @@ describe("DeviceUsageStatisticsJsTest", function () { if (err) { console.info('BUNDLE_ACTIVE queryAppNotificationNumber callback failure.'); expect(false).assertEqual(true); + done(); } else { console.info('BUNDLE_ACTIVE queryAppNotificationNumber callback success.'); expect(true).assertEqual(true); + done(); } }); - - setTimeout(()=>{ - done(); - }, 500); }) }) -- Gitee From d08c2c544485f779638be2a76ffce9dc539e7ae3 Mon Sep 17 00:00:00 2001 From: houdisheng Date: Tue, 28 Jun 2022 15:29:14 +0800 Subject: [PATCH 81/83] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E5=91=8A=E8=AD=A6=EF=BC=8C=E6=97=A0=E5=8A=9F=E8=83=BD=E5=BD=B1?= =?UTF-8?q?=E5=93=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: houdisheng --- services/packageusage/src/bundle_active_package_stats.cpp | 3 +++ services/packageusage/src/bundle_active_report_handler.cpp | 1 + 2 files changed, 4 insertions(+) diff --git a/services/packageusage/src/bundle_active_package_stats.cpp b/services/packageusage/src/bundle_active_package_stats.cpp index 142d763..9a76a21 100644 --- a/services/packageusage/src/bundle_active_package_stats.cpp +++ b/services/packageusage/src/bundle_active_package_stats.cpp @@ -118,6 +118,7 @@ void BundleActivePackageStats::UpdateAbility(const int64_t timeStamp, const int3 break; case BundleActiveEvent::ABILITY_STOP: abilities_.erase(abilityId); + break; default: break; } @@ -137,6 +138,7 @@ void BundleActivePackageStats::UpdateLongTimeTask(const std::string& longTimeTas switch (lastEventId) { case BundleActiveEvent::LONG_TIME_TASK_STARTTED: IncrementServiceTimeUsed(timeStamp); + break; default: break; } @@ -151,6 +153,7 @@ void BundleActivePackageStats::UpdateLongTimeTask(const std::string& longTimeTas break; case BundleActiveEvent::LONG_TIME_TASK_ENDED: longTimeTasks_.erase(longTimeTaskName); + break; default: break; } diff --git a/services/packageusage/src/bundle_active_report_handler.cpp b/services/packageusage/src/bundle_active_report_handler.cpp index 40b90fc..8a3b226 100644 --- a/services/packageusage/src/bundle_active_report_handler.cpp +++ b/services/packageusage/src/bundle_active_report_handler.cpp @@ -73,6 +73,7 @@ void BundleActiveReportHandler::ProcessEvent(const AppExecFwk::InnerEvent::Point auto ptrToHandlerobj = event->GetSharedObject(); BundleActiveReportHandlerObject tmpHandlerobj = *ptrToHandlerobj; bundleActiveCore_->OnUserSwitched(tmpHandlerobj.userId_); + break; } default: { break; -- Gitee From c3def2b7d8c69fac67127133952a5f1985933ff6 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Mon, 4 Jul 2022 16:55:38 +0800 Subject: [PATCH 82/83] =?UTF-8?q?=E6=9B=B4=E6=AD=A3bundle.json=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E4=B8=AD=E7=9A=84=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- bundle.json | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/bundle.json b/bundle.json index 6d1739a..aca71c9 100644 --- a/bundle.json +++ b/bundle.json @@ -23,24 +23,24 @@ "ram": "10240KB", "deps": { "components": [ - "libhilog", - "powermgr_client", - "cesfwk_innerkits", - "wantagent_innerkits", - "want", - "appexecfwk_base", - "appexecfwk_core", - "base", - "time_service", - "utils", - "ipc_core", - "system_ability_fwk", - "samgr_proxy", - "distributedschedsvr", - "libeventhandler", - "native_rdb", - "os_account_innerkits", - "libaccesstoken_sdk" + "bundle_framework", + "relational_store", + "safwk", + "common_event_service", + "os_account", + "ipc", + "access_token", + "ability_runtime", + "hiviewdfx_hilog_native", + "samgr_standard", + "utils_base", + "napi", + "startup_l2", + "ability_base", + "background_task_mgr", + "eventhandler", + "power_manager_native", + "time_native" ], "third_party": [ "googletest" ] }, -- Gitee From 0076fdd82ef7ff3d4c1625f0c2cfb913bf32f034 Mon Sep 17 00:00:00 2001 From: houdisheng Date: Thu, 7 Jul 2022 14:17:12 +0800 Subject: [PATCH 83/83] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=AE=BF=E9=97=AErdbst?= =?UTF-8?q?ore=E7=A9=BA=E6=8C=87=E9=92=88=E5=AF=BC=E8=87=B4=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1crash=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_usage_database.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp index 0035507..6cbef5a 100644 --- a/services/common/src/bundle_active_usage_database.cpp +++ b/services/common/src/bundle_active_usage_database.cpp @@ -787,6 +787,10 @@ pair BundleActiveUsageDatabase::GetDurationData() void BundleActiveUsageDatabase::FlushPackageInfo(uint32_t databaseType, const BundleActivePeriodStats &stats) { shared_ptr rdbStore = GetBundleActiveRdbStore(databaseType); + if (rdbStore == nullptr) { + BUNDLE_ACTIVE_LOGE("rdbStore is nullptr"); + return; + } string tableName = PACKAGE_LOG_TABLE + to_string(stats.beginTime_); int32_t changeRow = BUNDLE_ACTIVE_FAIL; int64_t outRowId = BUNDLE_ACTIVE_FAIL; -- Gitee