diff --git a/BUILD.gn b/BUILD.gn index 5a542017679de70b9e634a39e1ec2f3d6bde2da7..cf37d4bd1a33e1a6aee7b57d512f276d010cdd1d 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -41,6 +41,9 @@ ohos_shared_library("usagestatsinner") { "samgr_standard:samgr_proxy", "utils_base:utils", ] + + deps = [ ":usagestatservice" ] + part_name = "${device_usage_statistics_part_name}" subsystem_name = "resourceschedule" } @@ -52,7 +55,7 @@ ohos_prebuilt_etc("device_usage_statistics_service_init") { subsystem_name = "resourceschedule" } -ohos_shared_library("usagestatskit") { +ohos_shared_library("bundlestate") { sources = [ "frameworks/src/bundle_state_common.cpp", "frameworks/src/bundle_state_init.cpp", @@ -65,7 +68,10 @@ ohos_shared_library("usagestatskit") { "services/packageusage/include", ] - deps = [ "//foundation/resourceschedule/${device_usage_statistics_part_name}:usagestatsinner" ] + deps = [ + ":usagestatservice", + ":usagestatsinner", + ] external_deps = [ "dmsfwk_standard:zuri", @@ -87,6 +93,7 @@ ohos_shared_library("usagestatservice") { "services/common/src/bundle_active_binary_search.cpp", "services/common/src/bundle_active_continuous_task_observer.cpp", "services/common/src/bundle_active_core.cpp", + "services/common/src/bundle_active_log.cpp", "services/common/src/bundle_active_open_callback.cpp", "services/common/src/bundle_active_service.cpp", "services/common/src/bundle_active_shutdown_callback_proxy.cpp", diff --git a/bundle.json b/bundle.json index 1dcaacce264cc21f1c00c5c2372a39d378288136..014b937c47539a991fbf1ee2fb9efc57e3ba89d0 100644 --- a/bundle.json +++ b/bundle.json @@ -52,7 +52,7 @@ "//foundation/resourceschedule/device_usage_statistics:usagestatservice", "//foundation/resourceschedule/device_usage_statistics:device_usage_statistics_sa_profile", "//foundation/resourceschedule/device_usage_statistics:device_usage_statistics_service_init", - "//foundation/resourceschedule/device_usage_statistics:usagestatskit" + "//foundation/resourceschedule/device_usage_statistics:bundlestate" ], "inner_kits": [ { diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp index b4908dca75b80f353ca56e4c4cb8e3d0ef00ba73..1beaff661e6df951717a28869afabec891d74600 100644 --- a/frameworks/src/bundle_state_common.cpp +++ b/frameworks/src/bundle_state_common.cpp @@ -109,28 +109,32 @@ void BundleStateCommon::GetBundleStateInfoByIntervalForResult( } } -void BundleStateCommon::GetBundleStateInfoForResult( - napi_env env, const std::vector &packageStats, napi_value result) +void BundleStateCommon::GetBundleStateInfoForResult(napi_env env, + const std::shared_ptr> &packageStats, napi_value result) { - for (const auto &item : packageStats) { + if (packageStats == nullptr) { + BUNDLE_ACTIVE_LOGE("PackageStats is invalid"); + return; + } + for (const auto &item : *packageStats) { napi_value packageObject = nullptr; NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &packageObject)); napi_value bundleName = nullptr; NAPI_CALL_RETURN_VOID( - env, napi_create_string_utf8(env, item.bundleName_.c_str(), NAPI_AUTO_LENGTH, &bundleName)); + env, napi_create_string_utf8(env, item.second.bundleName_.c_str(), NAPI_AUTO_LENGTH, &bundleName)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "bundleName", bundleName)); napi_value abilityPrevAccessTime = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.lastTimeUsed_, &abilityPrevAccessTime)); + NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.second.lastTimeUsed_, &abilityPrevAccessTime)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityPrevAccessTime", abilityPrevAccessTime)); napi_value abilityInFgTotalTime = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.totalInFrontTime_, &abilityInFgTotalTime)); + NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.second.totalInFrontTime_, &abilityInFgTotalTime)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, packageObject, "abilityInFgTotalTime", abilityInFgTotalTime)); - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, item.bundleName_.c_str(), packageObject)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, result, item.first.c_str(), packageObject)); } } @@ -236,5 +240,42 @@ void BundleStateCommon::SettingCallbackPromiseInfo( info.isCallback = false; } } + +std::shared_ptr> BundleStateCommon::GetPackageStats( + int64_t &beginTime, int64_t &endTime) +{ + std::vector packageStats = + BundleActiveClient::GetInstance().QueryPackageStats(INTERVAL_TYPE_DEFAULT, beginTime, endTime); + std::shared_ptr> mergedPackageStats = + std::make_shared>(); + if (packageStats.empty()) { + return nullptr; + } + for (auto packageStat : packageStats) { + std::map::iterator iter = + mergedPackageStats->find(packageStat.bundleName_); + if (iter != mergedPackageStats->end()) { + MergePackageStats(iter->second, packageStat); + } else { + mergedPackageStats-> + insert(std::pair(packageStat.bundleName_, packageStat)); + } + } + return mergedPackageStats; +} + +void BundleStateCommon::MergePackageStats(BundleActivePackageStats &left, const BundleActivePackageStats &right) +{ + if (left.bundleName_ != right.bundleName_) { + BUNDLE_ACTIVE_LOGE("Merge package stats failed, existing packageName : %{public}s," + " new packageName : %{public}s,", left.bundleName_.c_str(), right.bundleName_.c_str()); + return; + } + left.lastTimeUsed_ = std::max(left.lastTimeUsed_, right.lastTimeUsed_); + left.lastContiniousTaskUsed_ = std::max(left.lastContiniousTaskUsed_, right.lastContiniousTaskUsed_); + left.totalInFrontTime_ += right.totalInFrontTime_; + left.totalContiniousTaskUsedTime_ += right.totalContiniousTaskUsedTime_; + left.bundleStartedCount_ += right.bundleStartedCount_; +} } // namespace DeviceUsageStats } // namespace OHOS \ No newline at end of file diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index a00cded8a064c498bdf34f8a77a6308783528747..00fd1aa3dc5813da329c39aea161ee54e7c452ef 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -17,32 +17,30 @@ #include "bundle_state_common.h" #include "bundle_active_log.h" -#include "bundle_active_client.h" #include "bundle_state_data.h" -#include "bundle_state_query.h" namespace OHOS { namespace DeviceUsageStats { -static const int32_t Is_Idle_State_MIN_PARAMS = 1; -static const int32_t Is_Idle_State_PARAMS = 2; -static const int32_t Priority_Group_MIN_PARAMS = 0; -static const int32_t Priority_Group_PARAMS = 1; -static const int32_t States_MIN_PARAMS = 2; -static const int32_t States_PARAMS = 3; -static const int32_t App_Usage_MIN_PARAMS_BY_INTERVAL = 3; -static const int32_t App_Usage_PARAMS_BY_INTERVAL = 4; -static const int32_t App_Usage_MIN_PARAMS = 2; -static const int32_t App_Usage_PARAMS = 3; -static const int32_t SECOND_ARG = 2; -static const int32_t THIRD_ARG = 3; +const u_int32_t IS_IDLE_STATE_MIN_PARAMS = 1; +const u_int32_t IS_IDLE_STATE_PARAMS = 2; +const u_int32_t PRIORITY_GROUP_MIN_PARAMS = 0; +const u_int32_t PRIORITY_GROUP_PARAMS = 1; +const u_int32_t STATES_MIN_PARAMS = 2; +const u_int32_t STATES_PARAMS = 3; +const u_int32_t APP_USAGE_MIN_PARAMS_BY_INTERVAL = 3; +const u_int32_t APP_USAGE_PARAMS_BY_INTERVAL = 4; +const u_int32_t APP_USAGE_MIN_PARAMS = 2; +const u_int32_t APP_USAGE_PARAMS = 3; +const u_int32_t SECOND_ARG = 2; +const u_int32_t THIRD_ARG = 3; napi_value ParseIsIdleStateParameters(const napi_env &env, const napi_callback_info &info, IsIdleStateParamsInfo ¶ms) { - size_t argc = Is_Idle_State_PARAMS; - napi_value argv[Is_Idle_State_PARAMS] = {nullptr}; + size_t argc = IS_IDLE_STATE_PARAMS; + napi_value argv[IS_IDLE_STATE_PARAMS] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_ASSERT(env, argc == Is_Idle_State_MIN_PARAMS || argc == Is_Idle_State_PARAMS, + NAPI_ASSERT(env, argc == IS_IDLE_STATE_MIN_PARAMS || argc == IS_IDLE_STATE_PARAMS, "invalid number of parameters"); // argv[0] : bundleName @@ -58,7 +56,7 @@ napi_value ParseIsIdleStateParameters(const napi_env &env, const napi_callback_i } // argv[1]: callback - if (argc == Is_Idle_State_PARAMS) { + if (argc == IS_IDLE_STATE_PARAMS) { napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "ParseIsIdleStateParameters invalid parameter type. " @@ -133,14 +131,14 @@ napi_value IsIdleState(napi_env env, napi_callback_info info) napi_value ParsePriorityGroupParameters(const napi_env &env, const napi_callback_info &info, PriorityGroupParamsInfo ¶ms) { - size_t argc = Priority_Group_PARAMS; - napi_value argv[Priority_Group_PARAMS] = {nullptr}; + 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, + NAPI_ASSERT(env, argc == PRIORITY_GROUP_MIN_PARAMS || argc == PRIORITY_GROUP_PARAMS, "invalid number of parameters"); // argv[0]: callback - if (argc == Priority_Group_PARAMS) { + if (argc == PRIORITY_GROUP_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. " @@ -211,10 +209,10 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) napi_value ParseStatesParameters(const napi_env &env, const napi_callback_info &info, StatesParamsInfo ¶ms) { - size_t argc = States_PARAMS; - napi_value argv[States_PARAMS] = {nullptr}; + size_t argc = STATES_PARAMS; + napi_value argv[STATES_PARAMS] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_ASSERT(env, argc == States_MIN_PARAMS || argc == States_PARAMS, + NAPI_ASSERT(env, argc == STATES_MIN_PARAMS || argc == STATES_PARAMS, "invalid number of parameters"); // argv[0] : beginTime @@ -230,7 +228,7 @@ napi_value ParseStatesParameters(const napi_env &env, const napi_callback_info & } // argv[SECOND_ARG]: callback - if (argc == States_PARAMS) { + if (argc == STATES_PARAMS) { napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[SECOND_ARG], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "ParseStatesParameters invalid parameter type. " @@ -379,10 +377,10 @@ napi_value QueryBundleActiveStates(napi_env env, napi_callback_info info) napi_value ParseAppUsageParametersByInterval(const napi_env &env, const napi_callback_info &info, AppUsageParamsByIntervalInfo ¶ms) { - size_t argc = App_Usage_PARAMS_BY_INTERVAL; - napi_value argv[App_Usage_PARAMS_BY_INTERVAL] = {nullptr}; + size_t argc = APP_USAGE_PARAMS_BY_INTERVAL; + napi_value argv[APP_USAGE_PARAMS_BY_INTERVAL] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_ASSERT(env, argc == App_Usage_MIN_PARAMS_BY_INTERVAL || argc == App_Usage_PARAMS_BY_INTERVAL, + NAPI_ASSERT(env, argc == APP_USAGE_MIN_PARAMS_BY_INTERVAL || argc == APP_USAGE_PARAMS_BY_INTERVAL, "invalid number of parameters"); // argv[0] : intervalType @@ -404,7 +402,7 @@ napi_value ParseAppUsageParametersByInterval(const napi_env &env, const napi_cal } // argv[THIRD_ARG]: callback - if (argc == App_Usage_PARAMS_BY_INTERVAL) { + if (argc == APP_USAGE_PARAMS_BY_INTERVAL) { napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[THIRD_ARG], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "ParseAppUsageParametersByInterval invalid parameter type. " @@ -487,10 +485,10 @@ napi_value QueryBundleStateInfoByInterval(napi_env env, napi_callback_info info) napi_value ParseAppUsageParameters(const napi_env &env, const napi_callback_info &info, AppUsageParamsInfo ¶ms) { - size_t argc = App_Usage_PARAMS; - napi_value argv[App_Usage_PARAMS] = {nullptr}; + size_t argc = APP_USAGE_PARAMS; + napi_value argv[APP_USAGE_PARAMS] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_ASSERT(env, argc == App_Usage_MIN_PARAMS || argc == App_Usage_PARAMS, + NAPI_ASSERT(env, argc == APP_USAGE_MIN_PARAMS || argc == APP_USAGE_PARAMS, "invalid number of parameters"); // argv[0] : beginTime @@ -506,7 +504,7 @@ napi_value ParseAppUsageParameters(const napi_env &env, const napi_callback_info } // argv[SECOND_ARG]: callback - if (argc == App_Usage_PARAMS) { + if (argc == APP_USAGE_PARAMS) { napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[SECOND_ARG], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "ParseAppUsageParameters invalid parameter type. " @@ -522,7 +520,6 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) if (ParseAppUsageParameters(env, info, params) == nullptr) { return BundleStateCommon::JSParaError(env, params.callback); } - napi_value promise = nullptr; AsyncCallbackInfoAppUsage *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoAppUsage {.env = env, .asyncWork = nullptr}; @@ -536,10 +533,8 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos asyncCallbackInfo->endTime: %{public}lld", asyncCallbackInfo->endTime); BundleStateCommon::SettingCallbackPromiseInfo(env, params.callback, asyncCallbackInfo->info, promise); - napi_value resourceName = nullptr; napi_create_string_latin1(env, "QueryBundleStateInfos", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, nullptr, resourceName, @@ -548,10 +543,9 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) AsyncCallbackInfoAppUsage *asyncCallbackInfo = (AsyncCallbackInfoAppUsage *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->packageStats = - BundleActiveClient::GetInstance().QueryPackageStats(INTERVAL_TYPE_DEFAULT, - asyncCallbackInfo->beginTime, asyncCallbackInfo->endTime); + BundleStateCommon::GetPackageStats(asyncCallbackInfo->beginTime, asyncCallbackInfo->endTime); } else { - BUNDLE_ACTIVE_LOGE("QueryBundleStateInfos, asyncCallbackInfo == nullptr"); + BUNDLE_ACTIVE_LOGE("QueryBundleStateInfos asyncCallbackInfo == nullptr"); } BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos worker pool thread execute end."); }, @@ -559,14 +553,12 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) AsyncCallbackInfoAppUsage *asyncCallbackInfo = (AsyncCallbackInfoAppUsage *)data; if (asyncCallbackInfo != nullptr) { napi_value result = nullptr; - napi_create_array(env, &result); + napi_create_object(env, &result); BundleStateCommon::GetBundleStateInfoForResult(env, asyncCallbackInfo->packageStats, result); BundleStateCommon::GetCallbackPromiseResult(env, asyncCallbackInfo->info, result); - if (asyncCallbackInfo->info.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->info.callback); } - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; asyncCallbackInfo = nullptr; @@ -574,9 +566,7 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) }, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); - if (asyncCallbackInfo->info.isCallback) { return BundleStateCommon::NapiGetNull(env); } else { diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index 068794f08f8d3a55148f756c3c173d4647faba60..a550088fb9f46ef5316bbc352168139d6020146a 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -51,7 +51,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("BundleActiveProxy::IsBundleIdle result is %{public}d", result); + BUNDLE_ACTIVE_LOGI("result is %{public}d", result); return result; } @@ -78,8 +78,8 @@ std::vector BundleActiveProxy::QueryPackageStats(const } result.push_back(*tmp); } - for (int i = 0; i < result.size(); i++) { - BUNDLE_ACTIVE_LOGI("BundleActiveProxy::QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, " + for (uint32_t i = 0; i < result.size(); i++) { + BUNDLE_ACTIVE_LOGI("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(), result[i].lastTimeUsed_, result[i].lastContiniousTaskUsed_, @@ -109,8 +109,8 @@ std::vector BundleActiveProxy::QueryEvents(const int64_t begi } result.push_back(*tmp); } - for (int i = 0; i < result.size(); i++) { - BUNDLE_ACTIVE_LOGI("BundleActiveProxy::QueryEvents event id is %{public}d, bundle name is %{public}s, " + for (uint32_t i = 0; i < result.size(); i++) { + BUNDLE_ACTIVE_LOGI("QueryEvents event id is %{public}d, bundle name is %{public}s, " "time stamp is %{public}lld", result[i].eventId_, result[i].bundleName_.c_str(), result[i].timeStamp_); } return result; @@ -153,8 +153,8 @@ std::vector BundleActiveProxy::QueryCurrentPackageStat } result.push_back(*tmp); } - for (int i = 0; i < result.size(); i++) { - BUNDLE_ACTIVE_LOGI("BundleActiveProxy::QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, " + for (uint32_t i = 0; i < result.size(); i++) { + BUNDLE_ACTIVE_LOGI("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(), result[i].lastTimeUsed_, result[i].lastContiniousTaskUsed_, @@ -184,8 +184,9 @@ std::vector BundleActiveProxy::QueryCurrentEvents(const int64 } result.push_back(*tmp); } - for (int i = 0; i < result.size(); i++) { - BUNDLE_ACTIVE_LOGI("event id is %{public}d, bundle name is %{public}s, time stamp is %{public}lld", + for (uint32_t i = 0; i < result.size(); i++) { + BUNDLE_ACTIVE_LOGI("QueryCurrentEvents event id is %{public}d, bundle name is %{public}s," + "time stamp is %{public}lld", result[i].eventId_, result[i].bundleName_.c_str(), result[i].timeStamp_); } return result; @@ -201,7 +202,7 @@ int BundleActiveProxy::QueryPackageGroup() } Remote() -> SendRequest(QUERY_BUNDLE_GROUP, data, reply, option); int32_t packageGroup = reply.ReadInt32(); - BUNDLE_ACTIVE_LOGI("BundleActiveProxy::QueryPackageGroup result is %{public}d", packageGroup); + BUNDLE_ACTIVE_LOGI("QueryPackageGroup result is %{public}d", packageGroup); return packageGroup; } } diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts index e28bf6ccf5a6c0ef29c37cb7bb20b0f5f26b2119..eb724fd056044215e00f8d7b64e79b1b2906762e 100644 --- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts +++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts @@ -25,14 +25,14 @@ import { AsyncCallback } from './basic'; * then returns it to you. * * @since 7 - * @devices phone, tablet, tv, wearable, car */ declare namespace bundleState { /** * @since 7 - * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App - * @devices phone, tablet, tv, wearable, car + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. + * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @systemapi Hide this for inner system use. */ interface BundleStateInfo { /** @@ -83,8 +83,9 @@ declare namespace bundleState { * The bundle name of both objects must be the same. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App - * @devices phone, tablet, tv, wearable, car + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. + * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @systemapi Hide this for inner system use. * @param toMerge Indicates the {@link BundleActiveInfo} object to merge. * if the bundle names of the two {@link BundleActiveInfo} objects are different. */ @@ -93,8 +94,9 @@ declare namespace bundleState { /** * @since 7 - * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App - * @devices phone, tablet, tv, wearable, car + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. + * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @systemapi Hide this for inner system use. */ interface BundleActiveState { /** @@ -127,8 +129,9 @@ declare namespace bundleState { * Checks whether the application with a specified bundle name is in the idle state. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup - * @devices phone, tablet, tv, wearable, car + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup. + * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @systemapi Hide this for inner system use. * @param bundleName Indicates the bundle name of the application to query. * @return Returns {@code true} if the application is idle in a particular period; * returns {@code false} otherwise. The time range of the particular period is defined by the system, @@ -144,8 +147,9 @@ declare namespace bundleState { * for example, restricting the running of background tasks.

* * @since 7 - * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup - * @devices phone, tablet, tv, wearable, car + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup. + * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @systemapi Hide this for inner system use. * @return Returns the usage priority group of the calling application. */ function queryAppUsagePriorityGroup(callback: AsyncCallback): void; @@ -153,8 +157,9 @@ declare namespace bundleState { /** * @since 7 - * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App - * @devices phone, tablet, tv, wearable, car + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. + * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @systemapi Hide this for inner system use. */ interface BundleActiveInfoResponse { [key: string]: BundleStateInfo; @@ -166,8 +171,9 @@ declare namespace bundleState { *

This method queries usage information at the {@link #BY_OPTIMIZED} interval by default.

* * @since 7 - * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App - * @devices phone, tablet, tv, wearable, car + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. + * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @systemapi Hide this for inner system use. * @param begin Indicates the start time of the query period, in milliseconds. * @param end Indicates the end time of the query period, in milliseconds. * @return Returns the {@link BundleActiveInfoResponse} objects containing the usage information about each bundle. @@ -179,8 +185,9 @@ declare namespace bundleState { * Declares interval type. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App - * @devices phone, tablet, tv, wearable, car + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. + * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @systemapi Hide this for inner system use. */ export enum IntervalType { /** @@ -213,8 +220,9 @@ declare namespace bundleState { * Queries usage information about each bundle within a specified period at a specified interval. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App - * @devices phone, tablet, tv, wearable, car + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. + * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @systemapi Hide this for inner system use. * @param byInterval Indicates the interval at which the usage statistics are queried. * The value can be {@link #BY_OPTIMIZED}, {@link #BY_DAILY}, * {@link #BY_WEEKLY}, {@link #BY_MONTHLY}, or {@link #BY_ANNUALLY}. @@ -229,8 +237,9 @@ declare namespace bundleState { * Queries state data of all bundles within a specified period identified by the start and end time. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App - * @devices phone, tablet, tv, wearable, car + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. + * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @systemapi Hide this for inner system use. * @param begin Indicates the start time of the query period, in milliseconds. * @param end Indicates the end time of the query period, in milliseconds. * @return Returns the list of {@link BundleActiveState} objects containing the state data of all bundles. @@ -242,8 +251,9 @@ declare namespace bundleState { * Queries state data of the current bundle within a specified period. * * @since 7 - * @sysCap SystemCapability.ResourceSchedule.UsageStatistics.App - * @devices phone, tablet, tv, wearable, car + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. + * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @systemapi Hide this for inner system use. * @param begin Indicates the start time of the query period, in milliseconds. * @param end Indicates the end time of the query period, in milliseconds. * @return Returns the {@link BundleActiveState} object Array containing the state data of the current bundle. diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h index ce44bee4a78d0dfec0813df4731fb09f5b71c4a0..5e8daf4642d1195c4b1037b9515b09ffcf867404 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h @@ -16,11 +16,11 @@ #ifndef FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_COMMON_H #define FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_COMMON_H -#include - +#include "bundle_active_client.h" +#include "bundle_state_data.h" +#include "bundle_state_query.h" #include "napi/native_api.h" #include "napi/native_node_api.h" -#include "bundle_state_data.h" namespace OHOS { namespace DeviceUsageStats { @@ -50,8 +50,8 @@ public: static void GetBundleStateInfoByIntervalForResult( napi_env env, const std::vector &packageStats, napi_value result); - static void GetBundleStateInfoForResult( - napi_env env, const std::vector &packageStats, napi_value result); + static void GetBundleStateInfoForResult(napi_env env, + const std::shared_ptr> &packageStats, napi_value result); static void SetPromiseInfo(const napi_env &env, const napi_deferred &deferred, const napi_value &result); @@ -62,6 +62,11 @@ public: static napi_value GetInt64NumberValue(const napi_env &env, const napi_value &value, int64_t &result); static napi_value GetInt32NumberValue(const napi_env &env, const napi_value &value, int32_t &result); + + static std::shared_ptr> GetPackageStats( + int64_t &beginTime, int64_t &endTime); + + static void MergePackageStats(BundleActivePackageStats &left, const BundleActivePackageStats &right); }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h index a44f85b3c6b3bb333ad492e3ff68e36c25a52e54..c854436457ebebaa61efb2b6335b29ef5ded1a4b 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h @@ -16,6 +16,7 @@ #ifndef FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_DATA_H #define FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_DATA_H +#include #include #include "napi/native_api.h" @@ -85,7 +86,7 @@ struct AsyncCallbackInfoAppUsage { napi_async_work asyncWork = nullptr; int64_t beginTime; int64_t endTime; - std::vector packageStats; + std::shared_ptr> packageStats; CallbackPromiseInfo info; }; diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_init.h b/interfaces/kits/bundlestats/napi/include/bundle_state_init.h index 045d7bb9eb7cc6080286972913d8b939c3b25ee4..7547c2a40376c489f9d621ed81ed566302668efa 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_init.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_init.h @@ -40,7 +40,7 @@ napi_module _module = { .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = BundleStateInit, - .nm_modname = "usagestatskit", + .nm_modname = "bundleState", .nm_priv = ((void *)0), .reserved = {0} }; diff --git a/services/common/include/bundle_active_constant.h b/services/common/include/bundle_active_constant.h index d3caa42ea5c57ae4c1616808233a57b7a0815a70..2e3bd8c1bfed63c7b52c341cefd83c765f409b31 100644 --- a/services/common/include/bundle_active_constant.h +++ b/services/common/include/bundle_active_constant.h @@ -59,7 +59,7 @@ const int BOOT_BASED_DURATION_COLUMN_INDEX = 0; const int SCREEN_ON_DURATION_COLUMN_INDEX = 1; const int DURATION_FLAG_COLUMN_INDEX = 2; const int TWO_SECONDS = 2 * 1000; -const int64_t SIX_DAY_IN_MILLIS_MAX = 6 * 24 * 60 * 60 * 1000; +const int64_t SIX_DAY_IN_MILLIS_MAX = 1 * 6 * 10 * 60 * 1000; const int64_t LAST_TIME_IN_MILLIS_MIN = 0; const int64_t EVENT_TIME_IN_MILLIS_MIN = 0; const int64_t EVENT_BEGIN_TIME_INITIAL_VALUE = -1; diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 1956dc510ccb8fa3d437a4709fe7b1d93bf7c05e..5464548fdc4cb98683a4719612120e3afe075c5f 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -36,7 +36,7 @@ public: BundleActiveEvent event_; int userId_; std::string bundleName_; - BundleActiveReportHandlerObject() {}; + BundleActiveReportHandlerObject(); BundleActiveReportHandlerObject(const BundleActiveReportHandlerObject& orig); ~BundleActiveReportHandlerObject() {}; }; @@ -60,7 +60,7 @@ public: /* * function: OnStatsChanged, report flush to disk, end_of_day event to service. */ - void OnStatsChanged() override; + void OnStatsChanged(const int userId) override; /* * function: OnStatsChanged, when device reboot after more than one day, BundleActiveUserService * will use it to flush group info. @@ -91,10 +91,10 @@ public: * function: SetHandler, BundleActiveService call it to set event report handler */ void SetHandler(const std::shared_ptr& reportHandler); - // flush database. - void RestoreToDatabase(); - // flush database - void RestoreToDatabaseLocked(); + // flush database for one user data + void RestoreToDatabase(const int userId); + // flush database for one user data + void RestoreToDatabaseLocked(const int userId); // called when device shutdown, update the in-memory stat and flush the database. void ShutDown(); // query the package stat for calling user. @@ -108,7 +108,7 @@ public: // query the app group for calling app. int QueryPackageGroup(const int userId, const std::string bundleName); // get the wall time and check if the wall time is changed. - int64_t CheckTimeChangeAndGetWallTime(); + int64_t CheckTimeChangeAndGetWallTime(int userId = 0); // convert event timestamp from boot based time to wall time. void ConvertToSystemTimeLocked(BundleActiveEvent& event); // get or create BundleActiveUserService object for specifice user. @@ -122,6 +122,7 @@ public: void GetAllActiveUser(std::vector &osAccountInfos); // when service stop, call it to unregister commen event and shutdown call back. void UnRegisterSubscriber(); + int64_t GetSystemTimeMs(); private: static const int64_t FLUSH_INTERVAL = TWO_MINUTE; @@ -138,6 +139,7 @@ private: std::map> userStatServices_; void RegisterSubscriber(); std::shared_ptr commonEventSubscriber_; + void RestoreAllData(); }; } } diff --git a/services/common/include/bundle_active_log.h b/services/common/include/bundle_active_log.h index 3a24733e5bdcb7d4b3e7a591a94caeb327f7a355..d4bc93a37ad4c9949d94b738d40bb8e5d4c225c7 100644 --- a/services/common/include/bundle_active_log.h +++ b/services/common/include/bundle_active_log.h @@ -16,10 +16,18 @@ #ifndef BUNDLE_ACTIVE_LOG_H #define BUNDLE_ACTIVE_LOG_H +#include #include "hilog/log.h" -#define LOG_TAG_BUNDLE_ACTIVE "BUNDLE_ACTIVE" +namespace OHOS { +namespace DeviceUsageStats { +#ifndef LOG_TAG_DOMAIN_ID_BUNDLE_ACTIVE #define LOG_TAG_DOMAIN_ID_BUNDLE_ACTIVE 0xD001701 +#endif + +#ifndef LOG_TAG_BUNDLE_ACTIVE +#define LOG_TAG_BUNDLE_ACTIVE "BUNDLE_ACTIVE" +#endif static constexpr OHOS::HiviewDFX::HiLogLabel BUNDLE_ACTIVE_LOG_LABEL = { LOG_CORE, @@ -27,10 +35,46 @@ static constexpr OHOS::HiviewDFX::HiLogLabel BUNDLE_ACTIVE_LOG_LABEL = { LOG_TAG_BUNDLE_ACTIVE }; -#define BUNDLE_ACTIVE_LOGF(...) (void)OHOS::HiviewDFX::HiLog::Fatal(BUNDLE_ACTIVE_LOG_LABEL, __VA_ARGS__) -#define BUNDLE_ACTIVE_LOGE(...) (void)OHOS::HiviewDFX::HiLog::Error(BUNDLE_ACTIVE_LOG_LABEL, __VA_ARGS__) -#define BUNDLE_ACTIVE_LOGW(...) (void)OHOS::HiviewDFX::HiLog::Warn(BUNDLE_ACTIVE_LOG_LABEL, __VA_ARGS__) -#define BUNDLE_ACTIVE_LOGI(...) (void)OHOS::HiviewDFX::HiLog::Info(BUNDLE_ACTIVE_LOG_LABEL, __VA_ARGS__) -#define BUNDLE_ACTIVE_LOGD(...) (void)OHOS::HiviewDFX::HiLog::Debug(BUNDLE_ACTIVE_LOG_LABEL, __VA_ARGS__) +enum class BundleActiveLogLevel : uint8_t { DEBUG = 0, INFO, WARN, ERROR, FATAL }; + +class BundleActiveLog { +public: + BundleActiveLog() = delete; + ~BundleActiveLog() = delete; + + static bool JudgeValidLevel(const BundleActiveLogLevel &level); + + static void SetLogLevel(const BundleActiveLogLevel &level) + { + logLevel_ = level; + } + + static const BundleActiveLogLevel &GetLogLevel() + { + return logLevel_; + } + + static std::string GetCurrFileName(const char *str); + +private: + static BundleActiveLogLevel logLevel_; +}; + +#define 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, \ + BundleActiveLog::GetCurrFileName(__FILE__).c_str(), \ + __FUNCTION__, \ + __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__) +} // namespace DeviceUsageStats +} // namespace OHOS -#endif \ No newline at end of file +#endif // BUNDLE_ACTIVE_LOG_H \ No newline at end of file diff --git a/services/common/include/bundle_active_usage_database.h b/services/common/include/bundle_active_usage_database.h index 345a247a40e23f41d44734ef54a719a3c0c13148..f52a995c3d5046667ff34c34aa071c930d259774 100644 --- a/services/common/include/bundle_active_usage_database.h +++ b/services/common/include/bundle_active_usage_database.h @@ -81,6 +81,7 @@ private: void DeleteUninstalledInfo(const int userId, const std::string& bundleName, const std::string& tableName, unsigned int databaseType); int32_t CreateDatabasePath(); + int64_t GetSystemTimeMs(); private: std::vector databaseFiles_; diff --git a/services/common/src/bundle_active_app_state_obsever.cpp b/services/common/src/bundle_active_app_state_obsever.cpp index cf613c603e7959b4bb3655f184412fa940b4ea1b..1bebdd57dac5cca5056e80ec05bfed8759e2b790 100644 --- a/services/common/src/bundle_active_app_state_obsever.cpp +++ b/services/common/src/bundle_active_app_state_obsever.cpp @@ -24,7 +24,7 @@ namespace DeviceUsageStats { void BundleActiveAppStateObserver::Init(const std::shared_ptr& reportHandler) { if (reportHandler != nullptr) { - BUNDLE_ACTIVE_LOGI("BundleActiveAppStateObserver::Init report handler is not null, init success"); + BUNDLE_ACTIVE_LOGI("Init report handler is not null, init success"); reportHandler_ = reportHandler; } } diff --git a/services/common/src/bundle_active_binary_search.cpp b/services/common/src/bundle_active_binary_search.cpp index 9b284d8426f62c1e2ce3ed70ab6a62b9c1a011cd..f16cf9348a07a1511d11350ca056d0064d28dc03 100644 --- a/services/common/src/bundle_active_binary_search.cpp +++ b/services/common/src/bundle_active_binary_search.cpp @@ -29,7 +29,7 @@ BundleActiveBinarySearch::~BundleActiveBinarySearch() int32_t BundleActiveBinarySearch::BinarySearch(const std::vector &tableNameArray, int64_t targetValue) { int32_t low = 0; - int32_t high = tableNameArray.size() - 1; + int32_t high = static_cast(tableNameArray.size() - 1); while (low <= high) { int32_t mid = (low + high) >> 1; int64_t midValue = tableNameArray.at(mid); @@ -41,7 +41,7 @@ int32_t BundleActiveBinarySearch::BinarySearch(const std::vector &table return mid; } } - return ~low; + return -1; } } } \ 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 5f09345ebfd4174517bbd07d0b47d6d3450f5fe7..842ebfa6cd2964d94d8c162d0b15e8e16c4e0ee8 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -23,6 +23,12 @@ namespace OHOS { namespace DeviceUsageStats { +BundleActiveReportHandlerObject::BundleActiveReportHandlerObject() +{ + userId_ = -1; + bundleName_ = ""; +} + BundleActiveReportHandlerObject::BundleActiveReportHandlerObject(const BundleActiveReportHandlerObject& orig) { event_.bundleName_ = orig.event_.bundleName_; @@ -30,7 +36,6 @@ BundleActiveReportHandlerObject::BundleActiveReportHandlerObject(const BundleAct event_.abilityId_ = orig.event_.abilityId_; event_.timeStamp_ = orig.event_.timeStamp_; event_.eventId_ = orig.event_.eventId_; - event_.isidle_ = orig.event_.isidle_; event_.continuousTaskAbilityName_ = orig.event_.continuousTaskAbilityName_; userId_ = orig.userId_; bundleName_ = orig.bundleName_; @@ -38,6 +43,8 @@ BundleActiveReportHandlerObject::BundleActiveReportHandlerObject(const BundleAct BundleActiveCore::BundleActiveCore() { + systemTimeShot_ = -1; + realTimeShot_ = -1; } BundleActiveCore::~BundleActiveCore() @@ -48,14 +55,14 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da { std::lock_guard lock(mutex_); std::string action = data.GetWant().GetAction(); - BUNDLE_ACTIVE_LOGI("BundleActiveCommonEventSubscriber::OnReceiveEvent action is %{public}s", action.c_str()); + BUNDLE_ACTIVE_LOGI("OnReceiveEvent action is %{public}s", action.c_str()); auto want = data.GetWant(); if (action == CommonEventSupport::COMMON_EVENT_SCREEN_OFF || action == CommonEventSupport::COMMON_EVENT_SCREEN_ON) { if (!activeGroupController_.expired()) { sptr timer = MiscServices::TimeServiceClient::GetInstance(); bool isScreenOn = activeGroupController_.lock()->IsScreenOn(); - BUNDLE_ACTIVE_LOGI("BundleActiveCommonEventSubscriber::OnReceiveEvent Screen state changed " + BUNDLE_ACTIVE_LOGI("OnReceiveEvent Screen state changed " "received, screen state chante to %{public}d", isScreenOn); activeGroupController_.lock()->OnScreenChanged(isScreenOn, timer->GetBootTimeMs()); } @@ -72,8 +79,7 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da } } else if (action == CommonEventSupport::COMMON_EVENT_USER_ADDED) { int32_t userId = data.GetCode(); - BUNDLE_ACTIVE_LOGI("BundleActiveCommonEventSubscriber::OnReceiveEvent receive add user event, " - "user id is %{public}d", userId); + BUNDLE_ACTIVE_LOGI("OnReceiveEvent receive add user event, user id is %{public}d", userId); if (!activeGroupController_.expired() && userId >= 0) { activeGroupController_.lock()->PeriodCheckBundleState(userId); } @@ -84,16 +90,13 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da BUNDLE_ACTIVE_LOGI("action is %{public}s, userID is %{public}d, bundlename is %{public}s", action.c_str(), userId, bundleName.c_str()); if (!bundleActiveReportHandler_.expired()) { - BUNDLE_ACTIVE_LOGI("BundleActiveCommonEventSubscriber::OnReceiveEvent gggggg"); BundleActiveReportHandlerObject tmpHandlerObject; tmpHandlerObject.bundleName_ = bundleName; tmpHandlerObject.userId_ = userId; std::shared_ptr handlerobjToPtr = std::make_shared(tmpHandlerObject); - BUNDLE_ACTIVE_LOGI("BundleActiveCommonEventSubscriber::OnReceiveEvent fffff"); auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_BUNDLE_UNINSTALLED, handlerobjToPtr); - BUNDLE_ACTIVE_LOGI("BundleActiveCommonEventSubscriber::OnReceiveEvent hhhhh"); bundleActiveReportHandler_.lock()->SendEvent(BundleActiveReportHandler::MSG_BUNDLE_UNINSTALLED, handlerobjToPtr); } @@ -127,17 +130,17 @@ void BundleActiveCore::Init() sptr timer = MiscServices::TimeServiceClient::GetInstance(); do { realTimeShot_ = timer->GetBootTimeMs(); - systemTimeShot_ = timer->GetWallTimeMs(); + systemTimeShot_ = GetSystemTimeMs(); } while (realTimeShot_ == -1 && systemTimeShot_ == -1); realTimeShot_ = timer->GetBootTimeMs(); - systemTimeShot_ = timer->GetWallTimeMs(); + systemTimeShot_ = GetSystemTimeMs(); bundleGroupController_ = std::make_shared(); BUNDLE_ACTIVE_LOGI("system time shot is %{public}lld", systemTimeShot_); } void BundleActiveCore::InitBundleGroupController() { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::InitBundleGroupController called"); + BUNDLE_ACTIVE_LOGI("InitBundleGroupController called"); std::string threadName = "bundle_active_group_handler"; auto runner = AppExecFwk::EventRunner::Create(threadName); if (runner == nullptr) { @@ -151,13 +154,13 @@ void BundleActiveCore::InitBundleGroupController() if (bundleGroupController_ != nullptr && bundleGroupHandler_ != nullptr) { bundleGroupHandler_->Init(bundleGroupController_); bundleGroupController_->SetHandlerAndCreateUserHistory(bundleGroupHandler_, realTimeShot_); - BUNDLE_ACTIVE_LOGI("BundleActiveCore::Init Set group controller and handler done"); + BUNDLE_ACTIVE_LOGI("Init Set group controller and handler done"); } RegisterSubscriber(); std::vector osAccountInfos; GetAllActiveUser(osAccountInfos); bundleGroupController_->bundleGroupEnable_ = true; - for (int i = 0; i < osAccountInfos.size(); i++) { + for (uint32_t i = 0; i < osAccountInfos.size(); i++) { bundleGroupController_->PeriodCheckBundleState(osAccountInfos[i].GetLocalId()); } } @@ -170,7 +173,7 @@ void BundleActiveCore::SetHandler(const std::shared_ptr BundleActiveCore::GetUserDataAndInitializeIfNeeded(const int userId, const int64_t timeStamp) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::GetUserDataAndInitializeIfNeeded called"); + BUNDLE_ACTIVE_LOGI("GetUserDataAndInitializeIfNeeded called"); std::map>::iterator it = userStatServices_.find(userId); if (it == userStatServices_.end()) { BUNDLE_ACTIVE_LOGI("first initialize user service"); @@ -188,9 +191,12 @@ std::shared_ptr BundleActiveCore::GetUserDataAndInitial } void BundleActiveCore::OnBundleUninstalled(const int userId, const std::string& bundleName) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::OnBundleUninstalled CALLED"); + BUNDLE_ACTIVE_LOGI("OnBundleUninstalled CALLED"); std::lock_guard lock(mutex_); - int64_t timeNow = CheckTimeChangeAndGetWallTime(); + int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); + if (timeNow == -1) { + return; + } auto service = GetUserDataAndInitializeIfNeeded(userId, timeNow); if (service == nullptr) { return; @@ -199,31 +205,21 @@ void BundleActiveCore::OnBundleUninstalled(const int userId, const std::string& bundleGroupController_->OnBundleUninstalled(userId, bundleName); } -void BundleActiveCore::OnStatsChanged() +void BundleActiveCore::OnStatsChanged(const int userId) { - auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); if (!handler_.expired()) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::OnStatsChanged send flush to disk event"); + BUNDLE_ACTIVE_LOGI("OnStatsChanged send flush to disk event"); + BundleActiveReportHandlerObject tmpHandlerObject; + tmpHandlerObject.userId_ = userId; + std::shared_ptr handlerobjToPtr = + std::make_shared(tmpHandlerObject); + auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_FLUSH_TO_DISK, handlerobjToPtr); handler_.lock()->SendEvent(event, FLUSH_INTERVAL); } } -void BundleActiveCore::RestoreToDatabase() -{ - BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabase called"); - std::lock_guard lock(mutex_); - sptr timer = MiscServices::TimeServiceClient::GetInstance(); - BundleActiveEvent event; - event.eventId_ = BundleActiveEvent::FLUSH; - event.timeStamp_ = timer->GetBootTimeMs(); - event.abilityId_ = ""; - ReportEventToAllUserId(event); - RestoreToDatabaseLocked(); -} - -void BundleActiveCore::RestoreToDatabaseLocked() +void BundleActiveCore::RestoreAllData() { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabaseLocked called"); for (std::map>::iterator it = userStatServices_.begin(); it != userStatServices_.end(); it++) { std::shared_ptr service = it->second; @@ -231,7 +227,7 @@ void BundleActiveCore::RestoreToDatabaseLocked() BUNDLE_ACTIVE_LOGI("service in BundleActiveCore::RestoreToDatabaseLocked() is null"); } BUNDLE_ACTIVE_LOGI("userid is %{public}d ", service->userId_); - service->RestoreStats(); + service->RestoreStats(true); if (bundleGroupController_ != nullptr && bundleGroupController_->bundleUserHistory_ != nullptr) { bundleGroupController_->RestoreToDatabase(it->first); } @@ -240,27 +236,58 @@ void BundleActiveCore::RestoreToDatabaseLocked() bundleGroupController_->RestoreDurationToDatabase(); } if (!handler_.expired()) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::RestoreToDatabaseLocked remove flush to disk event"); + BUNDLE_ACTIVE_LOGI("RestoreAllData remove flush to disk event"); + handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); + } +} + +void BundleActiveCore::RestoreToDatabase(const int userId) +{ + BUNDLE_ACTIVE_LOGI("RestoreToDatabase called"); + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + BundleActiveEvent event; + event.eventId_ = BundleActiveEvent::FLUSH; + event.timeStamp_ = GetSystemTimeMs(); + event.abilityId_ = ""; + auto it = userStatServices_.find(userId); + if (it != userStatServices_.end()) { + it->second->ReportEvent(event); + } + RestoreToDatabaseLocked(userId); +} + +void BundleActiveCore::RestoreToDatabaseLocked(const int userId) +{ + BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked called"); + auto it = userStatServices_.find(userId); + if (it != userStatServices_.end()) { + it->second->RestoreStats(false); + } + if (bundleGroupController_ != nullptr) { + bundleGroupController_->RestoreDurationToDatabase(); + } + if (!handler_.expired()) { + BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked remove flush to disk event"); handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); } } void BundleActiveCore::ShutDown() { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::ShutDown called"); std::lock_guard lock(mutex_); + BUNDLE_ACTIVE_LOGI("ShutDown called"); sptr timer = MiscServices::TimeServiceClient::GetInstance(); int64_t timeStamp = timer->GetBootTimeMs(); BundleActiveEvent event(BundleActiveEvent::SHUTDOWN, timeStamp); event.bundleName_ = BundleActiveEvent::DEVICE_EVENT_PACKAGE_NAME; bundleGroupController_->ShutDown(timeStamp); ReportEventToAllUserId(event); - RestoreToDatabaseLocked(); + RestoreAllData(); } void BundleActiveCore::OnStatsReload() { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::OnStatsReload called"); + BUNDLE_ACTIVE_LOGI("OnStatsReload called"); bundleGroupController_->CheckIdleStatsOneTime(); } @@ -268,22 +295,36 @@ void BundleActiveCore::OnSystemUpdate(int userId) { } -int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime() +int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime(int userId) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::CheckTimeChangeAndGetWallTime called"); + BUNDLE_ACTIVE_LOGI("CheckTimeChangeAndGetWallTime called, userId is %{public}d", userId); sptr timer = MiscServices::TimeServiceClient::GetInstance(); - int64_t actualSystemTime = timer->GetWallTimeMs(); + int64_t actualSystemTime = GetSystemTimeMs(); int64_t actualRealTime = timer->GetBootTimeMs(); int64_t expectedSystemTime = (actualRealTime - realTimeShot_) + systemTimeShot_; int64_t diffSystemTime = actualSystemTime - expectedSystemTime; + if (actualSystemTime == -1 || actualRealTime == -1) { + return -1; + } + BUNDLE_ACTIVE_LOGI("asystime is %{public}lld, artime is %{public}lld, esystime is %{public}lld, " + "diff is %{public}lld", + actualSystemTime, actualRealTime, expectedSystemTime, diffSystemTime); if (std::abs(diffSystemTime) > TIME_CHANGE_THRESHOLD_MILLIS) { // 时区变换逻辑 - BUNDLE_ACTIVE_LOGI("time changed!"); - for (std::map>::iterator it = userStatServices_.begin(); - it != userStatServices_.end(); it++) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::CheckTimeChangeAndGetWallTime in update time loop"); - std::shared_ptr service = it->second; - service->RenewTableTime(expectedSystemTime, actualSystemTime); + auto it = userStatServices_.find(userId); + if (it != userStatServices_.end()) { + BundleActiveEvent event; + event.eventId_ = BundleActiveEvent::FLUSH; + event.timeStamp_ = expectedSystemTime; + event.abilityId_ = ""; + it->second->ReportEvent(event); + it->second->RestoreStats(true); + it->second->RenewTableTime(expectedSystemTime, actualSystemTime); + it->second->LoadActiveStats(actualSystemTime, true, true); + if (!handler_.expired()) { + BUNDLE_ACTIVE_LOGI("CheckTimeChangeAndGetWallTime remove flush to disk event"); + handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); + } } realTimeShot_ = actualRealTime; systemTimeShot_ = actualSystemTime; @@ -293,13 +334,13 @@ int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime() void BundleActiveCore::ConvertToSystemTimeLocked(BundleActiveEvent& event) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::ConvertToSystemTimeLocked called"); + BUNDLE_ACTIVE_LOGI("ConvertToSystemTimeLocked called"); event.timeStamp_ = std::max((int64_t)0, event.timeStamp_ - realTimeShot_) + systemTimeShot_; } void BundleActiveCore::OnUserRemoved(const int userId) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::OnUserRemoved called"); + BUNDLE_ACTIVE_LOGI("OnUserRemoved called"); std::lock_guard lock(mutex_); auto it = userStatServices_.find(userId); if (it == userStatServices_.end()) { @@ -314,11 +355,17 @@ void BundleActiveCore::OnUserRemoved(const int userId) int BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int userId) { std::lock_guard lock(mutex_); - BUNDLE_ACTIVE_LOGI("BundleActiveCore::ReportEvent called"); + if (userId == 0) { + return -1; + } + BUNDLE_ACTIVE_LOGI("ReportEvent called"); BUNDLE_ACTIVE_LOGI("report event called bundle name %{public}s time %{public}lld userId %{public}d, " "eventid %{public}d, in lock range", event.bundleName_.c_str(), event.timeStamp_, userId, event.eventId_); sptr timer = MiscServices::TimeServiceClient::GetInstance(); - int64_t timeNow = CheckTimeChangeAndGetWallTime(); + int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); + if (timeNow == -1) { + return -1; + } int64_t bootBasedTimeStamp = timer->GetBootTimeMs(); ConvertToSystemTimeLocked(event); std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow); @@ -333,8 +380,11 @@ int BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int userId) int BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::ReportEventToAllUserId called"); + BUNDLE_ACTIVE_LOGI("ReportEventToAllUserId called"); int64_t timeNow = CheckTimeChangeAndGetWallTime(); + if (timeNow == -1) { + return -1; + } if (userStatServices_.empty()) { std::shared_ptr service = GetUserDataAndInitializeIfNeeded(DEFAULT_USER_ID, timeNow); } @@ -346,9 +396,9 @@ int BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event) BUNDLE_ACTIVE_LOGE("get user data service failed!"); return -1; } - BUNDLE_ACTIVE_LOGI("BundleActiveCore::ReportEventToAllUserId SERVICE user ID IS userId %{public}d", + BUNDLE_ACTIVE_LOGI("ReportEventToAllUserId SERVICE user ID IS userId %{public}d", service->userId_); - service->ReportForFlushAndShutdown(event); + service->ReportForShutdown(event); return 0; } return 0; @@ -357,19 +407,22 @@ int BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event) std::vector BundleActiveCore::QueryPackageStats(const int userId, const int intervalType, const int64_t beginTime, const int64_t endTime, std::string bundleName) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::QueryPackageStats called"); + BUNDLE_ACTIVE_LOGI("QueryPackageStats called"); std::lock_guard lock(mutex_); std::vector result; - int64_t timeNow = CheckTimeChangeAndGetWallTime(); - BUNDLE_ACTIVE_LOGI("BundleActiveCore::QueryPackageStats begin time is %{public}lld, end time is %{public}lld, " + int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); + if (timeNow == -1) { + return result; + } + BUNDLE_ACTIVE_LOGI("QueryPackageStats begin time is %{public}lld, end time is %{public}lld, " "intervaltype is %{public}d", beginTime, endTime, intervalType); if (beginTime > timeNow || beginTime >= endTime) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::QueryPackageStats time span illegal"); + BUNDLE_ACTIVE_LOGI("QueryPackageStats time span illegal"); return result; } std::shared_ptr service = GetUserDataAndInitializeIfNeeded(userId, timeNow); if (service == nullptr) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::QueryPackageStats service is null, failed"); + BUNDLE_ACTIVE_LOGI("QueryPackageStats service is null, failed"); return result; } result = service->QueryPackageStats(intervalType, beginTime, endTime, userId, bundleName); @@ -379,10 +432,13 @@ std::vector BundleActiveCore::QueryPackageStats(const std::vector BundleActiveCore::QueryEvents(const int userId, const int64_t beginTime, const int64_t endTime, std::string bundleName) { - BUNDLE_ACTIVE_LOGI("BundleActiveCore::QueryEvents called"); + BUNDLE_ACTIVE_LOGI("QueryEvents called"); std::vector result; std::lock_guard lock(mutex_); - int64_t timeNow = CheckTimeChangeAndGetWallTime(); + int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); + if (timeNow == -1) { + return result; + } if (beginTime > timeNow || beginTime >= endTime) { return result; } @@ -416,13 +472,31 @@ void BundleActiveCore::GetAllActiveUser(std::vector(now) < 0) { + BUNDLE_ACTIVE_LOGE("Get now time error"); + return 0; + } + auto tarEndTimePoint = std::chrono::system_clock::from_time_t(now); + auto tarDuration = std::chrono::duration_cast(tarEndTimePoint.time_since_epoch()); + int64_t tarDate = tarDuration.count(); + if (tarDate < 0) { + BUNDLE_ACTIVE_LOGE("tarDuration is less than 0."); + return -1; + } + return static_cast(tarDate); +} +} } -} \ No newline at end of file diff --git a/services/common/src/bundle_active_log.cpp b/services/common/src/bundle_active_log.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ddd88396ae277f3dc994e8192364ac3416ed1d05 --- /dev/null +++ b/services/common/src/bundle_active_log.cpp @@ -0,0 +1,43 @@ +/* + * 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" + +namespace OHOS { +namespace DeviceUsageStats { +BundleActiveLogLevel BundleActiveLog::logLevel_ = {BundleActiveLogLevel::DEBUG}; +bool BundleActiveLog::JudgeValidLevel(const BundleActiveLogLevel &level) +{ + const BundleActiveLogLevel &currLevel = BundleActiveLog::GetLogLevel(); + if (level < currLevel) { + return false; + } + return true; +} + +std::string BundleActiveLog::GetCurrFileName(const char *str) +{ + if (!str) { + return std::string(); + } + std::string fullPath(str); + size_t pos = fullPath.find_last_of("/"); + if (pos == std::string::npos) { + return std::string(); + } + return fullPath.substr(pos + 1); +} +} // namespace DeviceUsageStats +} // namespace OHOS diff --git a/services/common/src/bundle_active_open_callback.cpp b/services/common/src/bundle_active_open_callback.cpp index bf951e1f677347ae879b005e4006aebd9c137c67..6e1ce14b30b640c94487bf3ada4a49a4a7ea281b 100644 --- a/services/common/src/bundle_active_open_callback.cpp +++ b/services/common/src/bundle_active_open_callback.cpp @@ -29,13 +29,13 @@ BundleActiveOpenCallback::~BundleActiveOpenCallback() int32_t BundleActiveOpenCallback::OnCreate(NativeRdb::RdbStore &rdbStore) { - BUNDLE_ACTIVE_LOGI("wangyuanchao FlushDatabase SUCCESS.BundleActiveOpenCallback"); + BUNDLE_ACTIVE_LOGI("Create success."); return NativeRdb::E_OK; }; int32_t BundleActiveOpenCallback::OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) { - BUNDLE_ACTIVE_LOGI("FlushDatabase SUCCESS.OnUpgrade"); + BUNDLE_ACTIVE_LOGI("Upgrade success."); return NativeRdb::E_OK; }; } // namespace DeviceUsageStats diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 9b7bfd26662bbd3b9cbac0a797f3e3e7b34d34e5..cb4241a7f8d0f8bf723b16f4eebdbdc2f730995f 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -36,7 +36,7 @@ const std::string NEEDED_PERMISSION = "ohos.permission.BUNDLE_ACTIVE_INFO"; void BundleActiveService::OnStart() { - BUNDLE_ACTIVE_LOGI("BundleActiveService::OnStart() called"); + BUNDLE_ACTIVE_LOGI("OnStart() called"); runner_ = AppExecFwk::EventRunner::Create("device_usage_stats_init_handler"); if (runner_ == nullptr) { BUNDLE_ACTIVE_LOGI("BundleActiveService runner create failed!"); @@ -98,7 +98,12 @@ void BundleActiveService::InitNecessaryState() } else { return; } - shutdownCallback_ = new BundleActiveShutdownCallbackService(bundleActiveCore_); + try { + shutdownCallback_ = new BundleActiveShutdownCallbackService(bundleActiveCore_); + } catch(const std::bad_alloc &e) { + BUNDLE_ACTIVE_LOGE("Memory allocation failed"); + return; + } auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance(); powerManagerClient.RegisterShutdownCallback(shutdownCallback_); InitAppStateSubscriber(reportHandler_); @@ -134,10 +139,10 @@ void BundleActiveService::InitContinuousSubscriber(const std::shared_ptr appManager = GetAppManagerInstance(); if (appStateObserver_ == nullptr) { - BUNDLE_ACTIVE_LOGE("BundleActiveService::SubscribeAppState appstateobserver is null, return"); + BUNDLE_ACTIVE_LOGE("SubscribeAppState appstateobserver is null, return"); return false; } int32_t err = appManager->RegisterApplicationStateObserver(appStateObserver_.get()); @@ -153,7 +158,7 @@ bool BundleActiveService::SubscribeAppState() bool BundleActiveService::SubscribeContinuousTask() { if (continuousTaskObserver_ == nullptr) { - BUNDLE_ACTIVE_LOGE("BundleActiveService::SubscribeContinuousTask continuousTaskObserver_ is null, return"); + BUNDLE_ACTIVE_LOGE("SubscribeContinuousTask continuousTaskObserver_ is null, return"); return false; } if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::SubscribeBackgroundTask(*continuousTaskObserver_) @@ -169,15 +174,14 @@ void BundleActiveService::OnStop() if (shutdownCallback_ != nullptr) { auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance(); powerManagerClient.UnRegisterShutdownCallback(shutdownCallback_); - } else { - shutdownCallback_ = new BundleActiveShutdownCallbackService(bundleActiveCore_); + delete shutdownCallback_; + shutdownCallback_ = nullptr; + return; } - auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance(); - powerManagerClient.UnRegisterShutdownCallback(shutdownCallback_); - bundleActiveCore_->UnRegisterSubscriber(); BUNDLE_ACTIVE_LOGI("[Server] OnStop"); } + int BundleActiveService::ReportEvent(std::string& bundleName, std::string& abilityName, std::string abilityId, const std::string& continuousTask, const int userId, const int eventId) { @@ -209,7 +213,7 @@ bool BundleActiveService::IsBundleIdle(const std::string& bundleName) int result = -1; OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); if (ret == ERR_OK && userId != -1) { - BUNDLE_ACTIVE_LOGI("BundleActiveService::IsBundleIdle user id is %{public}d", userId); + BUNDLE_ACTIVE_LOGI("IsBundleIdle user id is %{public}d", userId); if (!GetBundleMgrProxy()) { BUNDLE_ACTIVE_LOGE("Get bundle manager proxy failed!"); return true; @@ -228,17 +232,17 @@ bool BundleActiveService::IsBundleIdle(const std::string& bundleName) std::vector BundleActiveService::QueryPackageStats(const int intervalType, const int64_t beginTime, const int64_t endTime) { - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryPackageStats stats called, intervaltype is %{public}d", + BUNDLE_ACTIVE_LOGI("QueryPackageStats stats called, intervaltype is %{public}d", intervalType); std::vector result; // get uid int callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryPackageStats UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGI("QueryPackageStats UID is %{public}d", callingUid); // get userid int userId = -1; OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); if (ret == ERR_OK && userId != -1) { - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryPackageStats user id is %{public}d", userId); + BUNDLE_ACTIVE_LOGI("QueryPackageStats user id is %{public}d", userId); bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, userId); if (isSystemAppAndHasPermission == true) { int convertedIntervalType = ConvertIntervalType(intervalType); @@ -250,16 +254,16 @@ std::vector BundleActiveService::QueryPackageStats(con std::vector BundleActiveService::QueryEvents(const int64_t beginTime, const int64_t endTime) { - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryEvents stats called"); + BUNDLE_ACTIVE_LOGI("QueryEvents stats called"); std::vector result; // get uid int callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryEvents UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGI("QueryEvents UID is %{public}d", callingUid); // get userid int userId = -1; OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); if (ret == ERR_OK && userId != -1) { - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryEvents userid is %{public}d", userId); + BUNDLE_ACTIVE_LOGI("QueryEvents userid is %{public}d", userId); bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, userId); if (isSystemAppAndHasPermission == true) { result = bundleActiveCore_->QueryEvents(userId, beginTime, endTime, ""); @@ -277,7 +281,7 @@ void BundleActiveService::SetBundleGroup(const std::string& bundleName, int newG std::vector BundleActiveService::QueryCurrentPackageStats(const int intervalType, const int64_t beginTime, const int64_t endTime) { - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryCurrentPackageStats stats called"); + BUNDLE_ACTIVE_LOGI("QueryCurrentPackageStats stats called"); std::vector result; // get uid int callingUid = OHOS::IPCSkeleton::GetCallingUid(); @@ -286,7 +290,7 @@ std::vector BundleActiveService::QueryCurrentPackageSt int userId = -1; OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); if (ret == ERR_OK && userId != -1) { - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryCurrentPackageStats userid is %{public}d", userId); + BUNDLE_ACTIVE_LOGI("QueryCurrentPackageStats userid is %{public}d", userId); if (!GetBundleMgrProxy()) { BUNDLE_ACTIVE_LOGE("BundleActiveGroupController::CheckEachBundleState get bundle manager proxy failed!"); return result; @@ -300,51 +304,51 @@ std::vector BundleActiveService::QueryCurrentPackageSt bundleName); } } - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryCurrentPackageStats result size is %{public}d", result.size()); + BUNDLE_ACTIVE_LOGI("QueryCurrentPackageStats result size is %{public}d", result.size()); return result; } std::vector BundleActiveService::QueryCurrentEvents(const int64_t beginTime, const int64_t endTime) { - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryCurrentEvents stats called"); + BUNDLE_ACTIVE_LOGI("QueryCurrentEvents stats called"); std::vector result; // get uid int callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryCurrentEvents UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGI("QueryCurrentEvents UID is %{public}d", callingUid); // get userid int userId = -1; OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); if (ret == ERR_OK && userId != -1) { - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryCurrentEvents userid is %{public}d", userId); + BUNDLE_ACTIVE_LOGI("QueryCurrentEvents userid is %{public}d", userId); if (!GetBundleMgrProxy()) { - BUNDLE_ACTIVE_LOGE("BundleActiveService::QueryCurrentEvents get bundle manager proxy failed!"); + BUNDLE_ACTIVE_LOGE("QueryCurrentEvents get bundle manager proxy failed!"); return result; } std::string bundleName = ""; sptrBundleMgr_->GetBundleNameForUid(callingUid, bundleName); bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, userId); if (!bundleName.empty() && isSystemAppAndHasPermission == true) { - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryCurrentEvents buindle name is %{public}s", + BUNDLE_ACTIVE_LOGI("QueryCurrentEvents buindle name is %{public}s", bundleName.c_str()); result = bundleActiveCore_->QueryEvents(userId, beginTime, endTime, bundleName); } } - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryCurrentEvents result size is %{public}d", result.size()); + BUNDLE_ACTIVE_LOGI("QueryCurrentEvents result size is %{public}d", result.size()); return result; } int BundleActiveService::QueryPackageGroup() { - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryPackageGroup stats called"); + BUNDLE_ACTIVE_LOGI("QueryPackageGroup stats called"); // get uid int callingUid = OHOS::IPCSkeleton::GetCallingUid(); - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryPackageGroup UID is %{public}d", callingUid); + BUNDLE_ACTIVE_LOGI("QueryPackageGroup UID is %{public}d", callingUid); // get userid int userId = -1; int result = -1; OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryPackageGroup user id is %{public}d", userId); + BUNDLE_ACTIVE_LOGI("QueryPackageGroup user id is %{public}d", userId); if (ret == ERR_OK && userId != -1) { if (!GetBundleMgrProxy()) { BUNDLE_ACTIVE_LOGE("BundleActiveGroupController::CheckEachBundleState get bundle manager proxy failed!"); @@ -353,12 +357,12 @@ int BundleActiveService::QueryPackageGroup() std::string bundleName = ""; // get bundle name sptrBundleMgr_->GetBundleNameForUid(callingUid, bundleName); - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryPackageGroup bundlename is %{public}s", bundleName.c_str()); + BUNDLE_ACTIVE_LOGI("QueryPackageGroup bundlename is %{public}s", bundleName.c_str()); if (!bundleName.empty()) { result = bundleActiveCore_->QueryPackageGroup(userId, bundleName); } } - BUNDLE_ACTIVE_LOGI("BundleActiveService::QueryPackageGroup result is %{public}d", result); + BUNDLE_ACTIVE_LOGI("QueryPackageGroup result is %{public}d", result); return result; } diff --git a/services/common/src/bundle_active_stub.cpp b/services/common/src/bundle_active_stub.cpp index 99beeea269752e3665563d37f46b87acfcf356ee..02c5beb10e732d8a1e856251f69aa8180c1be86c 100644 --- a/services/common/src/bundle_active_stub.cpp +++ b/services/common/src/bundle_active_stub.cpp @@ -45,13 +45,13 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me std::vector result; int size = 0; int intervalType = data.ReadInt32(); - BUNDLE_ACTIVE_LOGI("BundleActiveStub::OnRemoteRequest QUERY_USAGE_STATS intervaltype is %{public}d", + BUNDLE_ACTIVE_LOGI("OnRemoteRequest QUERY_USAGE_STATS intervaltype is %{public}d", intervalType); int64_t beginTime = data.ReadInt64(); int64_t endTime = data.ReadInt64(); result = QueryPackageStats(intervalType, beginTime, endTime); - size = result.size(); - BUNDLE_ACTIVE_LOGI("BundleActiveStub::OnRemoteRequest QUERY_USAGE_STATS result size is %{public}d", size); + size = static_cast(result.size()); + BUNDLE_ACTIVE_LOGI("OnRemoteRequest QUERY_USAGE_STATS result size is %{public}d", size); reply.WriteInt32(size); for (int i = 0; i < size; i++) { bool tmp = result[i].Marshalling(reply); @@ -67,7 +67,7 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me int64_t beginTime = data.ReadInt64(); int64_t endTime = data.ReadInt64(); result = QueryEvents(beginTime, endTime); - size = result.size(); + size = static_cast(result.size()); reply.WriteInt32(size); for (int i = 0; i < size; i++) { bool tmp = result[i].Marshalling(reply); @@ -88,13 +88,13 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me std::vector result; int size = 0; int intervalType = data.ReadInt32(); - BUNDLE_ACTIVE_LOGI("BundleActiveStub::OnRemoteRequest QUERY_CURRENT_USAGE_STATS intervaltype " + BUNDLE_ACTIVE_LOGI("OnRemoteRequest QUERY_CURRENT_USAGE_STATS intervaltype " "is %{public}d", intervalType); int64_t beginTime = data.ReadInt64(); int64_t endTime = data.ReadInt64(); result = QueryPackageStats(intervalType, beginTime, endTime); - size = result.size(); - BUNDLE_ACTIVE_LOGI("BundleActiveStub::OnRemoteRequest QUERY_CURRENT_USAGE_STATS result size " + size = static_cast(result.size()); + BUNDLE_ACTIVE_LOGI("OnRemoteRequest QUERY_CURRENT_USAGE_STATS result size " "is %{public}d", size); reply.WriteInt32(size); for (int i = 0; i < size; i++) { @@ -111,7 +111,7 @@ int32_t BundleActiveStub::OnRemoteRequest(uint32_t code, MessageParcel& data, Me int64_t beginTime = data.ReadInt64(); int64_t endTime = data.ReadInt64(); result = QueryCurrentEvents(beginTime, endTime); - size = result.size(); + size = static_cast(result.size()); reply.WriteInt32(size); for (int i = 0; i < size; i++) { bool tmp = result[i].Marshalling(reply); diff --git a/services/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp index 9a378e53c7dee6f4d000bc7540d298a12ee2cf02..4175d250fc70ad5bcfd45789f20722d945253b52 100644 --- a/services/common/src/bundle_active_usage_database.cpp +++ b/services/common/src/bundle_active_usage_database.cpp @@ -44,7 +44,7 @@ BundleActiveUsageDatabase::BundleActiveUsageDatabase() { currentVersion_ = BUNDLE_ACTIVE_CURRENT_VERSION; versionDirectoryPath_ = BUNDLE_ACTIVE_DATABASE_DIR + BUNDLE_ACTIVE_VERSION_FILE; - for (int i = 0; i < sizeof(DATABASE_TYPE)/sizeof(DATABASE_TYPE[0]); i++) { + for (uint32_t i = 0; i < sizeof(DATABASE_TYPE)/sizeof(DATABASE_TYPE[0]); i++) { databaseFiles_.push_back(DATABASE_TYPE[i]); } eventTableName_ = UNKNOWN_TABLE_NAME; @@ -131,7 +131,7 @@ void BundleActiveUsageDatabase::InitDatabaseTableInfo(int64_t currentTime) if (startIndex < BUNDLE_ACTIVE_SUCCESS) { continue; } - int32_t tableNumber = sortedTableArray_.at(i).size(); + int32_t tableNumber = static_cast(sortedTableArray_.at(i).size()); for (int32_t j = startIndex; j < tableNumber; j++) { DeleteInvalidTable(i, sortedTableArray_.at(i).at(startIndex)); sortedTableArray_.at(i).erase(sortedTableArray_.at(i).begin() + startIndex); @@ -149,11 +149,12 @@ int32_t BundleActiveUsageDatabase::NearIndexOnOrAfterCurrentTime(int64_t current vector &sortedTableArray) { int32_t low = 0; - int32_t high = sortedTableArray.size() - 1; + int32_t high = static_cast(sortedTableArray.size() - 1); int32_t mid = -1; int64_t tableTime = -1; + int32_t divisor = 2; while (low <= high) { - mid = (low + high) >> 1; + mid = (high - low) / divisor + low; tableTime = sortedTableArray.at(mid); if (currentTime > tableTime) { low = mid + 1; @@ -165,7 +166,7 @@ int32_t BundleActiveUsageDatabase::NearIndexOnOrAfterCurrentTime(int64_t current } if (currentTime < tableTime) { return mid; - } else if (currentTime > tableTime && low < sortedTableArray.size()) { + } else if (currentTime > tableTime && low < static_cast(sortedTableArray.size())) { return low; } else { return BUNDLE_ACTIVE_FAIL; @@ -190,7 +191,7 @@ unique_ptr BundleActiveUsageDatabase::QueryStatsInfoByStep { shared_ptr rdbStore = GetBundleActiveRdbStore(databaseType); if (rdbStore == nullptr) { - BUNDLE_ACTIVE_LOGE("queryStatsInfoByStep is failed"); + BUNDLE_ACTIVE_LOGE("rdbStore is nullptr"); return nullptr; } unique_ptr result; @@ -235,7 +236,7 @@ void BundleActiveUsageDatabase::HandleTableInfo(unsigned int databaseType) sort(sortedTableArray_.at(databaseType).begin(), sortedTableArray_.at(databaseType).end()); } if ((databaseType == DAILY_DATABASE_INDEX) && !sortedTableArray_.at(databaseType).empty()) { - int lastTableIndex = sortedTableArray_.at(databaseType).size() - 1; + size_t lastTableIndex = sortedTableArray_.at(databaseType).size() - 1; eventBeginTime_ = sortedTableArray_.at(databaseType).at(lastTableIndex); } } else if (databaseType == EVENT_DATABASE_INDEX) { @@ -258,7 +259,8 @@ void BundleActiveUsageDatabase::DeleteExcessiveTableData(unsigned int databaseTy BUNDLE_ACTIVE_LOGE("database table not exist"); return; } - int32_t deleteNumber = sortedTableArray_.at(databaseType).size() - MAX_FILES_EVERY_INTERVAL_TYPE[databaseType]; + int32_t existingNumber = static_cast(sortedTableArray_.at(databaseType).size()); + int32_t deleteNumber = existingNumber - MAX_FILES_EVERY_INTERVAL_TYPE[databaseType]; if (deleteNumber > 0) { for (int32_t i = 0; i < deleteNumber; i++) { // 删除多余文件 @@ -280,20 +282,19 @@ void BundleActiveUsageDatabase::DeleteExcessiveTableData(unsigned int databaseTy } shared_ptr rdbStore = GetBundleActiveRdbStore(databaseType); if (rdbStore == nullptr) { - BUNDLE_ACTIVE_LOGE("BundleActiveUsageDatabase DeleteExcessiveTableData is failed"); + BUNDLE_ACTIVE_LOGE("rdbStore is nullptr"); return; } string deleteEventDataSql = "delete from " + eventTableName_ + " where timeStamp <= " + to_string(deleteTimePoint); int32_t deleteResult = rdbStore->ExecuteSql(deleteEventDataSql); if (deleteResult != NativeRdb::E_OK) { - BUNDLE_ACTIVE_LOGE("BundleActiveUsageDatabase DeleteExcessiveTableData deleteEventData is failed"); + BUNDLE_ACTIVE_LOGE("delete event data failed, rdb error number: %{public}d", deleteResult); } } else if (databaseType == APP_GROUP_DATABASE_INDEX) { // 无数据删除 } else { - BUNDLE_ACTIVE_LOGE("BundleActiveUsageDatabase DeleteExcessiveTableData databaseType is invalid, databaseType = " - "%{public}d", databaseType); + BUNDLE_ACTIVE_LOGE("databaseType is invalid, databaseType = %{public}d", databaseType); } } @@ -302,8 +303,7 @@ std::unique_ptr> BundleActiveUsageDatabase::GetOverdueTable { std::unique_ptr> overdueTableCreateTime = std::make_unique>(); if (databaseType < 0 || databaseType >= sortedTableArray_.size()) { - BUNDLE_ACTIVE_LOGE("BundleActiveUsageDatabase GetOverdueTableCreateTime databaseType is invalid, databaseType " - "= %{public}d", databaseType); + BUNDLE_ACTIVE_LOGE("databaseType is invalid, databaseType = %{public}d", databaseType); return nullptr; } string queryDatabaseTableNames = "select * from sqlite_master where type = ?"; @@ -312,13 +312,13 @@ std::unique_ptr> BundleActiveUsageDatabase::GetOverdueTable unique_ptr bundleActiveResult = QueryStatsInfoByStep(databaseType, queryDatabaseTableNames, queryCondition); if (bundleActiveResult == nullptr) { - BUNDLE_ACTIVE_LOGE("BundleActiveUsageDatabase GetOverdueTableCreateTime bundleActiveResult is invalid"); + BUNDLE_ACTIVE_LOGE("bundleActiveResult is invalid"); return nullptr; } int32_t tableNumber; bundleActiveResult->GetRowCount(tableNumber); if (tableNumber == 0) { - BUNDLE_ACTIVE_LOGE("BundleActiveUsageDatabase GetOverdueTableCreateTime table does not exist"); + BUNDLE_ACTIVE_LOGE("table does not exist"); return nullptr; } int32_t tableNameIndex; @@ -338,7 +338,7 @@ int32_t BundleActiveUsageDatabase::DeleteInvalidTable(unsigned int databaseType, { shared_ptr rdbStore = GetBundleActiveRdbStore(databaseType); if (rdbStore == nullptr) { - BUNDLE_ACTIVE_LOGE("get rdbStore failed"); + BUNDLE_ACTIVE_LOGE("rdbStore is nullptr"); return BUNDLE_ACTIVE_FAIL; } if (databaseType >= 0 && databaseType < sortedTableArray_.size()) { @@ -346,7 +346,7 @@ int32_t BundleActiveUsageDatabase::DeleteInvalidTable(unsigned int databaseType, string deletePackageTableSql = "drop table " + packageTable; int32_t deletePackageTable = rdbStore->ExecuteSql(deletePackageTableSql); if (deletePackageTable != NativeRdb::E_OK) { - BUNDLE_ACTIVE_LOGE("deletePackageTable is %{public}d", deletePackageTable); + BUNDLE_ACTIVE_LOGE("delete package table failed, rdb error number: %{public}d", deletePackageTable); return BUNDLE_ACTIVE_FAIL; } } else if (databaseType == EVENT_DATABASE_INDEX) { @@ -354,7 +354,7 @@ int32_t BundleActiveUsageDatabase::DeleteInvalidTable(unsigned int databaseType, string deleteEventTableSql = "drop table " + eventTable; int32_t deleteEventTable = rdbStore->ExecuteSql(deleteEventTableSql); if (deleteEventTable != NativeRdb::E_OK) { - BUNDLE_ACTIVE_LOGE("deleteEventTable is %{public}d", deleteEventTable); + BUNDLE_ACTIVE_LOGE("delete event table failed, rdb error number: %{public}d", deleteEventTable); return BUNDLE_ACTIVE_FAIL; } } else if (databaseType == APP_GROUP_DATABASE_INDEX) { @@ -434,12 +434,13 @@ int32_t BundleActiveUsageDatabase::CreateEventLogTable(unsigned int databaseType + BUNDLE_ACTIVE_DB_ABILITY_ID + " TEXT NOT NULL);"; int32_t createEventTable = rdbStore->ExecuteSql(createEventTableSql); if (createEventTable != NativeRdb::E_OK) { + BUNDLE_ACTIVE_LOGE("create event table failed, rdb error number: %{public}d", createEventTable); return createEventTable; } string createEventTableIndex = GetTableIndexSql(EVENT_DATABASE_INDEX, currentTimeMillis, true); int32_t createResult = rdbStore->ExecuteSql(createEventTableIndex); if (createResult != NativeRdb::E_OK) { - BUNDLE_ACTIVE_LOGE("create event table index failed"); + BUNDLE_ACTIVE_LOGE("create event table index failed, rdb error number: %{public}d", createResult); return BUNDLE_ACTIVE_FAIL; } return BUNDLE_ACTIVE_SUCCESS; @@ -465,13 +466,13 @@ int32_t BundleActiveUsageDatabase::CreatePackageLogTable(unsigned int databaseTy + BUNDLE_ACTIVE_DB_TOTAL_TIME_CONTINUOUS_TASK + " INTEGER NOT NULL);"; int32_t createPackageTable = rdbStore->ExecuteSql(createPackageTableSql); if (createPackageTable != NativeRdb::E_OK) { - BUNDLE_ACTIVE_LOGE("create packageLog table failed"); + BUNDLE_ACTIVE_LOGE("create packageLog table failed, rdb error number: %{public}d", createPackageTable); return BUNDLE_ACTIVE_FAIL; } string createPackageTableIndex = GetTableIndexSql(databaseType, currentTimeMillis, true); int32_t createResult = rdbStore->ExecuteSql(createPackageTableIndex); if (createResult != NativeRdb::E_OK) { - BUNDLE_ACTIVE_LOGE("create package table index failed"); + BUNDLE_ACTIVE_LOGE("create package table index failed, rdb error number: %{public}d", createResult); return BUNDLE_ACTIVE_FAIL; } return BUNDLE_ACTIVE_SUCCESS; @@ -491,7 +492,7 @@ int32_t BundleActiveUsageDatabase::CreateDurationTable(unsigned int databaseType + BUNDLE_ACTIVE_DB_SCREEN_ON_DURATION + " INTEGER NOT NULL);"; int32_t createDurationTable = rdbStore->ExecuteSql(createDurationTableSql); if (createDurationTable != NativeRdb::E_OK) { - BUNDLE_ACTIVE_LOGE("create duration table failed"); + BUNDLE_ACTIVE_LOGE("create duration table failed, rdb error number: %{public}d", createDurationTable); return BUNDLE_ACTIVE_FAIL; } return BUNDLE_ACTIVE_SUCCESS; @@ -517,14 +518,14 @@ int32_t BundleActiveUsageDatabase::CreateBundleHistoryTable(unsigned int databas + BUNDLE_ACTIVE_DB_BUNDLE_DAILY_TIMEOUT_TIME + " INTEGER NOT NULL);"; int32_t createBundleHistoryTable = rdbStore->ExecuteSql(createBundleHistoryTableSql); if (createBundleHistoryTable != NativeRdb::E_OK) { - BUNDLE_ACTIVE_LOGE("create bundleHistory table failed"); + BUNDLE_ACTIVE_LOGE("create bundleHistory table failed, rdb error number: %{public}d", createBundleHistoryTable); return createBundleHistoryTable; } int32_t time = 0; string createBundleHistoryTableIndex = GetTableIndexSql(databaseType, time, true); int32_t createResult = rdbStore->ExecuteSql(createBundleHistoryTableIndex); if (createResult != NativeRdb::E_OK) { - BUNDLE_ACTIVE_LOGE("create bundleHistory table index failed"); + BUNDLE_ACTIVE_LOGE("create bundleHistory table index failed, rdb error number: %{public}d", createResult); return BUNDLE_ACTIVE_FAIL; } return BUNDLE_ACTIVE_SUCCESS; @@ -560,7 +561,7 @@ void BundleActiveUsageDatabase::PutBundleHistoryData(int userId, valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_BOOT_FROM_USED_TIME, iter->second->lastBootFromUsedTimeStamp_); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_SCREEN_USED_TIME, iter->second->lastScreenUsedTimeStamp_); valuesBucket.PutInt(BUNDLE_ACTIVE_DB_CURRENT_GROUP, iter->second->currentGroup_); - valuesBucket.PutInt(BUNDLE_ACTIVE_DB_REASON_IN_GROUP, iter->second->reasonInGroup_); + valuesBucket.PutInt(BUNDLE_ACTIVE_DB_REASON_IN_GROUP, static_cast(iter->second->reasonInGroup_)); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_BUNDLE_ALIVE_TIMEOUT_TIME, iter->second->bundleAliveTimeoutTimeStamp_); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_BUNDLE_DAILY_TIMEOUT_TIME, iter->second->bundleDailyTimeoutTimeStamp_); rdbStore->Update(changeRow, BUNDLE_HISTORY_LOG_TABLE, valuesBucket, "userId = ? and bundleName = ?", @@ -602,6 +603,7 @@ shared_ptr>> BundleActiveUsag shared_ptr>> userUsageHistory = make_shared>>(); shared_ptr usageHistory; + int currentBundleGroupReason = 0; for (int32_t i = 0; i < tableRowNumber; i++) { bundleActiveResult->GoToRow(i); bundleActiveResult->GetString(BUNDLE_NAME_COLUMN_INDEX, bundleName); @@ -609,7 +611,8 @@ shared_ptr>> BundleActiveUsag bundleActiveResult->GetLong(LAST_BOOT_FROM_USED_TIME_COLUMN_INDEX, usageHistory->lastBootFromUsedTimeStamp_); bundleActiveResult->GetLong(LAST_SCREEN_USED_TIME_COLUMN_INDEX, usageHistory->lastScreenUsedTimeStamp_); bundleActiveResult->GetInt(CURRENT_GROUP_COLUMN_INDEX, usageHistory->currentGroup_); - bundleActiveResult->GetInt(REASON_IN_GROUP_COLUMN_INDEX, usageHistory->reasonInGroup_); + bundleActiveResult->GetInt(REASON_IN_GROUP_COLUMN_INDEX, currentBundleGroupReason); + usageHistory->reasonInGroup_ = static_cast(currentBundleGroupReason); bundleActiveResult->GetLong(BUNDLE_ALIVE_TIMEOUT_TIME_COLUMN_INDEX, usageHistory->bundleAliveTimeoutTimeStamp_); bundleActiveResult->GetLong(BUNDLE_DAILY_TIMEOUT_TIME_COLUMN_INDEX, @@ -683,8 +686,12 @@ void BundleActiveUsageDatabase::FlushPackageInfo(unsigned int databaseType, cons queryCondition.push_back(iter->first); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_BUNDLE_STARTED_COUNT, iter->second->bundleStartedCount_); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME, (iter->second->lastTimeUsed_ - stats.beginTime_)); - valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME_CONTINUOUS_TASK, (iter->second->lastContiniousTaskUsed_ - - stats.beginTime_)); + if (iter->second->lastContiniousTaskUsed_ == -1) { + valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME_CONTINUOUS_TASK, (iter->second->lastContiniousTaskUsed_)); + } else { + valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME_CONTINUOUS_TASK, (iter->second->lastContiniousTaskUsed_ - + stats.beginTime_)); + } valuesBucket.PutLong(BUNDLE_ACTIVE_DB_TOTAL_TIME, iter->second->totalInFrontTime_); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_TOTAL_TIME_CONTINUOUS_TASK, iter->second->totalContiniousTaskUsedTime_); rdbStore->Update(changeRow, tableName, valuesBucket, "userId = ? and bundleName = ?", queryCondition); @@ -705,12 +712,12 @@ shared_ptr BundleActiveUsageDatabase::GetCurrentUsageDa int userId) { lock_guard lock(databaseMutex_); - if (databaseType < 0 || databaseType >= sortedTableArray_.size()) { + if (databaseType < 0 || databaseType >= static_cast(sortedTableArray_.size())) { BUNDLE_ACTIVE_LOGE("databaseType is invalid, databaseType = %{public}d", databaseType); return nullptr; } - int tableNumber = sortedTableArray_.at(databaseType).size(); + int tableNumber = static_cast(sortedTableArray_.at(databaseType).size()); if (tableNumber == TABLE_NOT_EXIST) { return nullptr; } @@ -741,7 +748,11 @@ shared_ptr BundleActiveUsageDatabase::GetCurrentUsageDa bundleActiveResult->GetLong(LAST_TIME_COLUMN_INDEX, relativeLastTimeUsed); usageStats->lastTimeUsed_ = relativeLastTimeUsed + currentPackageTime; bundleActiveResult->GetLong(LAST_TIME_CONTINUOUS_TASK_COLUMN_INDEX, relativeLastTimeFrontServiceUsed); - usageStats->lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + currentPackageTime; + if (relativeLastTimeFrontServiceUsed == -1) { + usageStats->lastContiniousTaskUsed_ = -1; + } else { + usageStats->lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + currentPackageTime; + } bundleActiveResult->GetLong(TOTAL_TIME_COLUMN_INDEX, usageStats->totalInFrontTime_); bundleActiveResult->GetLong(TOTAL_TIME_CONTINUOUS_TASK_COLUMN_INDEX, usageStats->totalContiniousTaskUsedTime_); bundleStats.insert(pair>(usageStats->bundleName_, @@ -753,7 +764,7 @@ shared_ptr BundleActiveUsageDatabase::GetCurrentUsageDa eventBeginTime_ = currentPackageTime; } sptr timer = MiscServices::TimeServiceClient::GetInstance(); - int64_t systemTime = timer->GetWallTimeMs(); + int64_t systemTime = GetSystemTimeMs(); intervalStats->lastTimeSaved_ = systemTime; return intervalStats; } @@ -866,9 +877,9 @@ int32_t BundleActiveUsageDatabase::GetOptimalIntervalType(int64_t beginTime, int lock_guard lock(databaseMutex_); int32_t optimalIntervalType = -1; int64_t leastTimeDiff = numeric_limits::max(); - for (int32_t i = sortedTableArray_.size() - 1; i >= 0; i--) { + for (int32_t i = static_cast(sortedTableArray_.size() - 1); i >= 0; i--) { int32_t index = NearIndexOnOrBeforeCurrentTime(beginTime, sortedTableArray_.at(i)); - int32_t size = sortedTableArray_.at(i).size(); + int32_t size = static_cast(sortedTableArray_.at(i).size()); if (index >= 0 && index < size) { int64_t diff = abs(sortedTableArray_.at(i).at(index) - beginTime); if (diff < leastTimeDiff) { @@ -936,6 +947,7 @@ void BundleActiveUsageDatabase::RenewTableTime(int64_t changedTime) vector tableArray = sortedTableArray_.at(i); for (unsigned int j = 0; j < tableArray.size(); j++) { int64_t newTime = tableArray.at(j) + changedTime; + BUNDLE_ACTIVE_LOGI("new table time is %{public}lld", newTime); if (newTime < 0) { DeleteInvalidTable(i, tableArray.at(j)); } else { @@ -983,14 +995,13 @@ void BundleActiveUsageDatabase::UpdateUsageData(int32_t databaseType, BundleActi eventBeginTime_ = stats.beginTime_; DeleteExcessiveTableData(EVENT_DATABASE_INDEX); } - packageTableIndex = ~packageTableIndex; - sortedTableArray_.at(databaseType).insert(sortedTableArray_.at(databaseType).begin() + packageTableIndex, - stats.beginTime_); + sortedTableArray_.at(databaseType).push_back(stats.beginTime_); + sort(sortedTableArray_.at(databaseType).begin(), sortedTableArray_.at(databaseType).end()); DeleteExcessiveTableData(databaseType); } FlushPackageInfo(databaseType, stats); sptr timer = MiscServices::TimeServiceClient::GetInstance(); - int64_t systemTime = timer->GetWallTimeMs(); + int64_t systemTime = GetSystemTimeMs(); stats.lastTimeSaved_ = systemTime; } @@ -999,7 +1010,7 @@ vector BundleActiveUsageDatabase::QueryDatabaseUsageSt { lock_guard lock(databaseMutex_); vector databaseUsageStats; - if (databaseType < 0 || databaseType >= sortedTableArray_.size()) { + if (databaseType < 0 || databaseType >= static_cast(sortedTableArray_.size())) { BUNDLE_ACTIVE_LOGE("databaseType is invalid, databaseType = %{public}d", databaseType); return databaseUsageStats; } @@ -1073,7 +1084,11 @@ vector BundleActiveUsageDatabase::QueryDatabaseUsageSt bundleActiveResult->GetLong(LAST_TIME_COLUMN_INDEX, relativeLastTimeUsed); usageStats.lastTimeUsed_ = relativeLastTimeUsed + packageTableTime; bundleActiveResult->GetLong(LAST_TIME_CONTINUOUS_TASK_COLUMN_INDEX, relativeLastTimeFrontServiceUsed); - usageStats.lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + packageTableTime; + if (relativeLastTimeFrontServiceUsed == -1) { + usageStats.lastContiniousTaskUsed_ = -1; + } else { + usageStats.lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + packageTableTime; + } bundleActiveResult->GetLong(TOTAL_TIME_COLUMN_INDEX, usageStats.totalInFrontTime_); bundleActiveResult->GetLong(TOTAL_TIME_CONTINUOUS_TASK_COLUMN_INDEX, usageStats.totalContiniousTaskUsedTime_); @@ -1179,5 +1194,23 @@ void BundleActiveUsageDatabase::DeleteUninstalledInfo(const int userId, const st rdbStore->Delete(deletedRows, tableName, "userId = ? and bundleName = ?", queryCondition); } } + +int64_t BundleActiveUsageDatabase::GetSystemTimeMs() +{ + time_t now; + (void)time(&now); // unit is seconds. + if (static_cast(now) < 0) { + BUNDLE_ACTIVE_LOGE("Get now time error"); + return 0; + } + auto tarEndTimePoint = std::chrono::system_clock::from_time_t(now); + auto tarDuration = std::chrono::duration_cast(tarEndTimePoint.time_since_epoch()); + int64_t tarDate = tarDuration.count(); + if (tarDate < 0) { + BUNDLE_ACTIVE_LOGE("tarDuration is less than 0."); + return -1; + } + return static_cast(tarDate); +} } } \ No newline at end of file diff --git a/services/packagegroup/include/bundle_active_group_common.h b/services/packagegroup/include/bundle_active_group_common.h index f530520da92a22eaede41847929e7d0f05659347..d3fdef4bd2c1294f99c2c08d19bf01d02dd56e9e 100644 --- a/services/packagegroup/include/bundle_active_group_common.h +++ b/services/packagegroup/include/bundle_active_group_common.h @@ -30,6 +30,7 @@ const int ACTIVE_GROUP_NEVER = 60; const int64_t FIVE_SECOND = 5 * 1000; const int64_t ONE_MINUTE = 60 * 1000; const int64_t TWO_MINUTE = 2 * ONE_MINUTE; +const int64_t THREE_MINUTE = 3 * ONE_MINUTE; const int64_t FOUR_MINUTE = 4 * ONE_MINUTE; const int64_t TEN_MINUTE = 10 * ONE_MINUTE; const int64_t SIXTEEN_MINUTE = 16 * ONE_MINUTE; @@ -43,21 +44,21 @@ const int64_t DEFAULT_EVENT_TIMEOUT = ONE_HOUR; const int64_t DEFAULT_NOTIFY_EVENT_TIMEOUT = 12 * ONE_HOUR; const int64_t DEFAULT_SYSTEevent__TIMEOUT = 2 * ONE_HOUR; const int64_t DEFAULT_LONT_TIME_TASK_START_EVENT_TIMEOUT = 30 * ONE_MINUTE; -const int GROUP_CONTROL_REASON_MASK = 0xFF00; -const int GROUP_CONTROL_REASON_DEFAULT = 0x0100; -const int GROUP_CONTROL_REASON_TIMEOUT = 0x0200; -const int GROUP_CONTROL_REASON_USAGE = 0x0300; -const int GROUP_CONTROL_REASON_FORCED = 0x0400; -const int GROUP_CONTROL_REASON_CALCULATED = 0x0500; -const int GROUP_EVENT_REASON_MASK = 0x00FF; -const int GROUP_EVENT_REASON_SYSTEM = 0x0001; -const int GROUP_EVENT_REASON_NOTIFY_SEEN = 0x0002; -const int GROUP_EVENT_REASON_USER_INTERACTION = 0x0003; -const int GROUP_EVENT_REASON_FOREGROUND = 0x0004; -const int GROUP_EVENT_REASON_BACKGROUND = 0x0005; -const int GROUP_EVENT_REASON_ALIVE_TIMEOUT = 0x0006; -const int GROUP_EVENT_REASON_LONG_TIME_TASK_STARTTED = 0x0007; -const int GROUP_EVENT_REASON_CALCULATED_RESTORED = 0x0008; +const uint32_t GROUP_CONTROL_REASON_MASK = 0xFF00; +const uint32_t GROUP_CONTROL_REASON_DEFAULT = 0x0100; +const uint32_t GROUP_CONTROL_REASON_TIMEOUT = 0x0200; +const uint32_t GROUP_CONTROL_REASON_USAGE = 0x0300; +const uint32_t GROUP_CONTROL_REASON_FORCED = 0x0400; +const uint32_t GROUP_CONTROL_REASON_CALCULATED = 0x0500; +const uint32_t GROUP_EVENT_REASON_MASK = 0x00FF; +const uint32_t GROUP_EVENT_REASON_SYSTEM = 0x0001; +const uint32_t GROUP_EVENT_REASON_NOTIFY_SEEN = 0x0002; +const uint32_t GROUP_EVENT_REASON_USER_INTERACTION = 0x0003; +const uint32_t GROUP_EVENT_REASON_FOREGROUND = 0x0004; +const uint32_t GROUP_EVENT_REASON_BACKGROUND = 0x0005; +const uint32_t GROUP_EVENT_REASON_ALIVE_TIMEOUT = 0x0006; +const uint32_t GROUP_EVENT_REASON_LONG_TIME_TASK_STARTTED = 0x0007; +const uint32_t GROUP_EVENT_REASON_CALCULATED_RESTORED = 0x0008; } } } diff --git a/services/packagegroup/include/bundle_active_group_controller.h b/services/packagegroup/include/bundle_active_group_controller.h index c0589b7218e011eefed595c774d53f8e83ba8ac6..1de660fc0c4a8a0f29a6fd540407a3ec577e894a 100644 --- a/services/packagegroup/include/bundle_active_group_controller.h +++ b/services/packagegroup/include/bundle_active_group_controller.h @@ -42,7 +42,7 @@ public: using BundleFlag = OHOS::AppExecFwk::BundleFlag; using ApplicationFlag = OHOS::AppExecFwk::ApplicationFlag; OHOS::AppExecFwk::ApplicationFlag flag = OHOS::AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO; - bool bundleGroupEnable_; + bool bundleGroupEnable_ = true; bool debug_ = true; const int LEVEL_GROUP[4] = { ACTIVE_GROUP_ALIVE, @@ -75,7 +75,7 @@ public: void OnUserRemoved(const int userId); void OnBundleUninstalled(const int userId, const std::string bundleName); void OnScreenChanged(const bool& isScreenOn, const int64_t bootFromTimeStamp); - void SetBundleGroup(const std::string& bundleName, const int userId, int newGroup, int reason, + void SetBundleGroup(const std::string& bundleName, const int userId, int newGroup, uint32_t reason, const int64_t bootBasedTimeStamp, const bool& resetTimeout); void RestoreToDatabase(const int userId); void RestoreDurationToDatabase(); @@ -89,8 +89,8 @@ private: std::mutex mutex_; bool GetBundleMgrProxy(); std::weak_ptr activeGroupHandler_; - int EventToGroupReason(const int eventId); - int64_t timeoutForDirectlyUse_ = debug_ ? ONE_MINUTE : ONE_HOUR; + uint32_t EventToGroupReason(const int eventId); + int64_t timeoutForDirectlyUse_ = debug_ ? THREE_MINUTE : ONE_HOUR; int64_t timeoutForNotifySeen_ = debug_ ? ONE_MINUTE : TWELVE_HOUR; int64_t timeoutForSystemInteraction_ = debug_ ? ONE_MINUTE : TEN_MINUTE; int64_t timeoutCalculated_; diff --git a/services/packagegroup/include/bundle_active_group_handler.h b/services/packagegroup/include/bundle_active_group_handler.h index cb9ec0ddfb1df08d979a49472428dba0b5ebefde..f498c65773227982a51b42a1ec4e026f89079212 100644 --- a/services/packagegroup/include/bundle_active_group_handler.h +++ b/services/packagegroup/include/bundle_active_group_handler.h @@ -29,7 +29,7 @@ class BundleActiveGroupHandlerObject { public: std::string bundleName_; int userId_; - BundleActiveGroupHandlerObject() {}; + BundleActiveGroupHandlerObject(); BundleActiveGroupHandlerObject(const BundleActiveGroupHandlerObject& orig); ~BundleActiveGroupHandlerObject() {}; }; @@ -48,7 +48,7 @@ public: static const int MSG_CHECK_BUNDLE_STATE = 0; static const int MSG_ONE_TIME_CHECK_BUNDLE_STATE = 1; static const int MSG_CHECK_IDLE_STATE = 2; - static const int CHECK_IDLE_INTERVAL = TEN_MINUTE; + static const int CHECK_IDLE_INTERVAL = ONE_MINUTE; private: std::shared_ptr bundleActiveGroupController_; diff --git a/services/packagegroup/include/bundle_active_package_history.h b/services/packagegroup/include/bundle_active_package_history.h index c78c30408a973ad9b76a477ffe5d9d1f2a2c57f1..ff25c7ab9e91bb052944f4f20fb0952802229060 100644 --- a/services/packagegroup/include/bundle_active_package_history.h +++ b/services/packagegroup/include/bundle_active_package_history.h @@ -17,7 +17,7 @@ #define BUNDLE_ACTIVE_USAGE_HISTORY_H #include "ibundle_active_service.h" - +#include "bundle_active_group_common.h" namespace OHOS { namespace DeviceUsageStats { class BundleActivePackageHistory { @@ -27,10 +27,10 @@ public: int64_t lastGroupCalculatedTimeStamp_; int lastCalculatedGroup_; int currentGroup_; - int reasonInGroup_; + uint32_t reasonInGroup_; int64_t bundleAliveTimeoutTimeStamp_; int64_t bundleDailyTimeoutTimeStamp_; - BundleActivePackageHistory() {}; + BundleActivePackageHistory(); ~BundleActivePackageHistory() {}; }; } diff --git a/services/packagegroup/include/bundle_active_user_history.h b/services/packagegroup/include/bundle_active_user_history.h index edfe5646cb4b8269aeb09bac8839b92930c4a0dd..5449c0f6f77133e4b77f4bace27a66f995744788 100644 --- a/services/packagegroup/include/bundle_active_user_history.h +++ b/services/packagegroup/include/bundle_active_user_history.h @@ -47,10 +47,10 @@ public: int64_t GetBootBasedTimeStamp(int64_t bootBasedTimeStamp); int64_t GetScreenOnTimeStamp(int64_t bootBasedTimeStamp); void ReportUsage(std::shared_ptr oneBundleUsageHistory, const std::string& bundleName, - const int newGroup, const int groupReason, const int64_t bootBasedTimeStamp, + const int newGroup, const uint32_t groupReason, const int64_t bootBasedTimeStamp, const int64_t timeUntilNextCheck); void SetBundleGroup(const std::string& bundleName, const int userId, const int64_t bootBasedTimeStamp, - int newGroup, int groupReason, const bool& resetTimeout); + int newGroup, uint32_t groupReason, const bool& resetTimeout); int GetLevelIndex(const std::string& bundleName, const int userId, const int64_t bootBasedTimeStamp, const int64_t screenTimeLevel[4], const int64_t bootFromTimeLevel[4]); void WriteDeviceDuration(); diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index ca79fead8deee27763ffbc680d3a25f559bdab55..f89d4bf08a94e3bfd1a4e55ec13d40f18c4b9515 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -23,6 +23,11 @@ namespace OHOS { namespace DeviceUsageStats { using namespace DeviceUsageStatsGroupConst; +BundleActiveGroupHandlerObject::BundleActiveGroupHandlerObject() +{ + bundleName_ = ""; + userId_ = -1; +} void BundleActiveGroupController::RestoreDurationToDatabase() { @@ -52,7 +57,7 @@ void BundleActiveGroupController::SetHandlerAndCreateUserHistory( const std::shared_ptr& groupHandler, const int64_t bootFromTimeStamp) { if (bundleUserHistory_ == nullptr) { - BUNDLE_ACTIVE_LOGI("BundleActiveGroupController::SetHandlerAndCreateUserHistory bundleUserHistory_ is null, " + BUNDLE_ACTIVE_LOGI("SetHandlerAndCreateUserHistory bundleUserHistory_ is null, " "called constructor, bootstamp is %{public}lld", bootFromTimeStamp); bundleUserHistory_ = std::make_shared(bootFromTimeStamp); } @@ -96,7 +101,7 @@ bool BundleActiveGroupController::GetBundleMgrProxy() void BundleActiveGroupController::PeriodCheckBundleState(const int userId) { - BUNDLE_ACTIVE_LOGI("BundleActiveGroupController::PeriodCheckBundleState called"); + BUNDLE_ACTIVE_LOGI("PeriodCheckBundleState called"); if (!activeGroupHandler_.expired()) { BundleActiveGroupHandlerObject tmpGroupHandlerObj; tmpGroupHandlerObj.userId_ = userId; @@ -110,10 +115,10 @@ void BundleActiveGroupController::PeriodCheckBundleState(const int userId) bool BundleActiveGroupController::CheckEachBundleState(const int userId) { - BUNDLE_ACTIVE_LOGI("BundleActiveGroupController::CheckEachBundleState called, userid is %{public}d", userId); + BUNDLE_ACTIVE_LOGI("CheckEachBundleState called, userid is %{public}d", userId); std::vector allBundlesForUser; if (!GetBundleMgrProxy()) { - BUNDLE_ACTIVE_LOGE("BundleActiveGroupController::CheckEachBundleState get bundle manager proxy failed!"); + BUNDLE_ACTIVE_LOGE("CheckEachBundleState get bundle manager proxy failed!"); return false; } sptrBundleMgr_->GetApplicationInfos(flag, userId, allBundlesForUser); @@ -126,7 +131,6 @@ bool BundleActiveGroupController::CheckEachBundleState(const int userId) for (auto oneBundleName : bundleNamesOfUser) { CheckAndUpdateGroup(oneBundleName, userId, bootBasedTimeStamp); } - bundleUserHistory_->printdata(userId); return true; } @@ -161,7 +165,7 @@ bool BundleActiveGroupController::calculationTimeOut( - lastGroupCalculatedTimeStamp > timeoutCalculated_; } -int BundleActiveGroupController::EventToGroupReason(const int eventId) +uint32_t BundleActiveGroupController::EventToGroupReason(const int eventId) { switch (eventId) { case BundleActiveEvent::ABILITY_FOREGROUND: @@ -184,7 +188,7 @@ int BundleActiveGroupController::EventToGroupReason(const int eventId) void BundleActiveGroupController::ReportEvent(const BundleActiveEvent& event, const int64_t bootBasedTimeStamp, const int userId) { - BUNDLE_ACTIVE_LOGI("BundleActiveGroupController::ReportEvent called"); + BUNDLE_ACTIVE_LOGI("ReportEvent called"); if (bundleGroupEnable_ == false) { return; } @@ -244,8 +248,8 @@ void BundleActiveGroupController::CheckAndUpdateGroup(const std::string& bundleN if (oneBundleHistory == nullptr) { return; } - int groupReason = oneBundleHistory->reasonInGroup_; - int oldGroupControlReason = groupReason & GROUP_CONTROL_REASON_MASK; + uint32_t groupReason = oneBundleHistory->reasonInGroup_; + uint32_t oldGroupControlReason = groupReason & GROUP_CONTROL_REASON_MASK; if (oldGroupControlReason == GROUP_CONTROL_REASON_FORCED) { return; } @@ -272,13 +276,13 @@ void BundleActiveGroupController::CheckAndUpdateGroup(const std::string& bundleN GROUP_EVENT_REASON_ALIVE_TIMEOUT; } if (oldGroup < newGroup) { - BUNDLE_ACTIVE_LOGI("BundleActiveGroupController::CheckAndUpdateGroup called SetBundleGroup"); + BUNDLE_ACTIVE_LOGI("CheckAndUpdateGroup called SetBundleGroup"); bundleUserHistory_->SetBundleGroup(bundleName, userId, bootBasedTimeStamp, newGroup, groupReason, false); } } void BundleActiveGroupController::SetBundleGroup(const std::string& bundleName, const int userId, int newGroup, - int reason, const int64_t bootBasedTimeStamp, const bool& resetTimeout) + uint32_t reason, const int64_t bootBasedTimeStamp, const bool& resetTimeout) { std::lock_guard lock(mutex_); if (IsBundleInstalled(bundleName, userId) == false) { @@ -291,6 +295,9 @@ void BundleActiveGroupController::SetBundleGroup(const std::string& bundleName, 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(), bootBasedTimeStampAdjusted, oneBundleHistory->bundleAliveTimeoutTimeStamp_); newGroup = ACTIVE_GROUP_ALIVE; reason = oneBundleHistory->reasonInGroup_; } else if (newGroup > ACTIVE_GROUP_DAILY && oneBundleHistory->bundleDailyTimeoutTimeStamp_ > @@ -317,11 +324,11 @@ int BundleActiveGroupController::IsBundleIdle(const std::string& bundleName, con if (oneBundleHistory == nullptr) { return 1; } else if (oneBundleHistory->currentGroup_ >= ACTIVE_GROUP_RARE) { - BUNDLE_ACTIVE_LOGI("BundleActiveGroupController::IsBundleIdle, bundle group is %{public}d", + BUNDLE_ACTIVE_LOGI("IsBundleIdle, bundle group is %{public}d", oneBundleHistory->currentGroup_); return 1; } else { - BUNDLE_ACTIVE_LOGI("BundleActiveGroupController::IsBundleIdle, bundle group is %{public}d", + BUNDLE_ACTIVE_LOGI("IsBundleIdle, bundle group is %{public}d", oneBundleHistory->currentGroup_); return 0; } @@ -329,7 +336,7 @@ int BundleActiveGroupController::IsBundleIdle(const std::string& bundleName, con int BundleActiveGroupController::QueryPackageGroup(const int userId, const std::string& bundleName) { - BUNDLE_ACTIVE_LOGI("BundleActiveGroupController::QueryPackageGroup called"); + BUNDLE_ACTIVE_LOGI("QueryPackageGroup called"); sptr timer = MiscServices::TimeServiceClient::GetInstance(); if (IsBundleInstalled(bundleName, userId) == false) { return -1; @@ -349,7 +356,7 @@ bool BundleActiveGroupController::IsBundleInstalled(const std::string& bundleNam ApplicationInfo bundleInfo; if (sptrBundleMgr_ != nullptr && sptrBundleMgr_->GetApplicationInfo( bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, bundleInfo) == false) { - BUNDLE_ACTIVE_LOGE("BundleActiveGroupController::IsBundleInstalled bundle is not installed!"); + BUNDLE_ACTIVE_LOGE("IsBundleInstalled bundle is not installed!"); return false; } return true; @@ -357,14 +364,14 @@ bool BundleActiveGroupController::IsBundleInstalled(const std::string& bundleNam void BundleActiveGroupController::ShutDown(const int64_t bootBasedTimeStamp) { - BUNDLE_ACTIVE_LOGI("BundleActiveGroupController::ShutDown called"); + BUNDLE_ACTIVE_LOGI("ShutDown called"); bundleUserHistory_->UpdateBootBasedAndScreenTime(false, bootBasedTimeStamp, true); } bool BundleActiveGroupController::IsScreenOn() { bool result = PowerMgrClient::GetInstance().IsScreenOn(); - BUNDLE_ACTIVE_LOGI("BundleActiveGroupController::IsScreenOn() is %{public}d", result); + BUNDLE_ACTIVE_LOGI("IsScreenOn() is %{public}d", result); return result; } } diff --git a/services/packagegroup/src/bundle_active_group_handler.cpp b/services/packagegroup/src/bundle_active_group_handler.cpp index ce1e0898361635bbbc535092faada9508f1223c6..ff45231868fdf2db32b783bbc47f0aaf3623e08a 100644 --- a/services/packagegroup/src/bundle_active_group_handler.cpp +++ b/services/packagegroup/src/bundle_active_group_handler.cpp @@ -33,9 +33,9 @@ BundleActiveGroupHandler::BundleActiveGroupHandler void BundleActiveGroupHandler::Init(const std::shared_ptr& bundleActiveController) { - BUNDLE_ACTIVE_LOGI("BundleActiveGroupHandler::Init called"); + BUNDLE_ACTIVE_LOGI("Init called"); if (bundleActiveController == nullptr) { - BUNDLE_ACTIVE_LOGE("BundleActiveGroupHandler::Init failed bundleActiveController is null"); + BUNDLE_ACTIVE_LOGE("Init failed bundleActiveController is null"); } bundleActiveGroupController_ = bundleActiveController; } @@ -64,7 +64,7 @@ void BundleActiveGroupHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointe BUNDLE_ACTIVE_LOGI("BundleActiveCore::GetAllActiveUser size is 0"); return; } - for (int i = 0; i < osAccountInfos.size(); i++) { + for (uint32_t i = 0; i < osAccountInfos.size(); i++) { bundleActiveGroupController_->CheckEachBundleState(osAccountInfos[i].GetLocalId()); bundleActiveGroupController_->RestoreToDatabase(osAccountInfos[i].GetLocalId()); } diff --git a/services/packagegroup/src/bundle_active_user_history.cpp b/services/packagegroup/src/bundle_active_user_history.cpp index 3399f2b09332f013a9aa1c804e6a0f6778832264..5179f8fec2590dc021ce82c4e28b6f5572643ddf 100644 --- a/services/packagegroup/src/bundle_active_user_history.cpp +++ b/services/packagegroup/src/bundle_active_user_history.cpp @@ -22,6 +22,17 @@ namespace DeviceUsageStats { using namespace DeviceUsageStatsGroupConst; using namespace std; +BundleActivePackageHistory::BundleActivePackageHistory() +{ + lastBootFromUsedTimeStamp_ = 0; + lastScreenUsedTimeStamp_ = 0; + lastGroupCalculatedTimeStamp_ = 0; + currentGroup_ = DeviceUsageStatsGroupConst::ACTIVE_GROUP_NEVER; + reasonInGroup_ = DeviceUsageStatsGroupConst::GROUP_CONTROL_REASON_DEFAULT; + bundleAliveTimeoutTimeStamp_ = 0; + bundleDailyTimeoutTimeStamp_ = 0; +}; + void BundleActiveUserHistory::WriteDeviceDuration() { database_.PutDurationData(bootBasedDuration_, ScreenOnDuration_); @@ -29,10 +40,10 @@ void BundleActiveUserHistory::WriteDeviceDuration() void BundleActiveUserHistory::WriteBundleUsage(const int userId) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserHistory::WriteBundleUsage called"); + BUNDLE_ACTIVE_LOGI("WriteBundleUsage called"); auto userHistory = GetUserHistory(userId, false); if (userHistory == nullptr) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserHistory::WriteBundleUsage called, no existed user history, return"); + BUNDLE_ACTIVE_LOGI("WriteBundleUsage called, no existed user history, return"); return; } database_.PutBundleHistoryData(userId, userHistory); @@ -62,6 +73,9 @@ int BundleActiveUserHistory::GetLevelIndex(const string& bundleName, const int u } int64_t screenDiff = GetScreenOnTimeStamp(bootBasedTimeStamp) - oneBundleHistory->lastScreenUsedTimeStamp_; int64_t bootFromDiff = GetBootBasedTimeStamp(bootBasedTimeStamp) - oneBundleHistory->lastBootFromUsedTimeStamp_; + BUNDLE_ACTIVE_LOGI("screendiff is %{public}lld, bootfromdiff is %{public}lld, bundle name is %{public}s," + "userid is %{public}d", + screenDiff, bootFromDiff, bundleName.c_str(), userId); for (int i = 3; i >= 0; i--) { if (screenDiff >= screenTimeLevel[i] && bootFromDiff >= bootFromTimeLevel[i]) { return i; @@ -92,11 +106,11 @@ shared_ptr>> BundleActiveUser shared_ptr>> usageHistoryInserted = database_.GetBundleHistoryData(userId); if (usageHistoryInserted == nullptr) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserHistory::GetUserHistory READ FROM DATABASE FAILD"); + BUNDLE_ACTIVE_LOGI("GetUserHistory READ FROM DATABASE FAILD"); usageHistoryInserted = make_shared>>(); } - BUNDLE_ACTIVE_LOGI("BundleActiveUserHistory::GetUserHistory usageHistoryInserted not null"); + BUNDLE_ACTIVE_LOGI("GetUserHistory usageHistoryInserted not null"); userHistory_[userId] = usageHistoryInserted; } return userHistory_[userId]; @@ -139,7 +153,7 @@ shared_ptr BundleActiveUserHistory::GetUsageHistoryF } void BundleActiveUserHistory::ReportUsage(shared_ptr oneBundleUsageHistory, - const string& bundleName, const int newGroup, const int groupReason, const int64_t bootBasedTimeStamp, + const string& bundleName, const int newGroup, const uint32_t groupReason, const int64_t bootBasedTimeStamp, const int64_t timeUntilNextCheck) { if (timeUntilNextCheck > bootBasedTimeStamp) { @@ -166,8 +180,10 @@ void BundleActiveUserHistory::ReportUsage(shared_ptr } void BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int userId, - const int64_t bootBasedTimeStamp, int newGroup, int groupReason, const bool& resetTimeout) + const int64_t bootBasedTimeStamp, int newGroup, uint32_t groupReason, const bool& resetTimeout) { + 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) { @@ -207,7 +223,7 @@ void BundleActiveUserHistory::UpdateBootBasedAndScreenTime(const bool& isScreenO void BundleActiveUserHistory::printdata(int userId) { auto oneUserHistory = GetUserHistory(userId, false); - BUNDLE_ACTIVE_LOGI("BundleActiveUserHistory::printdata screen is %{public}d", isScreenOn_); + BUNDLE_ACTIVE_LOGI("printdata screen is %{public}d", isScreenOn_); if (oneUserHistory == nullptr) { return; } diff --git a/services/packageusage/include/bundle_active_calendar.h b/services/packageusage/include/bundle_active_calendar.h index fa0d88db5bddc7f69b3df984243630d4c259aab9..2e7a2f4e57d002bcb980e07a1d497afc0df07654 100644 --- a/services/packageusage/include/bundle_active_calendar.h +++ b/services/packageusage/include/bundle_active_calendar.h @@ -23,10 +23,10 @@ namespace DeviceUsageStats { class BundleActiveCalendar { public: static const int64_t ONE_SECOND_MILLISECONDS = 1000; - static const int64_t DAY_MILLISECONDS = (int64_t)1 * 1 * 30 * 60 * 1000; - static const int64_t WEEK_MILLISECONDS = (int64_t)7 * 24 * 60 * 60 * 1000; - static const int64_t MONTH_MILLISECONDS = (int64_t)30 * 24 * 60 * 60 * 1000; - static const int64_t YEAR_MILLISECONDS = (int64_t)365 * 24 * 60 * 60 * 1000; + static const int64_t DAY_MILLISECONDS = (int64_t)1 * 1 * 10 * 60 * 1000; + static const int64_t WEEK_MILLISECONDS = (int64_t)1 * 1 * 20 * 60 * 1000; + static const int64_t MONTH_MILLISECONDS = (int64_t)1 * 1 * 30 * 60 * 1000; + static const int64_t YEAR_MILLISECONDS = (int64_t)1 * 1 * 40 * 60 * 1000; BundleActiveCalendar(const int64_t timeStamp); BundleActiveCalendar() { diff --git a/services/packageusage/include/bundle_active_event.h b/services/packageusage/include/bundle_active_event.h index d4383847f81b245fb187f80c20657e8457648471..4e66b230df12a8d0f2fafab7375dae3fdd46bcd7 100644 --- a/services/packageusage/include/bundle_active_event.h +++ b/services/packageusage/include/bundle_active_event.h @@ -47,10 +47,9 @@ public: std::string abilityId_; int64_t timeStamp_; int eventId_; - bool isidle_; public: - BundleActiveEvent() {}; + BundleActiveEvent(); BundleActiveEvent(const BundleActiveEvent& orig); BundleActiveEvent(int eventId, int64_t timeStamp); std::string GetBundleName(); @@ -58,7 +57,6 @@ public: std::string GetAbilityId(); int64_t GetTimeStamp(); int GetEventId(); - bool GetIsIdle(); virtual bool Marshalling(Parcel &parcel) const override; std::shared_ptr Unmarshalling(Parcel &parcel); }; diff --git a/services/packageusage/include/bundle_active_event_stats.h b/services/packageusage/include/bundle_active_event_stats.h index a2f390016721708f69af820c2a459e01097d9325..77d9e2daaf32fa49342bfac0f33717572cecae3a 100644 --- a/services/packageusage/include/bundle_active_event_stats.h +++ b/services/packageusage/include/bundle_active_event_stats.h @@ -28,7 +28,7 @@ public: int64_t lastEventTime_; int64_t totalTime_; int count_; - BundleActiveEventStats() {}; + BundleActiveEventStats(); BundleActiveEventStats(const BundleActiveEventStats& orig); int GetEventId(); int GetFirstTimeStamp(); diff --git a/services/packageusage/include/bundle_active_stats_update_listener.h b/services/packageusage/include/bundle_active_stats_update_listener.h index 5f0b3b82e58617f21fd65fd7c5cacb35737e48fd..6968b6cec6be60fe586a735c89c9d913e93d2365 100644 --- a/services/packageusage/include/bundle_active_stats_update_listener.h +++ b/services/packageusage/include/bundle_active_stats_update_listener.h @@ -19,7 +19,7 @@ namespace OHOS { namespace DeviceUsageStats { class BundleActiveStatsUpdateListener { - virtual void OnStatsChanged() = 0; + virtual void OnStatsChanged(const int userId) = 0; virtual void OnStatsReload() = 0; virtual void OnSystemUpdate(int userId) = 0; }; diff --git a/services/packageusage/include/bundle_active_user_service.h b/services/packageusage/include/bundle_active_user_service.h index 1f4dfcf103db15f22844fdc91c42d4e7c77d2621..6aa13e79464ec01e237502bc8d9580eb69d15800 100644 --- a/services/packageusage/include/bundle_active_user_service.h +++ b/services/packageusage/include/bundle_active_user_service.h @@ -44,9 +44,9 @@ public: } void Init(const int64_t timeStamp); ~BundleActiveUserService() {}; - void ReportForFlushAndShutdown(const BundleActiveEvent& event); + void ReportForShutdown(const BundleActiveEvent& event); void ReportEvent(const BundleActiveEvent& event); - void RestoreStats(); + void RestoreStats(bool forced); void RenewStatsInMemory(const int64_t timeStamp); void RenewTableTime(int64_t oldTime, int64_t newTime); void OnUserRemoved(); @@ -57,6 +57,7 @@ public: const int64_t endTime, const int userId, const std::string& bundleName); std::vector QueryEvents(const int64_t beginTime, const int64_t endTime, const int userId, const std::string& bundleName); + void LoadActiveStats(const int64_t timeStamp, const bool& force, const bool& timeChanged); private: static const int64_t ONE_SECOND_MILLISECONDS = 1000; @@ -68,7 +69,6 @@ private: inline static const std::vector PERIOD_LENGTH = {BundleActiveCalendar::DAY_MILLISECONDS, BundleActiveCalendar::WEEK_MILLISECONDS, BundleActiveCalendar::MONTH_MILLISECONDS, BundleActiveCalendar::YEAR_MILLISECONDS}; - void LoadActiveStats(const int64_t timeStamp, const bool& force); void NotifyStatsChanged(); void NotifyNewUpdate(); void printstat(); diff --git a/services/packageusage/src/bundle_active_event.cpp b/services/packageusage/src/bundle_active_event.cpp index c29ebc33a3561ada5be5044f361aa3832fb95735..bc6c81ffbf1675aaef844fe1d002d8a69f04ae93 100644 --- a/services/packageusage/src/bundle_active_event.cpp +++ b/services/packageusage/src/bundle_active_event.cpp @@ -17,6 +17,16 @@ namespace OHOS { namespace DeviceUsageStats { +BundleActiveEvent::BundleActiveEvent() +{ + bundleName_ = ""; + continuousTaskAbilityName_ = ""; + abilityName_ = ""; + abilityId_ = ""; + timeStamp_ = 0; + eventId_ = 0; +} + BundleActiveEvent::BundleActiveEvent (const BundleActiveEvent& orig) { bundleName_ = orig.bundleName_; @@ -24,7 +34,6 @@ BundleActiveEvent::BundleActiveEvent (const BundleActiveEvent& orig) abilityId_ = orig.abilityId_; timeStamp_ = orig.timeStamp_; eventId_ = orig.eventId_; - isidle_ = orig.isidle_; } BundleActiveEvent::BundleActiveEvent(int eventId, int64_t timeStamp) @@ -61,11 +70,6 @@ int BundleActiveEvent::GetEventId() return eventId_; } -bool BundleActiveEvent::GetIsIdle() -{ - return isidle_; -} - bool BundleActiveEvent::Marshalling(Parcel &parcel) const { if (parcel.WriteString(bundleName_) && diff --git a/services/packageusage/src/bundle_active_event_list.cpp b/services/packageusage/src/bundle_active_event_list.cpp index 86d0c3da95211a8ab179460d17096fc530a91d19..51c081b3aa94bcdde9aaa21620948ee76b094ad3 100644 --- a/services/packageusage/src/bundle_active_event_list.cpp +++ b/services/packageusage/src/bundle_active_event_list.cpp @@ -33,7 +33,7 @@ void BundleActiveEventList::Clear() void BundleActiveEventList::Insert(BundleActiveEvent event) { - int size = events_.size(); + uint32_t size = events_.size(); if (size == 0 || event.timeStamp_ >= events_.back().timeStamp_) { events_.push_back(event); return; @@ -44,7 +44,7 @@ void BundleActiveEventList::Insert(BundleActiveEvent event) int BundleActiveEventList::FindBestIndex(const int64_t timeStamp) { - int size = events_.size(); + int size = static_cast(events_.size()); int result = size; int lo = 0; int hi = size - 1; @@ -63,7 +63,7 @@ int BundleActiveEventList::FindBestIndex(const int64_t timeStamp) void BundleActiveEventList::Merge(const BundleActiveEventList& right) { - int size = right.events_.size(); + int size = static_cast(right.events_.size()); for (int i = 0; i < size; i++) { Insert(right.events_[i]); } diff --git a/services/packageusage/src/bundle_active_event_stats.cpp b/services/packageusage/src/bundle_active_event_stats.cpp index 02d527cb37463c6c9022c64c52a3bf15e345bbb1..4dfa187ada9a155923a4604cf46893cf64c21095 100644 --- a/services/packageusage/src/bundle_active_event_stats.cpp +++ b/services/packageusage/src/bundle_active_event_stats.cpp @@ -17,6 +17,15 @@ namespace OHOS { namespace DeviceUsageStats { +BundleActiveEventStats::BundleActiveEventStats() +{ + beginTimeStamp_ = 0; + endTimeStamp_ = 0; + lastEventTime_ = 0; + totalTime_ = 0; + count_ = 0; +} + BundleActiveEventStats::BundleActiveEventStats(const BundleActiveEventStats& orig) { eventId_ = orig.eventId_; diff --git a/services/packageusage/src/bundle_active_event_tracker.cpp b/services/packageusage/src/bundle_active_event_tracker.cpp index 85d828bb2ce916b784d66b956e52eb242ff95f48..caea54dd95861f0c6cab241d415119f6950f993d 100644 --- a/services/packageusage/src/bundle_active_event_tracker.cpp +++ b/services/packageusage/src/bundle_active_event_tracker.cpp @@ -27,7 +27,7 @@ BundleActiveEventTracker::BundleActiveEventTracker() void BundleActiveEventTracker::CommitTime(const int64_t timeStamp) { - if (curStartTime_ != 0) { + if (curStartTime_) { duration_ += timeStamp - curStartTime_; curStartTime_ = 0; } @@ -35,7 +35,7 @@ void BundleActiveEventTracker::CommitTime(const int64_t timeStamp) void BundleActiveEventTracker::Update(int64_t timeStamp) { - if (curStartTime_ == 0) { + if (!curStartTime_) { count_++; } CommitTime(timeStamp); @@ -46,7 +46,7 @@ void BundleActiveEventTracker::Update(int64_t timeStamp) void BundleActiveEventTracker::AddToEventStats(std::vector& eventStatsList, int eventId, int64_t beginTime, int64_t endTime) { - if (count_ != 0 || duration_ != 0) { + if (count_ || duration_) { BundleActiveEventStats newEvent; newEvent.eventId_ = eventId; newEvent.count_ = count_; diff --git a/services/packageusage/src/bundle_active_package_stats.cpp b/services/packageusage/src/bundle_active_package_stats.cpp index 01048a2b0e44e06a530a8a0b6ec9a09c42fec7f8..95205f0dee2e2571c838a55899b65fb42557e952 100644 --- a/services/packageusage/src/bundle_active_package_stats.cpp +++ b/services/packageusage/src/bundle_active_package_stats.cpp @@ -24,7 +24,7 @@ BundleActivePackageStats::BundleActivePackageStats() endTimeStamp_ = 0; // stop time of counting lastTimeUsed_ = 0; // the timestamp of last launch totalInFrontTime_ = 0; // the total time of bundle in front. - lastContiniousTaskUsed_ = 0; // the timestamp of bundle calling a continuous task. + lastContiniousTaskUsed_ = -1; // the timestamp of bundle calling a continuous task. totalContiniousTaskUsedTime_ = 0; // the total time of bundle use continuous tasks. startCount_ = 0; bundleStartedCount_ = 0; @@ -141,7 +141,7 @@ void BundleActivePackageStats::UpdateAbility(const int64_t timeStamp, const int std::map::iterator it = abilities_.find(abilityId); if (it != abilities_.end()) { int lastEventId = it->second; - // When we recieve a new event, first update the time stats according to the last event in map. + // When we receive a new event, first update the time stats according to the last event in map. switch (lastEventId) { case BundleActiveEvent::ABILITY_FOREGROUND: IncrementTimeUsed(timeStamp); @@ -175,7 +175,7 @@ void BundleActivePackageStats::UpdateLongTimeTask(const std::string& longTimeTas return; } - // When we recieve a new event, first update the time stats according to the last service event in map. + // When we receive a new event, first update the time stats according to the last service event in map. std::map::iterator it = longTimeTasks_.find(longTimeTaskName); if (it != longTimeTasks_.end()) { int lastEventId = it->second; diff --git a/services/packageusage/src/bundle_active_report_handler.cpp b/services/packageusage/src/bundle_active_report_handler.cpp index 87b149657d1f52af62093f8aeee383f22d22f083..d02a40d18cdee7cbb6443cd1c4810529c6789aa5 100644 --- a/services/packageusage/src/bundle_active_report_handler.cpp +++ b/services/packageusage/src/bundle_active_report_handler.cpp @@ -50,7 +50,9 @@ void BundleActiveReportHandler::ProcessEvent(const AppExecFwk::InnerEvent::Point } case MSG_FLUSH_TO_DISK: { BUNDLE_ACTIVE_LOGI("FLUSH TO DISK HANDLE"); - bundleActiveCore_->RestoreToDatabase(); + auto ptrToHandlerobj = event->GetSharedObject(); + BundleActiveReportHandlerObject tmpHandlerobj = *ptrToHandlerobj; + bundleActiveCore_->RestoreToDatabase(tmpHandlerobj.userId_); break; } case MSG_REMOVE_USER: { diff --git a/services/packageusage/src/bundle_active_stats_combiner.cpp b/services/packageusage/src/bundle_active_stats_combiner.cpp index 88ddd974801d008a9a35733f00458f014928a57b..4e63f90e1c87a6937cef850ca976d091f16d0f71 100644 --- a/services/packageusage/src/bundle_active_stats_combiner.cpp +++ b/services/packageusage/src/bundle_active_stats_combiner.cpp @@ -21,7 +21,7 @@ void BundleActiveStatsCombiner::combine( const std::shared_ptr& stats, std::vector& accumulatedResult, int64_t beginTime) { - BUNDLE_ACTIVE_LOGI("BundleActiveStatsCombiner::combine called"); + BUNDLE_ACTIVE_LOGI("BundleActivePackageStats combine called"); for (auto it : stats->bundleStats_) { if (it.second != nullptr) { accumulatedResult.push_back(*(it.second)); @@ -33,9 +33,9 @@ void BundleActiveStatsCombiner::combine(const std::shared_ptr std::vector& accumulatedResult, int64_t beginTime) { - BUNDLE_ACTIVE_LOGI("BundleActiveStatsCombiner::combine called"); + BUNDLE_ACTIVE_LOGI("BundleActiveEvent combine called"); int startIndex = stats->events_.FindBestIndex(beginTime); - int size = stats->events_.events_.size(); + int size = static_cast(stats->events_.events_.size()); for (int i = startIndex; i < size; i++) { accumulatedResult.push_back(stats->events_.events_[i]); } diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index cdc163937ced6cc91e990018a7f2ce21eb1920db..4686d761c353be675076c5f65eec21066476da10 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -21,18 +21,18 @@ namespace DeviceUsageStats { void BundleActiveUserService::Init(const int64_t timeStamp) { database_.InitDatabaseTableInfo(timeStamp); - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::Init called"); - LoadActiveStats(timeStamp, false); + BUNDLE_ACTIVE_LOGI("Init called"); + LoadActiveStats(timeStamp, false, false); std::shared_ptr currentDailyStats = currentStats_[BundleActivePeriodStats::PERIOD_DAILY]; if (currentDailyStats != nullptr) { BundleActiveEvent startupEvent(BundleActiveEvent::STARTUP, timeStamp - ONE_SECOND_MILLISECONDS); startupEvent.bundleName_ = BundleActiveEvent::DEVICE_EVENT_PACKAGE_NAME; currentDailyStats->AddEvent(startupEvent); for (auto it : currentDailyStats->events_.events_) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::Init event id is %{public}d, time stamp is %{public}lld", + BUNDLE_ACTIVE_LOGI("Init event id is %{public}d, time stamp is %{public}lld", it.eventId_, it.timeStamp_); } - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::Init currentDailyStats begintime is %{public}lld, " + BUNDLE_ACTIVE_LOGI("Init currentDailyStats begintime is %{public}lld, " "expire time is %{public}lld", currentDailyStats->beginTime_, dailyExpiryDate_.GetMilliseconds()); } } @@ -63,18 +63,18 @@ void BundleActiveUserService::DeleteUninstalledBundleStats(const std::string& bu void BundleActiveUserService::RenewTableTime(int64_t oldTime, int64_t newTime) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::RenewTableTime called"); - RestoreStats(); + BUNDLE_ACTIVE_LOGI("RenewTableTime called"); + BUNDLE_ACTIVE_LOGI("RenewTableTime called current event size is %{public}d", + currentStats_[0]->events_.Size()); database_.RenewTableTime(newTime - oldTime); - LoadActiveStats(newTime, true); } void BundleActiveUserService::NotifyStatsChanged() { if (!statsChanged_) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::NotifyStatsChanged() set stats changed to true"); + BUNDLE_ACTIVE_LOGI("NotifyStatsChanged() set stats changed to true"); statsChanged_ = true; - listener_.OnStatsChanged(); + listener_.OnStatsChanged(userId_); } } @@ -85,12 +85,12 @@ void BundleActiveUserService::NotifyNewUpdate() void BundleActiveUserService::ReportEvent(const BundleActiveEvent& event) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportEvent called"); + BUNDLE_ACTIVE_LOGI("ReportEvent, B time is %{public}lld, E time is %{public}lld", + currentStats_[0]->beginTime_, dailyExpiryDate_.GetMilliseconds()); if (event.timeStamp_ >= dailyExpiryDate_.GetMilliseconds()) { - BUNDLE_ACTIVE_LOGI(" BundleActiveUserService::ReportEvent later than daily expire"); + BUNDLE_ACTIVE_LOGI("ReportEvent later than daily expire, renew data in memory"); RenewStatsInMemory(event.timeStamp_); } - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportEvent later than daily expire check done"); std::shared_ptr currentDailyStats = currentStats_[BundleActivePeriodStats::PERIOD_DAILY]; if (!currentDailyStats) { return; @@ -126,20 +126,18 @@ void BundleActiveUserService::ReportEvent(const BundleActiveEvent& event) it->Update(event.bundleName_, event.continuousTaskAbilityName_, event.timeStamp_, event.eventId_, event.abilityId_); if (incrementBundleLaunch) { - BUNDLE_ACTIVE_LOGI(" BundleActiveUserService::ReportEvent increase bundle started count"); it->bundleStats_[event.bundleName_]->IncrementBundleLaunchedCount(); } break; } } - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportEvent called notify"); NotifyStatsChanged(); } -void BundleActiveUserService::ReportForFlushAndShutdown(const BundleActiveEvent& event) +void BundleActiveUserService::ReportForShutdown(const BundleActiveEvent& event) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportForFlushAndShutdown() called"); - if (event.eventId_ != BundleActiveEvent::FLUSH && event.eventId_ != BundleActiveEvent::SHUTDOWN) { + BUNDLE_ACTIVE_LOGI("ReportForShutdown() called"); + if (event.eventId_ != BundleActiveEvent::SHUTDOWN) { return; } if (event.eventId_ == BundleActiveEvent::SHUTDOWN) { @@ -153,30 +151,36 @@ void BundleActiveUserService::ReportForFlushAndShutdown(const BundleActiveEvent& it->Update(event.bundleName_, event.continuousTaskAbilityName_, event.timeStamp_, event.eventId_, event.abilityId_); } - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::ReportForFlushAndShutdown called notify"); + BUNDLE_ACTIVE_LOGI("ReportForShutdown called notify"); NotifyStatsChanged(); } -void BundleActiveUserService::RestoreStats() +void BundleActiveUserService::RestoreStats(bool forced) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::RestoreStats() called"); - if (statsChanged_) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::RestoreStats() stat changed is true"); - for (int i = 0; i < currentStats_.size(); i++) { - database_.UpdateUsageData(i, *(currentStats_[i])); + BUNDLE_ACTIVE_LOGI("RestoreStats() called, userId is %{public}d", userId_); + if (statsChanged_ || forced) { + BUNDLE_ACTIVE_LOGI("RestoreStats() stat changed is true"); + for (uint32_t i = 0; i < currentStats_.size(); i++) { + if (currentStats_[i] != nullptr) { + database_.UpdateUsageData(i, *(currentStats_[i])); + } + if (i == 0) { + BUNDLE_ACTIVE_LOGI("RESOTRE EVENT SIZE IS %{public}d, USER ID IS %{public}d", + currentStats_[i]->events_.Size(), userId_); + } } currentStats_[BundleActivePeriodStats::PERIOD_DAILY]->events_.Clear(); statsChanged_ = false; } } -void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const bool& force) +void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const bool& force, const bool& timeChanged) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::LoadActiveStats called"); + BUNDLE_ACTIVE_LOGI("LoadActiveStats called"); BundleActiveCalendar tmpCalendar(0); tmpCalendar.SetMilliseconds(timeStamp); tmpCalendar.TruncateTo(BundleActivePeriodStats::PERIOD_DAILY); - for (int intervalType = 0; intervalType < PERIOD_LENGTH.size(); intervalType++) { + for (uint32_t intervalType = 0; intervalType < PERIOD_LENGTH.size(); intervalType++) { if (!force && currentStats_[intervalType] != nullptr && currentStats_[intervalType]->beginTime_ == tmpCalendar.GetMilliseconds()) { continue; @@ -184,7 +188,7 @@ void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const boo std::shared_ptr stats = database_.GetCurrentUsageData(intervalType, userId_); currentStats_[intervalType].reset(); // 当前interval stat置空 if (stats != nullptr) { // 找出最近的stats - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::LoadActiveStats inter type is %{public}d, " + BUNDLE_ACTIVE_LOGI("LoadActiveStats inter type is %{public}d, " "bundle size is %{public}d", intervalType, stats->bundleStats_.size()); // 如果当前时间在stats的统计时间范围内,则可以从数据库加载数据 BUNDLE_ACTIVE_LOGI("interval type is %{public}d, database stat BEGIN time is %{public}lld, " @@ -197,7 +201,7 @@ void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const boo if (currentStats_[intervalType] != nullptr) { continue; } - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::LoadActiveStats [Server]create new interval stats!"); + BUNDLE_ACTIVE_LOGI("LoadActiveStats [Server]create new interval stats!"); currentStats_[intervalType] = std::make_shared(); currentStats_[intervalType]->userId_ = userId_; currentStats_[intervalType]->beginTime_ = tmpCalendar.GetMilliseconds(); @@ -205,11 +209,17 @@ void BundleActiveUserService::LoadActiveStats(const int64_t timeStamp, const boo } statsChanged_ = false; // 延长统计时间到第二天0点 - dailyExpiryDate_.SetMilliseconds(timeStamp); + if (timeChanged) { + dailyExpiryDate_.SetMilliseconds(currentStats_[BundleActivePeriodStats::PERIOD_DAILY]->beginTime_); + } else { + dailyExpiryDate_.SetMilliseconds(timeStamp); + } dailyExpiryDate_.IncreaseDays(1); - dailyExpiryDate_.TruncateToDay(); + if (!timeChanged) { + dailyExpiryDate_.TruncateToDay(); + } listener_.OnStatsReload(); - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::LoadActiveStats current expire time is %{public}lld, " + BUNDLE_ACTIVE_LOGI("LoadActiveStats current expire time is %{public}lld, " "begin time is %{public}lld", dailyExpiryDate_.GetMilliseconds(), tmpCalendar.GetMilliseconds()); } @@ -241,9 +251,9 @@ void BundleActiveUserService::RenewStatsInMemory(const int64_t timeStamp) } (*it)->CommitTime(dailyExpiryDate_.GetMilliseconds() - 1); } - RestoreStats(); + RestoreStats(true); database_.RemoveOldData(timeStamp); - LoadActiveStats(timeStamp, false); // 新建intervalstat或加载当前数据库数据 + LoadActiveStats(timeStamp, false, false); // 新建intervalstat或加载当前数据库数据 for (std::string continueBundleName : continueBundles) { // 更新所有事件的时间戳到新的begintime int64_t beginTime = currentStats_[BundleActivePeriodStats::PERIOD_DAILY]->beginTime_; for (std::vector>::iterator itInterval = currentStats_.begin(); @@ -260,10 +270,9 @@ void BundleActiveUserService::RenewStatsInMemory(const int64_t timeStamp) (*itInterval)->Update(continueBundleName, it->first, beginTime, it->second, ""); } } - NotifyStatsChanged(); } } - RestoreStats(); + RestoreStats(true); } std::vector BundleActiveUserService::QueryPackageStats(int intervalType, @@ -276,14 +285,10 @@ std::vector BundleActiveUserService::QueryPackageStats intervalType = BundleActivePeriodStats::PERIOD_DAILY; } } - if (intervalType < 0 || intervalType >= currentStats_.size()) { + if (intervalType < 0 || intervalType >= static_cast(currentStats_.size())) { return result; } - auto currentStats = currentStats_[intervalType]; - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryPackageStats, intervaltype is %{public}d, " - "current begin time is %{public}lld, current end time is %{public}lld", - intervalType, currentStats->beginTime_, currentStats->endTime_); if (currentStats == nullptr) { BUNDLE_ACTIVE_LOGE("current interval stat is null!"); return result; @@ -299,13 +304,10 @@ std::vector BundleActiveUserService::QueryPackageStats return result; } int64_t truncatedEndTime = std::min(currentStats->beginTime_, endTime); - - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryPackageStats bundle name is %{public}s", bundleName.c_str()); result = database_.QueryDatabaseUsageStats(intervalType, beginTime, truncatedEndTime, userId); - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryPackageStats is %{public}d", result.size()); // if we need a in-memory stats, combine current stats with result from database. if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryPackageStats need in memory stats"); + BUNDLE_ACTIVE_LOGI("QueryPackageStats need in memory stats"); for (auto it : currentStats->bundleStats_) { if (bundleName.empty()) { if ((it.second->totalInFrontTime_ != 0 || it.second->totalContiniousTaskUsedTime_ != 0) && @@ -327,7 +329,7 @@ std::vector BundleActiveUserService::QueryPackageStats std::vector BundleActiveUserService::QueryEvents(const int64_t beginTime, const int64_t endTime, const int userId, const std::string& bundleName) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryEvents called"); + BUNDLE_ACTIVE_LOGI("QueryEvents called"); std::vector result; auto currentStats = currentStats_[BundleActivePeriodStats::PERIOD_DAILY]; if (currentStats == nullptr) { @@ -337,11 +339,12 @@ std::vector BundleActiveUserService::QueryEvents(const int64_ if (beginTime >= currentStats->endTime_) { return result; } - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryEvents bundle name is %{public}s", bundleName.c_str()); + BUNDLE_ACTIVE_LOGI("QueryEvents bundle name is %{public}s", bundleName.c_str()); result = database_.QueryDatabaseEvents(beginTime, endTime, userId, bundleName); + BUNDLE_ACTIVE_LOGI("event database query size is %{public}d", result.size()); // if we need a in-memory stats, combine current stats with result from database. if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::QueryEvents need in memory stats"); + BUNDLE_ACTIVE_LOGI("QueryEvents need in memory stats"); int eventBeginIdx = currentStats->events_.FindBestIndex(beginTime); int eventSize = currentStats->events_.Size(); for (int i = eventBeginIdx; i < eventSize; i++) { @@ -357,7 +360,7 @@ std::vector BundleActiveUserService::QueryEvents(const int64_ void BundleActiveUserService::printstat() { - BUNDLE_ACTIVE_LOGI("BundleActiveUserService::printstat called"); + BUNDLE_ACTIVE_LOGI("printstat called"); int idx = 0; for (auto it : currentStats_[idx]->bundleStats_) { BUNDLE_ACTIVE_LOGI("bundle name is %{public}s", it.first.c_str()); @@ -366,7 +369,7 @@ void BundleActiveUserService::printstat() BUNDLE_ACTIVE_LOGI("event stat is, totaltime is %{public}lld, lasttimeused is %{public}lld", totalusedtime, lasttimeused); } - int size = currentStats_[idx]->events_.events_.size(); + int size = static_cast(currentStats_[idx]->events_.events_.size()); for (int i = 0; i < size; i++) { std::string abilityId = currentStats_[idx]->events_.events_[i].abilityId_; std::string abilityname = currentStats_[idx]->events_.events_[i].abilityName_;