diff --git a/BUILD.gn b/BUILD.gn index cf37d4bd1a33e1a6aee7b57d512f276d010cdd1d..9505c9170614822f71b5eba1cb59679401a5579f 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -34,7 +34,6 @@ ohos_shared_library("usagestatsinner") { ] external_deps = [ - "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", @@ -74,7 +73,6 @@ ohos_shared_library("bundlestate") { ] external_deps = [ - "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "napi:ace_napi", @@ -131,7 +129,6 @@ ohos_shared_library("usagestatservice") { "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", - "dmsfwk_standard:zuri", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/README.md b/README.md index 23a3e1c1a3a77838a08497a39a8deb801162a322..5337ed0a11e283e7d581904c0c6043e8595ebe14 100644 --- a/README.md +++ b/README.md @@ -18,16 +18,15 @@ the component will be periodically refreshed to the database for persistent stor ``` /foundation/resourceschedule/device_usage_statistics -├── ohos.build # Compilation script ├── BUILD.gn # Module compilation script +├── LICENSE # Open source protocol +├── adapter # Adaptation directory +├── bundle.json # Component decoupling and compiling script +├── frameworks # Framework layer directory ├── interfaces -│ ├── innerkits # Internal interface directory -│ └── kits # External interface directory +│   ├── innerkits # Internal interface directory +│   └── kits # External interface directory ├── services # Service layer directory -├── frameworks -│ ├── JS # External JS interface implementation directory -│ └── native # External native interface implementation directory -├── adapter # Adaptation directory └── test # Testing case directory ``` @@ -45,20 +44,20 @@ Taking app usage interface as an example, the main exposed interfaces are as fol -

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

+

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

Queries the event collection of all applications through time interval.

-

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

+

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

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

-

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

+

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

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

-

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

+

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

Queries application usage duration statistics by time interval.

queryAppUsagePriorityGroup(callback:AsyncCallback<number>):void

@@ -76,7 +75,6 @@ Taking app usage interface as an example, the main exposed interfaces are as fol There are many interfaces for device usage statistics. Take app usage interface as an example to introduce the interface logic. -- **running process**:The device usage statistics service starts and runs in the foundation process. - **device usage statistics saving time**: >1. refreshing is triggered every 30 minutes; >2. refreshing is triggered when system time changes; diff --git a/README_ZH.md b/README_ZH.md index 8d12502c47d985eba0f36498d34571d176f47dfd..8692a540c44828671e0b47ea8f1e7ae83c9d1633 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -16,16 +16,15 @@ ``` /foundation/resourceschedule/device_usage_statistics -├── ohos.build # 编译脚本 ├── BUILD.gn # 模块编译脚本 +├── LICENSE # 开源协议 +├── adapter # 适配目录 +├── bundle.json # 部件化解耦及编译脚本 +├── frameworks # 框架层目录 ├── interfaces -│ ├── innerkits # 对内接口目录 -│ └── kits # 对外接口目录 +│   ├── innerkits # 对内接口目录 +│   └── kits # 对外接口目录 ├── services # 服务层目录 -├── frameworks -│ ├── JS # 对外JS接口实现目录 -│ └── native # 对外Native接口实现目录 -├── adapter # 适配目录 └── test # 测试用例目录 ``` @@ -42,20 +41,20 @@ -

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

+

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

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

-

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

+

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

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

-

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

+

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

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

-

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

+

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

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

queryAppUsagePriorityGroup(callback:AsyncCallback<number>):void

@@ -73,7 +72,6 @@ 设备使用信息统计接口众多,以应用使用详情(app usage)接口为例,介绍接口逻辑。 -- **运行进程**:设备使用信息统计服务在foundation进程启动和运行。 - **应用使用统计信息落盘时机**: >1. 每隔30分钟触发一次刷新; >2. 系统时间变更触发一次刷新; @@ -84,7 +82,7 @@ >3. 根据起止时间查询当前应用的事件集合; >4. 根据interval(日、周、月、年)类型和起止时间查询应用的使用时长; >5. 查询调用者应用的优先级群组; ->5. 判断指定应用当前是否是空闲状态; +>6. 判断指定应用当前是否是空闲状态; ## 相关仓 diff --git a/bundle.json b/bundle.json index 014b937c47539a991fbf1ee2fb9efc57e3ba89d0..8dbbd215bd8531f6661b327d82152234da0206f7 100644 --- a/bundle.json +++ b/bundle.json @@ -31,7 +31,6 @@ "want", "appexecfwk_base", "appexecfwk_core", - "zuri", "base", "time_service", "utils", @@ -67,7 +66,8 @@ } ], "test": [ - "//foundation/resourceschedule/device_usage_statistics/test/unittest:unittest" + "//foundation/resourceschedule/device_usage_statistics/test/unittest:unittest", + "//foundation/resourceschedule/device_usage_statistics/interfaces/test/unittest/device_usage_statistics_jsunittest:js_unittest" ] } } diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp index 1beaff661e6df951717a28869afabec891d74600..e1730a60df122719adc819213cdabd0f93f9f0cf 100644 --- a/frameworks/src/bundle_state_common.cpp +++ b/frameworks/src/bundle_state_common.cpp @@ -34,7 +34,7 @@ void BundleStateCommon::GetCallbackPromiseResult(const napi_env &env, if (info.isCallback) { SetCallbackInfo(env, info.callback, info.errorCode, result); } else { - SetPromiseInfo(env, info.deferred, result); + SetPromiseInfo(env, info.deferred, result, info.errorCode); } } @@ -48,7 +48,7 @@ void BundleStateCommon::SetCallbackInfo( napi_value resultout = nullptr; napi_get_reference_value(env, callbackIn, &callback); napi_value results[ARGS_TWO] = {nullptr}; - results[PARAM_FIRST] = GetCallbackErrorValue(env, errorCode); + results[PARAM_FIRST] = GetErrorValue(env, errorCode); results[PARAM_SECOND] = result; NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &results[PARAM_FIRST], &resultout)); @@ -138,37 +138,44 @@ void BundleStateCommon::GetBundleStateInfoForResult(napi_env env, } } -void BundleStateCommon::SetPromiseInfo(const napi_env &env, const napi_deferred &deferred, const napi_value &result) +void BundleStateCommon::SetPromiseInfo(const napi_env &env, const napi_deferred &deferred, + const napi_value &result, const int &errorCode) { - napi_resolve_deferred(env, deferred, result); + if (errorCode == ERR_OK) { + napi_resolve_deferred(env, deferred, result); + } else { + napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode)); + } } -napi_value BundleStateCommon::GetCallbackErrorValue(napi_env env, int errCode) +napi_value BundleStateCommon::GetErrorValue(napi_env env, int errCode) { napi_value result = nullptr; napi_value eCode = nullptr; NAPI_CALL(env, napi_create_int32(env, errCode, &eCode)); NAPI_CALL(env, napi_create_object(env, &result)); - NAPI_CALL(env, napi_set_named_property(env, result, "data", eCode)); + NAPI_CALL(env, napi_set_named_property(env, result, "code", eCode)); return result; } -napi_value BundleStateCommon::JSParaError(const napi_env &env, const napi_ref &callback) +napi_value BundleStateCommon::JSParaError(const napi_env &env, const napi_ref &callback, const int &errorCode) { if (callback) { - return BundleStateCommon::NapiGetNull(env); + napi_value result = nullptr; + napi_create_array(env, &result); + SetCallbackInfo(env, callback, errorCode, result); + return result; } else { napi_value promise = nullptr; napi_deferred deferred = nullptr; napi_create_promise(env, &deferred, &promise); - napi_resolve_deferred(env, deferred, BundleStateCommon::NapiGetNull(env)); + napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode)); return promise; } } std::string BundleStateCommon::GetTypeStringValue(napi_env env, napi_value param, const std::string &result) { - BUNDLE_ACTIVE_LOGI("GetTypeStringValue start"); size_t size = 0; if (napi_get_value_string_utf8(env, param, nullptr, 0, &size) != BUNDLE_STATE_OK) { return result; @@ -197,33 +204,31 @@ std::string BundleStateCommon::GetTypeStringValue(napi_env env, napi_value param delete[] buf; buf = nullptr; - BUNDLE_ACTIVE_LOGI("string result: %{public}s", value.c_str()); return value; } napi_value BundleStateCommon::GetInt64NumberValue(const napi_env &env, const napi_value &value, int64_t &result) { - BUNDLE_ACTIVE_LOGI("GetInt64NumberValue start"); napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, value, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number or function expected."); + if (valuetype != napi_number) { + BUNDLE_ACTIVE_LOGE("Wrong argument type, number expected."); + return nullptr; + } napi_get_value_int64(env, value, &result); - BUNDLE_ACTIVE_LOGI("number result: %{public}lld", result); - return BundleStateCommon::NapiGetNull(env); } napi_value BundleStateCommon::GetInt32NumberValue(const napi_env &env, const napi_value &value, int32_t &result) { - BUNDLE_ACTIVE_LOGI("GetInt32NumberValue start"); napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, value, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number or function expected."); + if (valuetype != napi_number) { + BUNDLE_ACTIVE_LOGE("Wrong argument type. Number expected."); + return nullptr; + } napi_get_value_int32(env, value, &result); - BUNDLE_ACTIVE_LOGI("number result: %{public}d", result); - return BundleStateCommon::NapiGetNull(env); } diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index 8d84091dfa25928e9616a1d61b1889ebf6f2198c..b9218b9eccc5ef986a811897dcd48927de05ff28 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -15,52 +15,55 @@ #include -#include "bundle_state_common.h" #include "bundle_active_log.h" +#include "bundle_state_common.h" #include "bundle_state_data.h" +#include "bundle_state_inner_errors.h" namespace OHOS { namespace DeviceUsageStats { -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 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, - "invalid number of parameters"); + NAPI_ASSERT(env, argc == IS_IDLE_STATE_MIN_PARAMS || argc == IS_IDLE_STATE_PARAMS, + "Invalid number of parameters"); // argv[0] : bundleName - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "ParseIsIdleStateParameters invalid parameter type. " - "String expected."); std::string result = ""; params.bundleName = BundleStateCommon::GetTypeStringValue(env, argv[0], result); if (params.bundleName.empty()) { - BUNDLE_ACTIVE_LOGI("ParseIsIdleStateParameters failed, bundleName is invalid."); - return nullptr; + BUNDLE_ACTIVE_LOGE("ParseIsIdleStateParameters failed, bundleName is empty."); + params.errorCode = ERR_USAGE_STATS_BUNDLENAME_EMPTY; + } + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + if ((valuetype != napi_string) && (params.errorCode == ERR_OK)) { + BUNDLE_ACTIVE_LOGE("Wrong argument type, string expected."); + params.errorCode = ERR_USAGE_STATS_BUNDLENAME_TYPE; } // argv[1]: 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. " - "Function expected."); + NAPI_ASSERT(env, valuetype == napi_function, + "ParseIsIdleStateParameters invalid parameter type, function expected."); napi_create_reference(env, argv[1], 1, ¶ms.callback); } return BundleStateCommon::NapiGetNull(env); @@ -69,36 +72,33 @@ napi_value ParseIsIdleStateParameters(const napi_env &env, const napi_callback_i napi_value IsIdleState(napi_env env, napi_callback_info info) { IsIdleStateParamsInfo params; - if (ParseIsIdleStateParameters(env, info, params) == nullptr) { - return BundleStateCommon::JSParaError(env, params.callback); + ParseIsIdleStateParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; AsyncCallbackInfoIsIdleState *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoIsIdleState {.env = env, .asyncWork = nullptr}; if (!asyncCallbackInfo) { - return BundleStateCommon::JSParaError(env, params.callback); + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } asyncCallbackInfo->bundleName = params.bundleName; - BUNDLE_ACTIVE_LOGI("asyncCallbackInfo->bundleName: %{public}s", asyncCallbackInfo->bundleName.c_str()); BundleStateCommon::SettingCallbackPromiseInfo(env, params.callback, asyncCallbackInfo->info, promise); - napi_value resourceName = nullptr; napi_create_string_latin1(env, "IsIdleState", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, nullptr, resourceName, [](napi_env env, void *data) { - BUNDLE_ACTIVE_LOGI("IsIdleState, worker pool thread execute."); AsyncCallbackInfoIsIdleState *asyncCallbackInfo = (AsyncCallbackInfoIsIdleState *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->state = BundleActiveClient::GetInstance().IsBundleIdle( asyncCallbackInfo->bundleName); } else { + asyncCallbackInfo->info.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; BUNDLE_ACTIVE_LOGE("IsIdleState, asyncCallbackInfo == nullptr"); } - BUNDLE_ACTIVE_LOGI("IsIdleState, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoIsIdleState *asyncCallbackInfo = (AsyncCallbackInfoIsIdleState *)data; @@ -118,9 +118,7 @@ napi_value IsIdleState(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 { @@ -131,14 +129,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, - "invalid number of parameters"); + 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. " @@ -151,33 +149,28 @@ napi_value ParsePriorityGroupParameters(const napi_env &env, const napi_callback napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) { PriorityGroupParamsInfo params; - if (ParsePriorityGroupParameters(env, info, params) == nullptr) { - return BundleStateCommon::JSParaError(env, params.callback); - } - + ParsePriorityGroupParameters(env, info, params); napi_value promise = nullptr; AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoPriorityGroup {.env = env, .asyncWork = nullptr}; if (!asyncCallbackInfo) { - return BundleStateCommon::JSParaError(env, params.callback); + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } BundleStateCommon::SettingCallbackPromiseInfo(env, params.callback, asyncCallbackInfo->info, promise); - napi_value resourceName = nullptr; napi_create_string_latin1(env, "QueryAppUsagePriorityGroup", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, nullptr, resourceName, [](napi_env env, void *data) { - BUNDLE_ACTIVE_LOGI("QueryAppUsagePriorityGroup, worker pool thread execute."); AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->priorityGroup = BundleActiveClient::GetInstance().QueryPackageGroup(); } else { + asyncCallbackInfo->info.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; BUNDLE_ACTIVE_LOGE("QueryAppUsagePriorityGroup, asyncCallbackInfo == nullptr"); } - BUNDLE_ACTIVE_LOGI("QueryAppUsagePriorityGroup, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data; @@ -185,11 +178,9 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) napi_value result = nullptr; napi_create_int32(env, asyncCallbackInfo->priorityGroup, &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; @@ -197,9 +188,7 @@ napi_value QueryAppUsagePriorityGroup(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 { @@ -209,26 +198,42 @@ 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, - "invalid number of parameters"); - + NAPI_ASSERT(env, argc == STATES_MIN_PARAMS || argc == STATES_PARAMS, + "Invalid number of parameters"); + // argv[0] : beginTime if (BundleStateCommon::GetInt64NumberValue(env, argv[0], params.beginTime) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseStatesParameters failed, beginTime is invalid."); - return nullptr; + BUNDLE_ACTIVE_LOGE("ParseStatesParameters failed, beginTime type is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) + && (params.beginTime < TIME_NUMBER_MIN)) { + BUNDLE_ACTIVE_LOGE("ParseStatesParameters failed, beginTime value is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; } // argv[1] : endTime - if (BundleStateCommon::GetInt64NumberValue(env, argv[1], params.endTime) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseStatesParameters failed, endTime is invalid."); - return nullptr; + if ((params.errorCode == ERR_OK) + && (BundleStateCommon::GetInt64NumberValue(env, argv[1], params.endTime) == nullptr)) { + BUNDLE_ACTIVE_LOGE("ParseStatesParameters failed, endTime type is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) + && (params.endTime < TIME_NUMBER_MIN)) { + BUNDLE_ACTIVE_LOGE("ParseStatesParameters failed, endTime value is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) && (params.endTime <= params.beginTime)) { + BUNDLE_ACTIVE_LOGE("ParseStatesParameters endTime(%{public}lld) <= beginTime(%{public}lld)", + params.endTime, params.beginTime); + params.errorCode = ERR_USAGE_STATS_TIME_INTERVAL; } // 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. " @@ -241,15 +246,16 @@ napi_value ParseStatesParameters(const napi_env &env, const napi_callback_info & napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info) { StatesParamsInfo params; - if (ParseStatesParameters(env, info, params) == nullptr) { - return BundleStateCommon::JSParaError(env, params.callback); + ParseStatesParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; AsyncCallbackInfoStates *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoStates {.env = env, .asyncWork = nullptr}; if (!asyncCallbackInfo) { - return BundleStateCommon::JSParaError(env, params.callback); + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } asyncCallbackInfo->beginTime = params.beginTime; BUNDLE_ACTIVE_LOGI("QueryCurrentBundleActiveStates asyncCallbackInfo->beginTime: %{public}lld", @@ -266,16 +272,15 @@ napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info) nullptr, resourceName, [](napi_env env, void *data) { - BUNDLE_ACTIVE_LOGI("QueryCurrentBundleActiveStates, worker pool thread execute."); AsyncCallbackInfoStates *asyncCallbackInfo = (AsyncCallbackInfoStates *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->BundleActiveState = BundleActiveClient::GetInstance().QueryCurrentEvents(asyncCallbackInfo->beginTime, asyncCallbackInfo->endTime); } else { + asyncCallbackInfo->info.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; BUNDLE_ACTIVE_LOGE("QueryCurrentBundleActiveStates, asyncCallbackInfo == nullptr"); } - BUNDLE_ACTIVE_LOGI("QueryCurrentBundleActiveStates, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoStates *asyncCallbackInfo = (AsyncCallbackInfoStates *)data; @@ -288,7 +293,6 @@ napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info) if (asyncCallbackInfo->info.callback != nullptr) { napi_delete_reference(env, asyncCallbackInfo->info.callback); } - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; asyncCallbackInfo = nullptr; @@ -309,15 +313,16 @@ napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info) napi_value QueryBundleActiveStates(napi_env env, napi_callback_info info) { StatesParamsInfo params; - if (ParseStatesParameters(env, info, params) == nullptr) { - return BundleStateCommon::JSParaError(env, params.callback); + ParseStatesParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; AsyncCallbackInfoStates *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoStates {.env = env, .asyncWork = nullptr}; if (!asyncCallbackInfo) { - return BundleStateCommon::JSParaError(env, params.callback); + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } asyncCallbackInfo->beginTime = params.beginTime; BUNDLE_ACTIVE_LOGI("QueryBundleActiveStates asyncCallbackInfo->beginTime: %{public}lld", @@ -334,16 +339,15 @@ napi_value QueryBundleActiveStates(napi_env env, napi_callback_info info) nullptr, resourceName, [](napi_env env, void *data) { - BUNDLE_ACTIVE_LOGI("QueryBundleActiveStates, worker pool thread execute."); AsyncCallbackInfoStates *asyncCallbackInfo = (AsyncCallbackInfoStates *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->BundleActiveState = BundleActiveClient::GetInstance().QueryEvents(asyncCallbackInfo->beginTime, asyncCallbackInfo->endTime); } else { + asyncCallbackInfo->info.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; BUNDLE_ACTIVE_LOGE("QueryBundleActiveStates, asyncCallbackInfo == nullptr"); } - BUNDLE_ACTIVE_LOGI("QueryBundleActiveStates, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoStates *asyncCallbackInfo = (AsyncCallbackInfoStates *)data; @@ -352,11 +356,9 @@ napi_value QueryBundleActiveStates(napi_env env, napi_callback_info info) napi_create_array(env, &result); BundleStateCommon::GetBundleActiveEventForResult(env, asyncCallbackInfo->BundleActiveState, 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; @@ -364,9 +366,7 @@ napi_value QueryBundleActiveStates(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 { @@ -377,32 +377,54 @@ 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, - "invalid number of parameters"); + NAPI_ASSERT(env, argc == APP_USAGE_MIN_PARAMS_BY_INTERVAL || argc == APP_USAGE_PARAMS_BY_INTERVAL, + "Invalid number of parameters"); // argv[0] : intervalType if (BundleStateCommon::GetInt32NumberValue(env, argv[0], params.intervalType) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, beginTime is invalid."); - return nullptr; + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, intervalType is invalid."); + params.errorCode = ERR_USAGE_STATS_INTERVAL_TYPE; + } + if ((params.errorCode == ERR_OK) && ((params.intervalType < INTERVAL_NUMBER_MIN) + || (params.intervalType > INTERVAL_NUMBER_MAX))) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, intervalType number is invalid."); + params.errorCode = ERR_USAGE_STATS_INTERVAL_NUMBER; } // argv[1] : beginTime - if (BundleStateCommon::GetInt64NumberValue(env, argv[1], params.beginTime) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, beginTime is invalid."); - return nullptr; + if ((params.errorCode == ERR_OK) + && (BundleStateCommon::GetInt64NumberValue(env, argv[1], params.beginTime) == nullptr)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, beginTime type is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) + && (params.beginTime < TIME_NUMBER_MIN)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, beginTime value is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; } // argv[SECOND_ARG] : endTime - if (BundleStateCommon::GetInt64NumberValue(env, argv[SECOND_ARG], params.endTime) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, endTime is invalid."); - return nullptr; + if ((params.errorCode == ERR_OK) + && (BundleStateCommon::GetInt64NumberValue(env, argv[SECOND_ARG], params.endTime) == nullptr)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, endTime type is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) + && (params.endTime < TIME_NUMBER_MIN)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval failed, endTime value is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) && (params.endTime <= params.beginTime)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParametersByInterval endTime(%{public}lld) <= beginTime(%{public}lld)", + params.endTime, params.beginTime); + params.errorCode = ERR_USAGE_STATS_TIME_INTERVAL; } // 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. " @@ -415,15 +437,16 @@ napi_value ParseAppUsageParametersByInterval(const napi_env &env, const napi_cal napi_value QueryBundleStateInfoByInterval(napi_env env, napi_callback_info info) { AppUsageParamsByIntervalInfo params; - if (ParseAppUsageParametersByInterval(env, info, params) == nullptr) { - return BundleStateCommon::JSParaError(env, params.callback); + ParseAppUsageParametersByInterval(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } - napi_value promise = nullptr; AsyncCallbackInfoAppUsageByInterval *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoAppUsageByInterval {.env = env, .asyncWork = nullptr}; if (!asyncCallbackInfo) { - return BundleStateCommon::JSParaError(env, params.callback); + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } asyncCallbackInfo->intervalType = params.intervalType; BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval asyncCallbackInfo->intervalType: %{public}d", @@ -435,24 +458,21 @@ napi_value QueryBundleStateInfoByInterval(napi_env env, napi_callback_info info) BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval asyncCallbackInfo->endTime: %{public}lld", asyncCallbackInfo->endTime); BundleStateCommon::SettingCallbackPromiseInfo(env, params.callback, asyncCallbackInfo->info, promise); - napi_value resourceName = nullptr; napi_create_string_latin1(env, "QueryBundleStateInfoByInterval", NAPI_AUTO_LENGTH, &resourceName); - napi_create_async_work(env, nullptr, resourceName, [](napi_env env, void *data) { - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval, worker pool thread execute."); AsyncCallbackInfoAppUsageByInterval *asyncCallbackInfo = (AsyncCallbackInfoAppUsageByInterval *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->packageStats = BundleActiveClient::GetInstance().QueryPackageStats(asyncCallbackInfo->intervalType, asyncCallbackInfo->beginTime, asyncCallbackInfo->endTime); } else { + asyncCallbackInfo->info.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; BUNDLE_ACTIVE_LOGE("QueryBundleStateInfoByInterval, asyncCallbackInfo == nullptr"); } - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval, worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoAppUsageByInterval *asyncCallbackInfo = (AsyncCallbackInfoAppUsageByInterval *)data; @@ -473,9 +493,7 @@ napi_value QueryBundleStateInfoByInterval(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 { @@ -485,26 +503,42 @@ 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, - "invalid number of parameters"); - + NAPI_ASSERT(env, argc == APP_USAGE_MIN_PARAMS || argc == APP_USAGE_PARAMS, + "Invalid number of parameters"); + // argv[0] : beginTime if (BundleStateCommon::GetInt64NumberValue(env, argv[0], params.beginTime) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters failed, beginTime is invalid."); - return nullptr; + BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters failed, beginTime type is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) + && (params.beginTime < TIME_NUMBER_MIN)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters failed failed, beginTime value is invalid."); + params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID; } // argv[1] : endTime - if (BundleStateCommon::GetInt64NumberValue(env, argv[1], params.endTime) == nullptr) { - BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters failed, endTime is invalid."); - return nullptr; + if ((params.errorCode == ERR_OK) + && (BundleStateCommon::GetInt64NumberValue(env, argv[1], params.endTime) == nullptr)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters failed, endTime type is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) + && (params.endTime < TIME_NUMBER_MIN)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters failed failed, endTime value is invalid."); + params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID; + } + if ((params.errorCode == ERR_OK) && (params.endTime <= params.beginTime)) { + BUNDLE_ACTIVE_LOGE("ParseAppUsageParameters endTime(%{public}lld) <= beginTime(%{public}lld)", + params.endTime, params.beginTime); + params.errorCode = ERR_USAGE_STATS_TIME_INTERVAL; } // 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. " @@ -517,14 +551,16 @@ napi_value ParseAppUsageParameters(const napi_env &env, const napi_callback_info napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) { AppUsageParamsInfo params; - if (ParseAppUsageParameters(env, info, params) == nullptr) { - return BundleStateCommon::JSParaError(env, params.callback); + ParseAppUsageParameters(env, info, params); + if (params.errorCode != ERR_OK) { + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } napi_value promise = nullptr; AsyncCallbackInfoAppUsage *asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfoAppUsage {.env = env, .asyncWork = nullptr}; if (!asyncCallbackInfo) { - return BundleStateCommon::JSParaError(env, params.callback); + params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; + return BundleStateCommon::JSParaError(env, params.callback, params.errorCode); } asyncCallbackInfo->beginTime = params.beginTime; BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos asyncCallbackInfo->beginTime: %{public}lld", @@ -539,15 +575,14 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) nullptr, resourceName, [](napi_env env, void *data) { - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos, worker pool thread execute."); AsyncCallbackInfoAppUsage *asyncCallbackInfo = (AsyncCallbackInfoAppUsage *)data; if (asyncCallbackInfo != nullptr) { asyncCallbackInfo->packageStats = BundleStateCommon::GetPackageStats(asyncCallbackInfo->beginTime, asyncCallbackInfo->endTime); } else { + asyncCallbackInfo->info.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR; BUNDLE_ACTIVE_LOGE("QueryBundleStateInfos asyncCallbackInfo == nullptr"); } - BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos worker pool thread execute end."); }, [](napi_env env, napi_status status, void *data) { AsyncCallbackInfoAppUsage *asyncCallbackInfo = (AsyncCallbackInfoAppUsage *)data; diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 1487c37189ec9db6d240c7eeae594ec3aeb2d7b9..6a3f2825d13dc2a118819baddcd9be9b33ef3a45 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -27,19 +27,19 @@ BundleActiveClient& BundleActiveClient::GetInstance() bool BundleActiveClient::GetBundleActiveProxy() { sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (samgr == nullptr) { + if (!samgr) { BUNDLE_ACTIVE_LOGE("Failed to get SystemAbilityManager."); return false; } sptr object = samgr->GetSystemAbility(DEVICE_USAGE_STATISTICS_SYS_ABILITY_ID); - if (object == nullptr) { + if (!object) { BUNDLE_ACTIVE_LOGE("Failed to get SystemAbility[1920] ."); return false; } bundleActiveProxy_ = iface_cast(object); - if (bundleActiveProxy_ == nullptr) { + if (!bundleActiveProxy_) { BUNDLE_ACTIVE_LOGE("Failed to get BundleActiveClient."); return false; } diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts index eb724fd056044215e00f8d7b64e79b1b2906762e..0734372b77c45a6e0346c9da414c196ed23e4d51 100644 --- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts +++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts @@ -30,9 +30,7 @@ declare namespace bundleState { /** * @since 7 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. - * @permission ohos.permission.BUNDLE_ACTIVE_INFO. - * @systemapi Hide this for inner system use. + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App */ interface BundleStateInfo { /** @@ -83,9 +81,7 @@ declare namespace bundleState { * The bundle name of both objects must be the same. * * @since 7 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. - * @permission ohos.permission.BUNDLE_ACTIVE_INFO. - * @systemapi Hide this for inner system use. + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App * @param toMerge Indicates the {@link BundleActiveInfo} object to merge. * if the bundle names of the two {@link BundleActiveInfo} objects are different. */ @@ -94,9 +90,7 @@ declare namespace bundleState { /** * @since 7 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. - * @permission ohos.permission.BUNDLE_ACTIVE_INFO. - * @systemapi Hide this for inner system use. + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App */ interface BundleActiveState { /** @@ -129,9 +123,7 @@ declare namespace bundleState { * Checks whether the application with a specified bundle name is in the idle state. * * @since 7 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup. - * @permission ohos.permission.BUNDLE_ACTIVE_INFO. - * @systemapi Hide this for inner system use. + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup * @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, @@ -147,9 +139,7 @@ declare namespace bundleState { * for example, restricting the running of background tasks.

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

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

* * @since 7 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. - * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @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. @@ -185,9 +173,7 @@ declare namespace bundleState { * Declares interval type. * * @since 7 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. - * @permission ohos.permission.BUNDLE_ACTIVE_INFO. - * @systemapi Hide this for inner system use. + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App */ export enum IntervalType { /** @@ -220,8 +206,8 @@ declare namespace bundleState { * Queries usage information about each bundle within a specified period at a specified interval. * * @since 7 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. - * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @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}, @@ -237,8 +223,8 @@ 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. - * @permission ohos.permission.BUNDLE_ACTIVE_INFO. + * @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. @@ -251,9 +237,7 @@ declare namespace bundleState { * Queries state data of the current bundle within a specified period. * * @since 7 - * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App. - * @permission ohos.permission.BUNDLE_ACTIVE_INFO. - * @systemapi Hide this for inner system use. + * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App * @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 5e8daf4642d1195c4b1037b9515b09ffcf867404..a8ff5e20beb17113cc1e6cf91f14253d44e8b29d 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h @@ -33,7 +33,7 @@ public: static napi_value NapiGetUndefined(napi_env env); - static napi_value GetCallbackErrorValue(napi_env env, int errCode); + static napi_value GetErrorValue(napi_env env, int errCode); static void SettingCallbackPromiseInfo( const napi_env &env, const napi_ref &callback, CallbackPromiseInfo &info, napi_value &promise); @@ -53,9 +53,10 @@ public: 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); + static void SetPromiseInfo(const napi_env &env, const napi_deferred &deferred, + const napi_value &result, const int &errorCode); - static napi_value JSParaError(const napi_env &env, const napi_ref &callback); + static napi_value JSParaError(const napi_env &env, const napi_ref &callback, const int &errorCode); static std::string GetTypeStringValue(napi_env env, napi_value param, const std::string &result); diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h index c854436457ebebaa61efb2b6335b29ef5ded1a4b..5d4f5652b1f3c6e9ae96871eaabc9736e7b7dfb6 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_data.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_data.h @@ -39,6 +39,9 @@ namespace DeviceUsageStats { #define BUNDLE_STATE_OK 0 #define INTERVAL_TYPE_DEFAULT 0 +#define INTERVAL_NUMBER_MIN 0 +#define INTERVAL_NUMBER_MAX 4 +#define TIME_NUMBER_MIN 0 struct CallbackPromiseInfo { napi_ref callback = nullptr; @@ -93,16 +96,19 @@ struct AsyncCallbackInfoAppUsage { struct IsIdleStateParamsInfo { std::string bundleName; napi_ref callback = nullptr; + int errorCode = 0; }; struct PriorityGroupParamsInfo { napi_ref callback = nullptr; + int errorCode = 0; }; struct StatesParamsInfo { int64_t beginTime; int64_t endTime; napi_ref callback = nullptr; + int errorCode = 0; }; struct AppUsageParamsByIntervalInfo { @@ -110,12 +116,14 @@ struct AppUsageParamsByIntervalInfo { int64_t beginTime; int64_t endTime; napi_ref callback = nullptr; + int errorCode = 0; }; struct AppUsageParamsInfo { int64_t beginTime; int64_t endTime; napi_ref callback = nullptr; + int errorCode = 0; }; } // namespace DeviceUsageStats } // namespace OHOS diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h new file mode 100644 index 0000000000000000000000000000000000000000..aa70a02b8fc3f21bb1c19e270fd0ef5f988e12fc --- /dev/null +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_INNER_ERRORS_H +#define FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_INNER_ERRORS_H + +#include "errors.h" + +namespace OHOS { +namespace DeviceUsageStats { +/** + * ErrCode layout + * + * +-----+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + * | Bit |31|30|29|28|27|26|25|24|23|22|21|20|19|18|17|16|15|14|13|12|11|10|09|08|07|06|05|04|03|02|01|00| + * +-----+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + * |Field|Reserved| Subsystem | Module | Code | + * +-----+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + */ + +// DeviceUsageStats's module const defined. +enum : int { + DEVICE_USAGE_STATS_MODULE_COMMON = 0x01, +}; + +// Offset of device usage stats sub-system's errcode base, number : 39911424. +constexpr ErrCode DEVICE_USAGE_STATS_COMMON_ERR_OFFSET = + ErrCodeOffset(SUBSYS_IAWARE, DEVICE_USAGE_STATS_MODULE_COMMON); +// Device Usage Stats Common Error Code Defined. +enum : int { + ERR_USAGE_STATS_BUNDLENAME_EMPTY = DEVICE_USAGE_STATS_COMMON_ERR_OFFSET + 1, + ERR_USAGE_STATS_BUNDLENAME_TYPE, + ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR, + ERR_USAGE_STATS_BEGIN_TIME_INVALID, + ERR_USAGE_STATS_END_TIME_INVALID, + ERR_USAGE_STATS_TIME_INTERVAL, + ERR_USAGE_STATS_INTERVAL_TYPE, + ERR_USAGE_STATS_INTERVAL_NUMBER, +}; +} // namespace DeviceUsageStats +} // namespace OHOS +#endif // FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_INNER_ERRORS_H \ No newline at end of file diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/BUILD.gn b/interfaces/test/unittest/device_usage_statistics_jsunittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c505e9abe098b22865f17964b992bd5331fe5b37 --- /dev/null +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/BUILD.gn @@ -0,0 +1,26 @@ +# 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. + +import("//build/test.gni") +module_output_path = "device_usage_statistics/interfaces" + +ohos_js_unittest("DeviceUsageStatisticsJsTest") { + module_out_path = module_output_path + hap_profile = "./config.json" + certificate_profile = "./ohos_device_usage_statistics.p7b" +} + +group("js_unittest") { + testonly = true + deps = [ ":DeviceUsageStatisticsJsTest" ] +} diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/config.json b/interfaces/test/unittest/device_usage_statistics_jsunittest/config.json new file mode 100644 index 0000000000000000000000000000000000000000..88bddc091de4eeb93361e08fd772e65b1a155233 --- /dev/null +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/config.json @@ -0,0 +1,74 @@ +{ + "app": { + "bundleName": "com.example.deviceUsageStatistics", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 7, + "target": 8 + } + }, + "deviceConfig": {}, + "module": { + "package": "com.example.deviceUsageStatistics", + "name": ".MyApplication", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry" + }, + "abilities": [ + { + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "backgroundModes": [ + "dataTransfer" + ], + "name": "com.example.deviceUsageStatistics.MainAbility", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "MyApplication", + "type": "page", + "launchType": "standard" + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ], + "defPermissions": [ + { + "name": "ohos.permission.BUNDLE_ACTIVE_INFO" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.BUNDLE_ACTIVE_INFO" + } + ] + } + } + \ No newline at end of file diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2b3c15cab8a7a6c856b85c3b61fa728697430139 --- /dev/null +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -0,0 +1,332 @@ +/* + * 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. + */ + +import bundleState from '@ohos.bundleState' + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + +describe("DeviceUsageStatisticsJsTest", function () { + beforeAll(function() { + /* + * @tc.setup: setup invoked before all testcases + */ + console.info('beforeAll called') + }) + + afterAll(function() { + /* + * @tc.teardown: teardown invoked after all testcases + */ + console.info('afterAll called') + }) + + beforeEach(function() { + /* + * @tc.setup: setup invoked before each testcases + */ + console.info('beforeEach called') + }) + + afterEach(function() { + /* + * @tc.teardown: teardown invoked after each testcases + */ + console.info('afterEach caled') + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest001 + * @tc.desc: test isIdleState promise. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + */ + it("DeviceUsageStatisticsJsTest001", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest001---------------------------'); + let bundleName = 'com.example.deviceUsageStatistics'; + bundleState.isIdleState(bundleName).then((res) => { + console.info('BUNDLE_ACTIVE isIdleState promise success.'); + expect(true).assertEqual(true); + }).catch((err) => { + expect(false).assertEqual(true); + console.info('BUNDLE_ACTIVE isIdleState promise failure.'); + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest002 + * @tc.desc: test isIdleState callback. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("DeviceUsageStatisticsJsTest002", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest002---------------------------'); + let bundleName = 'com.example.deviceUsageStatistics'; + bundleState.isIdleState(bundleName, (err, res) => { + if(err.code === 0) { + console.info('BUNDLE_ACTIVE isIdleState callback success.'); + expect(true).assertEqual(true); + } else { + expect(false).assertEqual(true); + console.info('BUNDLE_ACTIVE isIdleState callback failure.'); + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest003 + * @tc.desc: test queryAppUsagePriorityGroup promise. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + */ + it("DeviceUsageStatisticsJsTest003", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest003---------------------------'); + bundleState.queryAppUsagePriorityGroup().then( res => { + console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise success.'); + expect(true).assertEqual(true) + }).catch( err => { + expect(false).assertEqual(true) + console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failure.'); + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest004 + * @tc.desc: test queryAppUsagePriorityGroup callback. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("DeviceUsageStatisticsJsTest004", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest004---------------------------'); + bundleState.queryAppUsagePriorityGroup((err, res) => { + if(err.code === 0) { + console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback success.'); + expect(true).assertEqual(true) + } else { + expect(false).assertEqual(true) + console.info('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failure.'); + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest005 + * @tc.desc: test queryBundleActiveStates promise. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + */ + it("DeviceUsageStatisticsJsTest005", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest005---------------------------'); + let beginTime = 0; + let endTime = 20000000000000; + bundleState.queryBundleActiveStates(beginTime, endTime).then((res) => { + console.info('BUNDLE_ACTIVE queryBundleActiveStates promise success.'); + expect(true).assertEqual(true); + }).catch((err) => { + expect(false).assertEqual(true); + console.info('BUNDLE_ACTIVE queryBundleActiveStates promise failure.'); + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest006 + * @tc.desc: test queryBundleActiveStates callback. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("DeviceUsageStatisticsJsTest006", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest006---------------------------'); + let beginTime = 0; + let endTime = 20000000000000; + bundleState.queryBundleActiveStates(beginTime, endTime, (err, res) => { + if(err.code === 0) { + console.info('BUNDLE_ACTIVE queryBundleActiveStates callback success.'); + expect(true).assertEqual(true); + } else { + expect(false).assertEqual(true); + console.info('BUNDLE_ACTIVE queryBundleActiveStates callback failure.'); + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest007 + * @tc.desc: test queryBundleStateInfos promise. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + */ + it("DeviceUsageStatisticsJsTest007", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest007---------------------------'); + let beginTime = 0; + let endTime = 20000000000000; + bundleState.queryBundleStateInfos(beginTime, endTime).then((res) => { + console.info('BUNDLE_ACTIVE queryBundleStateInfos promise success.'); + expect(true).assertEqual(true); + }).catch((err) => { + expect(false).assertEqual(true); + console.info('BUNDLE_ACTIVE queryBundleStateInfos promise failure.'); + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest008 + * @tc.desc: test queryBundleStateInfos callback. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("DeviceUsageStatisticsJsTest008", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest008---------------------------'); + let beginTime = 0; + let endTime = 20000000000000; + bundleState.queryBundleStateInfos(beginTime, endTime, (err, res) => { + if(err.code === 0) { + console.info('BUNDLE_ACTIVE queryBundleStateInfos callback success.'); + expect(true).assertEqual(true); + } else { + expect(false).assertEqual(true); + console.info('BUNDLE_ACTIVE queryBundleStateInfos callback failure.'); + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest009 + * @tc.desc: test queryCurrentBundleActiveStates promise. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + */ + it("DeviceUsageStatisticsJsTest009", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest009---------------------------'); + let beginTime = 0; + let endTime = 20000000000000; + bundleState.queryCurrentBundleActiveStates(beginTime, endTime).then((res) => { + console.info('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.'); + expect(true).assertEqual(true); + }).catch((err) => { + expect(false).assertEqual(true); + console.info('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failure.'); + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest010 + * @tc.desc: test queryCurrentBundleActiveStates callback. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("DeviceUsageStatisticsJsTest010", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest010---------------------------'); + let beginTime = 0; + let endTime = 20000000000000; + bundleState.queryCurrentBundleActiveStates(beginTime, endTime, (err, res) => { + if(err.code === 0) { + console.info('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback success.'); + expect(true).assertEqual(true); + } else { + expect(false).assertEqual(true); + console.info('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback failure.'); + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest011 + * @tc.desc: test queryBundleStateInfoByInterval promise. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89H AR000GH89I AR000GH899 + */ + it("DeviceUsageStatisticsJsTest011", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest011---------------------------'); + let intervalType = 0; + let beginTime = 0; + let endTime = 20000000000000; + bundleState.queryBundleStateInfoByInterval(intervalType, beginTime, endTime).then((res) => { + console.info('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.'); + expect(true).assertEqual(true); + }).catch((err) => { + expect(false).assertEqual(true); + console.info('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failure.'); + }); + + setTimeout(()=>{ + done(); + }, 500); + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest012 + * @tc.desc: test queryBundleStateInfoByInterval callback. + * @tc.type: FUNC + * @tc.require: SR000GGTN7 AR000GH89E AR000GH89F AR000GH89G + */ + it("DeviceUsageStatisticsJsTest012", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest012---------------------------'); + let intervalType = 0; + let beginTime = 0; + let endTime = 20000000000000; + bundleState.queryBundleStateInfoByInterval(intervalType, beginTime, endTime, (err, res) => { + if(err.code === 0) { + console.info('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback success.'); + expect(true).assertEqual(true); + } else { + expect(false).assertEqual(true); + console.info('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback failure.'); + } + }); + + setTimeout(()=>{ + done(); + }, 500); + }) +}) \ No newline at end of file diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/ohos_device_usage_statistics.p7b b/interfaces/test/unittest/device_usage_statistics_jsunittest/ohos_device_usage_statistics.p7b new file mode 100644 index 0000000000000000000000000000000000000000..6d38035da96bab2ca3e7cdb4cc9d76c1d8cdd32f Binary files /dev/null and b/interfaces/test/unittest/device_usage_statistics_jsunittest/ohos_device_usage_statistics.p7b differ diff --git a/services/common/include/bundle_active_core.h b/services/common/include/bundle_active_core.h index 5464548fdc4cb98683a4719612120e3afe075c5f..d5fc211c87984202f932245ddca4afaadd1e17df 100644 --- a/services/common/include/bundle_active_core.h +++ b/services/common/include/bundle_active_core.h @@ -37,6 +37,7 @@ public: int userId_; std::string bundleName_; BundleActiveReportHandlerObject(); + BundleActiveReportHandlerObject(const int userId, const std::string bundleName); BundleActiveReportHandlerObject(const BundleActiveReportHandlerObject& orig); ~BundleActiveReportHandlerObject() {}; }; @@ -116,10 +117,11 @@ public: const int64_t timeStamp); // when received a USER_REMOVED commen event, call it to remove data. void OnUserRemoved(const int userId); + void OnUserSwitched(const int userId); // force set app group. void SetBundleGroup(const std::string& bundleName, const int newGroup, const int userId); // get all user in device - void GetAllActiveUser(std::vector &osAccountInfos); + void GetAllActiveUser(std::vector& activatedOsAccountIds); // when service stop, call it to unregister commen event and shutdown call back. void UnRegisterSubscriber(); int64_t GetSystemTimeMs(); @@ -140,6 +142,7 @@ private: void RegisterSubscriber(); std::shared_ptr commonEventSubscriber_; void RestoreAllData(); + int lastUsedUser_; }; } } diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index c0ec21705dda6664982e55965135d2de37b46d7f..64732cd3c9821fb31fe4ed3e05aab679850bd786 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -66,6 +66,7 @@ private: std::shared_ptr handler_; int ConvertIntervalType(const int intervalType); void InitNecessaryState(); + void InitService(); bool GetBundleMgrProxy(); bool CheckBundleIsSystemAppAndHasPermission(const int uid, const int userId); void InitAppStateSubscriber(const std::shared_ptr& reportHandler); diff --git a/services/common/src/bundle_active_app_state_obsever.cpp b/services/common/src/bundle_active_app_state_obsever.cpp index 1bebdd57dac5cca5056e80ec05bfed8759e2b790..0a9b881012c071ef8339508c9f2c1afaa678467d 100644 --- a/services/common/src/bundle_active_app_state_obsever.cpp +++ b/services/common/src/bundle_active_app_state_obsever.cpp @@ -44,12 +44,11 @@ void BundleActiveAppStateObserver::OnAbilityStateChanged(const AbilityStateData std::stringstream stream; stream << abilityStateData.token.GetRefPtr(); std::string abilityId = stream.str(); - BundleActiveReportHandlerObject tmpHandlerObject; + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); tmpHandlerObject.event_.bundleName_ = abilityStateData.bundleName; tmpHandlerObject.event_.abilityName_ = abilityStateData.abilityName; tmpHandlerObject.event_.abilityId_ = abilityStateData.abilityName; tmpHandlerObject.event_.continuousTaskAbilityName_ = ""; - tmpHandlerObject.userId_ = userId; sptr timer = MiscServices::TimeServiceClient::GetInstance(); tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); switch (abilityStateData.abilityState) { diff --git a/services/common/src/bundle_active_binary_search.cpp b/services/common/src/bundle_active_binary_search.cpp index f16cf9348a07a1511d11350ca056d0064d28dc03..28ce0202dfafcef10071dd58de3b860e0dfafd72 100644 --- a/services/common/src/bundle_active_binary_search.cpp +++ b/services/common/src/bundle_active_binary_search.cpp @@ -30,8 +30,9 @@ int32_t BundleActiveBinarySearch::BinarySearch(const std::vector &table { int32_t low = 0; int32_t high = static_cast(tableNameArray.size() - 1); + int32_t divider = 2; while (low <= high) { - int32_t mid = (low + high) >> 1; + int32_t mid = (low + high) / divider; int64_t midValue = tableNameArray.at(mid); if (midValue < targetValue) { low = mid + 1; diff --git a/services/common/src/bundle_active_continuous_task_observer.cpp b/services/common/src/bundle_active_continuous_task_observer.cpp index 459524f71a7aebecae2d4bbb9c9a7902f4dfdc28..a64c7204a5627163651f27f8025f0b678b95e42f 100644 --- a/services/common/src/bundle_active_continuous_task_observer.cpp +++ b/services/common/src/bundle_active_continuous_task_observer.cpp @@ -88,12 +88,11 @@ void BundleActiveContinuousTaskObserver::ReportContinuousTaskEvent( OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); if (ret == ERR_OK && userId != -1 && !bundleName.empty()) { std::stringstream stream; - BundleActiveReportHandlerObject tmpHandlerObject; + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); tmpHandlerObject.event_.bundleName_ = bundleName; tmpHandlerObject.event_.abilityName_ = ""; tmpHandlerObject.event_.abilityId_ = abilityId; tmpHandlerObject.event_.continuousTaskAbilityName_ = abiliytName; - tmpHandlerObject.userId_ = userId; sptr timer = MiscServices::TimeServiceClient::GetInstance(); tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); if (isStart) { diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index 25fe675d5d0b703efff9a7c98c28dea84c847b6a..1d431ec773eba40d739eba0ecf080536e880662f 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -29,6 +29,12 @@ BundleActiveReportHandlerObject::BundleActiveReportHandlerObject() bundleName_ = ""; } +BundleActiveReportHandlerObject::BundleActiveReportHandlerObject(const int userId, const std::string bundleName) +{ + userId_ = userId; + bundleName_ = bundleName; +} + BundleActiveReportHandlerObject::BundleActiveReportHandlerObject(const BundleActiveReportHandlerObject& orig) { event_.bundleName_ = orig.event_.bundleName_; @@ -45,6 +51,7 @@ BundleActiveCore::BundleActiveCore() { systemTimeShot_ = -1; realTimeShot_ = -1; + lastUsedUser_ = -1; } BundleActiveCore::~BundleActiveCore() @@ -70,19 +77,20 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da if (!bundleActiveReportHandler_.expired()) { int32_t userId = data.GetCode(); BUNDLE_ACTIVE_LOGI("remove user id %{public}d", userId); - BundleActiveReportHandlerObject tmpHandlerObject; - tmpHandlerObject.userId_ = userId; + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); std::shared_ptr handlerobjToPtr = std::make_shared(tmpHandlerObject); auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_REMOVE_USER, handlerobjToPtr); bundleActiveReportHandler_.lock()->SendEvent(event); } - } else if (action == CommonEventSupport::COMMON_EVENT_USER_ADDED) { + } else if (action == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { int32_t userId = data.GetCode(); - BUNDLE_ACTIVE_LOGI("OnReceiveEvent receive add user event, user id is %{public}d", userId); - if (!activeGroupController_.expired() && userId >= 0) { - activeGroupController_.lock()->PeriodCheckBundleState(userId); - } + BUNDLE_ACTIVE_LOGI("OnReceiveEvent receive switched user event, user id is %{public}d", userId); + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); + std::shared_ptr handlerobjToPtr = + std::make_shared(tmpHandlerObject); + auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_SWITCH_USER, handlerobjToPtr); + bundleActiveReportHandler_.lock()->SendEvent(event); } else if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED || action == CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED) { int32_t userId = data.GetWant().GetIntParam("userId", 0); @@ -90,9 +98,7 @@ void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &da BUNDLE_ACTIVE_LOGI("action is %{public}s, userID is %{public}d, bundlename is %{public}s", action.c_str(), userId, bundleName.c_str()); if (!bundleActiveReportHandler_.expired()) { - BundleActiveReportHandlerObject tmpHandlerObject; - tmpHandlerObject.bundleName_ = bundleName; - tmpHandlerObject.userId_ = userId; + BundleActiveReportHandlerObject tmpHandlerObject(userId, bundleName); std::shared_ptr handlerobjToPtr = std::make_shared(tmpHandlerObject); auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_BUNDLE_UNINSTALLED, @@ -109,7 +115,7 @@ void BundleActiveCore::RegisterSubscriber() matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_OFF); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_ON); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED); - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_ADDED); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED); matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); @@ -157,11 +163,15 @@ void BundleActiveCore::InitBundleGroupController() BUNDLE_ACTIVE_LOGI("Init Set group controller and handler done"); } RegisterSubscriber(); - std::vector osAccountInfos; - GetAllActiveUser(osAccountInfos); + std::vector activatedOsAccountIds; bundleGroupController_->bundleGroupEnable_ = true; - for (uint32_t i = 0; i < osAccountInfos.size(); i++) { - bundleGroupController_->PeriodCheckBundleState(osAccountInfos[i].GetLocalId()); + GetAllActiveUser(activatedOsAccountIds); + if (activatedOsAccountIds.size() == 0) { + BUNDLE_ACTIVE_LOGI("query activated account failed, no account activated"); + return; + } + for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) { + bundleGroupController_->PeriodCheckBundleState(activatedOsAccountIds[i]); } } @@ -208,13 +218,16 @@ void BundleActiveCore::OnBundleUninstalled(const int userId, const std::string& void BundleActiveCore::OnStatsChanged(const int userId) { if (!handler_.expired()) { - BUNDLE_ACTIVE_LOGI("OnStatsChanged send flush to disk event"); BundleActiveReportHandlerObject tmpHandlerObject; tmpHandlerObject.userId_ = userId; std::shared_ptr handlerobjToPtr = std::make_shared(tmpHandlerObject); auto event = AppExecFwk::InnerEvent::Get(BundleActiveReportHandler::MSG_FLUSH_TO_DISK, handlerobjToPtr); - handler_.lock()->SendEvent(event, FLUSH_INTERVAL); + if (handler_.lock()->HasInnerEvent(static_cast(BundleActiveReportHandler::MSG_FLUSH_TO_DISK)) == + false) { + BUNDLE_ACTIVE_LOGI("OnStatsChanged send flush to disk event"); + handler_.lock()->SendEvent(event, FLUSH_INTERVAL); + } } } @@ -236,7 +249,7 @@ void BundleActiveCore::RestoreAllData() bundleGroupController_->RestoreDurationToDatabase(); } if (!handler_.expired()) { - BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked remove flush to disk event"); + BUNDLE_ACTIVE_LOGI("RestoreAllData remove flush to disk event"); handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); } } @@ -280,7 +293,15 @@ void BundleActiveCore::ShutDown() int64_t timeStamp = timer->GetBootTimeMs(); BundleActiveEvent event(BundleActiveEvent::SHUTDOWN, timeStamp); event.bundleName_ = BundleActiveEvent::DEVICE_EVENT_PACKAGE_NAME; - bundleGroupController_->ShutDown(timeStamp); + std::vector activatedOsAccountIds; + GetAllActiveUser(activatedOsAccountIds); + if (activatedOsAccountIds.size() == 0) { + BUNDLE_ACTIVE_LOGI("query activated account failed, no account activated"); + return; + } + for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) { + bundleGroupController_->ShutDown(timeStamp, activatedOsAccountIds[i]); + } ReportEventToAllUserId(event); RestoreAllData(); } @@ -322,7 +343,7 @@ int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime(int userId) it->second->RenewTableTime(expectedSystemTime, actualSystemTime); it->second->LoadActiveStats(actualSystemTime, true, true); if (!handler_.expired()) { - BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked remove flush to disk event"); + BUNDLE_ACTIVE_LOGI("CheckTimeChangeAndGetWallTime remove flush to disk event"); handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK); } } @@ -352,13 +373,46 @@ void BundleActiveCore::OnUserRemoved(const int userId) bundleGroupController_->OnUserRemoved(userId); } +void BundleActiveCore::OnUserSwitched(const int userId) +{ + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + auto it = userStatServices_.find(lastUsedUser_); + if (it != userStatServices_.end()) { + if (it != userStatServices_.end()) { + BUNDLE_ACTIVE_LOGI("restore old user id %{public}d data when switch user", lastUsedUser_); + BundleActiveEvent event; + event.eventId_ = BundleActiveEvent::FLUSH; + int64_t actualRealTime = timer->GetBootTimeMs(); + event.timeStamp_ = (actualRealTime - realTimeShot_) + systemTimeShot_; + event.abilityId_ = ""; + it->second->ReportEvent(event); + it->second->RestoreStats(true); + } + } + std::vector activatedOsAccountIds; + GetAllActiveUser(activatedOsAccountIds); + if (activatedOsAccountIds.size() == 0) { + BUNDLE_ACTIVE_LOGI("query activated account failed, no account activated"); + return; + } + for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) { + BUNDLE_ACTIVE_LOGI("start to period check for userId %{public}d", activatedOsAccountIds[i]); + bundleGroupController_->OnUserSwitched(activatedOsAccountIds[i]); + } + lastUsedUser_ = userId; + OnStatsChanged(userId); +} + int BundleActiveCore::ReportEvent(BundleActiveEvent& event, const int userId) { std::lock_guard lock(mutex_); - if (userId == 0) { + if (userId == 0 || userId == -1) { return -1; } - BUNDLE_ACTIVE_LOGI("ReportEvent called"); + if (lastUsedUser_ == -1) { + lastUsedUser_ = userId; + BUNDLE_ACTIVE_LOGI("last used id change to %{public}d", lastUsedUser_); + } 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(); @@ -468,14 +522,13 @@ int BundleActiveCore::IsBundleIdle(const std::string& bundleName, const int user return bundleGroupController_->IsBundleIdle(bundleName, userId); } -void BundleActiveCore::GetAllActiveUser(std::vector &osAccountInfos) +void BundleActiveCore::GetAllActiveUser(std::vector& activatedOsAccountIds) { - OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); - if (ret != ERR_OK) { - BUNDLE_ACTIVE_LOGI("GetAllActiveUser failed"); + if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(activatedOsAccountIds) != ERR_OK) { + BUNDLE_ACTIVE_LOGI("query activated account failed"); return; } - if (osAccountInfos.size() == 0) { + if (activatedOsAccountIds.size() == 0) { BUNDLE_ACTIVE_LOGI("GetAllActiveUser size is 0"); return; } diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 09eb93dc2f320b20b0c07cbba75066646051f830..652450d2660e25558d3dded3810a6e88302fb732 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -75,6 +75,24 @@ void BundleActiveService::InitNecessaryState() return; } + if (systemAbilityManager == nullptr + || systemAbilityManager->GetSystemAbility(APP_MGR_SERVICE_ID) == nullptr + || systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) == nullptr + || systemAbilityManager->GetSystemAbility(POWER_MANAGER_SERVICE_ID) == nullptr + || systemAbilityManager->GetSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr + || systemAbilityManager->GetSystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID) == nullptr + || systemAbilityManager->GetSystemAbility(TIME_SERVICE_ID) == nullptr) { + BUNDLE_ACTIVE_LOGI("request system service object is not ready yet!"); + auto task = [this]() { this->InitNecessaryState(); }; + handler_->PostTask(task, DELAY_TIME); + return; + } + + InitService(); +} + +void BundleActiveService::InitService() +{ if (bundleActiveCore_ == nullptr) { bundleActiveCore_ = std::make_shared(); bundleActiveCore_->Init(); @@ -100,7 +118,7 @@ void BundleActiveService::InitNecessaryState() } try { shutdownCallback_ = new BundleActiveShutdownCallbackService(bundleActiveCore_); - } catch(const std::bad_alloc &e) { + } catch (const std::bad_alloc &e) { BUNDLE_ACTIVE_LOGE("Memory allocation failed"); return; } @@ -118,6 +136,9 @@ OHOS::sptr BundleActiveService::GetAppManagerInstance OHOS::sptr systemAbilityManager = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); OHOS::sptr object = systemAbilityManager->GetSystemAbility(OHOS::APP_MGR_SERVICE_ID); + if (!object) { + return nullptr; + } return OHOS::iface_cast(object); } @@ -141,7 +162,7 @@ bool BundleActiveService::SubscribeAppState() { BUNDLE_ACTIVE_LOGI("SubscribeAppState called"); sptr appManager = GetAppManagerInstance(); - if (appStateObserver_ == nullptr) { + if (appStateObserver_ == nullptr || appManager == nullptr) { BUNDLE_ACTIVE_LOGE("SubscribeAppState appstateobserver is null, return"); return false; } @@ -169,7 +190,6 @@ bool BundleActiveService::SubscribeContinuousTask() return true; } - void BundleActiveService::OnStop() { if (shutdownCallback_ != nullptr) { @@ -186,14 +206,12 @@ void BundleActiveService::OnStop() int BundleActiveService::ReportEvent(std::string& bundleName, std::string& abilityName, std::string abilityId, const std::string& continuousTask, const int userId, const int eventId) { - BUNDLE_ACTIVE_LOGI("report event called123123"); - BundleActiveReportHandlerObject tmpHandlerObject; + BundleActiveReportHandlerObject tmpHandlerObject(userId, ""); tmpHandlerObject.event_.bundleName_ = bundleName; tmpHandlerObject.event_.abilityName_ = abilityName; tmpHandlerObject.event_.abilityId_ = abilityId; tmpHandlerObject.event_.eventId_ = eventId; tmpHandlerObject.event_.continuousTaskAbilityName_ = continuousTask; - tmpHandlerObject.userId_ = userId; sptr timer = MiscServices::TimeServiceClient::GetInstance(); tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs(); std::shared_ptr handlerobjToPtr = @@ -214,15 +232,7 @@ bool BundleActiveService::IsBundleIdle(const std::string& bundleName) int result = -1; OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); if (ret == ERR_OK && userId != -1) { - BUNDLE_ACTIVE_LOGI("IsBundleIdle user id is %{public}d", userId); - if (!GetBundleMgrProxy()) { - BUNDLE_ACTIVE_LOGE("Get bundle manager proxy failed!"); - return true; - } - bool bundleIsSystemApp = sptrBundleMgr_->CheckIsSystemAppByUid(callingUid); - if (bundleIsSystemApp == true) { - result = bundleActiveCore_->IsBundleIdle(bundleName, userId); - } + result = bundleActiveCore_->IsBundleIdle(bundleName, userId); } if (result == 0) { return false; @@ -321,15 +331,9 @@ std::vector BundleActiveService::QueryCurrentEvents(const int int userId = -1; OHOS::ErrCode ret = OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); if (ret == ERR_OK && userId != -1) { - BUNDLE_ACTIVE_LOGI("QueryCurrentEvents userid is %{public}d", userId); - if (!GetBundleMgrProxy()) { - BUNDLE_ACTIVE_LOGE("QueryCurrentEvents get bundle manager proxy failed!"); - return result; - } std::string bundleName = ""; sptrBundleMgr_->GetBundleNameForUid(callingUid, bundleName); - bool isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, userId); - if (!bundleName.empty() && isSystemAppAndHasPermission == true) { + if (!bundleName.empty()) { BUNDLE_ACTIVE_LOGI("QueryCurrentEvents buindle name is %{public}s", bundleName.c_str()); result = bundleActiveCore_->QueryEvents(userId, beginTime, endTime, bundleName); diff --git a/services/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp index 4175d250fc70ad5bcfd45789f20722d945253b52..4433bcc69d9d1c9875ee86288519ee5e634d265f 100644 --- a/services/common/src/bundle_active_usage_database.cpp +++ b/services/common/src/bundle_active_usage_database.cpp @@ -154,7 +154,7 @@ int32_t BundleActiveUsageDatabase::NearIndexOnOrAfterCurrentTime(int64_t current int64_t tableTime = -1; int32_t divisor = 2; while (low <= high) { - mid = (high - low) / divisor + low; + mid = (high + low) / divisor; tableTime = sortedTableArray.at(mid); if (currentTime > tableTime) { low = mid + 1; @@ -552,8 +552,11 @@ void BundleActiveUsageDatabase::PutBundleHistoryData(int userId, int64_t outRowId = BUNDLE_ACTIVE_FAIL; NativeRdb::ValuesBucket valuesBucket; vector queryCondition; + int updatedcount = 0; + int unupdatedcount = 0; for (auto iter = userHistory->begin(); iter != userHistory->end(); iter++) { - if (iter->second == nullptr) { + if (iter->second == nullptr || !iter->second->isChanged_) { + unupdatedcount++; continue; } queryCondition.push_back(to_string(userId)); @@ -576,7 +579,11 @@ void BundleActiveUsageDatabase::PutBundleHistoryData(int userId, } valuesBucket.Clear(); queryCondition.clear(); + iter->second->isChanged_ = false; + updatedcount++; } + BUNDLE_ACTIVE_LOGI("PutBundleHistoryData, update %{public}d bundles, keep %{public}d bundles group", + updatedcount, unupdatedcount); } shared_ptr>> BundleActiveUsageDatabase::GetBundleHistoryData( @@ -685,13 +692,12 @@ void BundleActiveUsageDatabase::FlushPackageInfo(unsigned int databaseType, cons queryCondition.push_back(to_string(stats.userId_)); queryCondition.push_back(iter->first); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_BUNDLE_STARTED_COUNT, iter->second->bundleStartedCount_); - valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME, (iter->second->lastTimeUsed_ - stats.beginTime_)); - if (iter->second->lastContiniousTaskUsed_ == -1) { - valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME_CONTINUOUS_TASK, (iter->second->lastContiniousTaskUsed_)); - } else { - valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME_CONTINUOUS_TASK, (iter->second->lastContiniousTaskUsed_ - - stats.beginTime_)); - } + int64_t lastTimeUsedAdjusted = iter->second->lastTimeUsed_ == -1 ? + iter->second->lastTimeUsed_ : iter->second->lastTimeUsed_ - stats.beginTime_; + valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME, lastTimeUsedAdjusted); + int64_t lastContinuousTaskUsedAdjusted = iter->second->lastContiniousTaskUsed_ == -1 ? + iter->second->lastContiniousTaskUsed_ : iter->second->lastContiniousTaskUsed_ - stats.beginTime_; + valuesBucket.PutLong(BUNDLE_ACTIVE_DB_LAST_TIME_CONTINUOUS_TASK, lastContinuousTaskUsedAdjusted); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_TOTAL_TIME, iter->second->totalInFrontTime_); valuesBucket.PutLong(BUNDLE_ACTIVE_DB_TOTAL_TIME_CONTINUOUS_TASK, iter->second->totalContiniousTaskUsedTime_); rdbStore->Update(changeRow, tableName, valuesBucket, "userId = ? and bundleName = ?", queryCondition); @@ -746,13 +752,11 @@ shared_ptr BundleActiveUsageDatabase::GetCurrentUsageDa bundleActiveResult->GetString(BUNDLE_NAME_COLUMN_INDEX, usageStats->bundleName_); bundleActiveResult->GetInt(BUNDLE_STARTED_COUNT_COLUMN_INDEX, usageStats->bundleStartedCount_); bundleActiveResult->GetLong(LAST_TIME_COLUMN_INDEX, relativeLastTimeUsed); - usageStats->lastTimeUsed_ = relativeLastTimeUsed + currentPackageTime; + usageStats->lastTimeUsed_ = relativeLastTimeUsed == -1 ? -1 : + relativeLastTimeUsed + currentPackageTime; bundleActiveResult->GetLong(LAST_TIME_CONTINUOUS_TASK_COLUMN_INDEX, relativeLastTimeFrontServiceUsed); - if (relativeLastTimeFrontServiceUsed == -1) { - usageStats->lastContiniousTaskUsed_ = -1; - } else { - usageStats->lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + currentPackageTime; - } + usageStats->lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed == -1 ? -1 : + relativeLastTimeFrontServiceUsed + currentPackageTime; bundleActiveResult->GetLong(TOTAL_TIME_COLUMN_INDEX, usageStats->totalInFrontTime_); bundleActiveResult->GetLong(TOTAL_TIME_CONTINUOUS_TASK_COLUMN_INDEX, usageStats->totalContiniousTaskUsedTime_); bundleStats.insert(pair>(usageStats->bundleName_, @@ -888,6 +892,7 @@ int32_t BundleActiveUsageDatabase::GetOptimalIntervalType(int64_t beginTime, int } } } + BUNDLE_ACTIVE_LOGI("optimalIntervalType is %{public}d", optimalIntervalType); return optimalIntervalType; } @@ -1082,13 +1087,11 @@ vector BundleActiveUsageDatabase::QueryDatabaseUsageSt bundleActiveResult->GetInt(BUNDLE_STARTED_COUNT_COLUMN_INDEX, usageStats.bundleStartedCount_); bundleActiveResult->GetLong(LAST_TIME_COLUMN_INDEX, usageStats.lastTimeUsed_); bundleActiveResult->GetLong(LAST_TIME_COLUMN_INDEX, relativeLastTimeUsed); - usageStats.lastTimeUsed_ = relativeLastTimeUsed + packageTableTime; + usageStats.lastTimeUsed_ = relativeLastTimeUsed == -1 ? -1 : + relativeLastTimeUsed + packageTableTime; bundleActiveResult->GetLong(LAST_TIME_CONTINUOUS_TASK_COLUMN_INDEX, relativeLastTimeFrontServiceUsed); - if (relativeLastTimeFrontServiceUsed == -1) { - usageStats.lastContiniousTaskUsed_ = -1; - } else { - usageStats.lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed + packageTableTime; - } + usageStats.lastContiniousTaskUsed_ = relativeLastTimeFrontServiceUsed == -1 ? -1 : + relativeLastTimeFrontServiceUsed + packageTableTime; bundleActiveResult->GetLong(TOTAL_TIME_COLUMN_INDEX, usageStats.totalInFrontTime_); bundleActiveResult->GetLong(TOTAL_TIME_CONTINUOUS_TASK_COLUMN_INDEX, usageStats.totalContiniousTaskUsedTime_); diff --git a/services/packagegroup/include/bundle_active_group_common.h b/services/packagegroup/include/bundle_active_group_common.h index d3fdef4bd2c1294f99c2c08d19bf01d02dd56e9e..4d8fe0ba0f16393f3c7836638621ee567715bc46 100644 --- a/services/packagegroup/include/bundle_active_group_common.h +++ b/services/packagegroup/include/bundle_active_group_common.h @@ -59,6 +59,7 @@ const uint32_t GROUP_EVENT_REASON_BACKGROUND = 0x0005; const uint32_t GROUP_EVENT_REASON_ALIVE_TIMEOUT = 0x0006; const uint32_t GROUP_EVENT_REASON_LONG_TIME_TASK_STARTTED = 0x0007; const uint32_t GROUP_EVENT_REASON_CALCULATED_RESTORED = 0x0008; +const uint32_t GROUP_EVENT_REASON_ALIVE_NOT_TIMEOUT = 0x0009; } } } diff --git a/services/packagegroup/include/bundle_active_group_controller.h b/services/packagegroup/include/bundle_active_group_controller.h index 1de660fc0c4a8a0f29a6fd540407a3ec577e894a..90c03cb291af3d569251447c90284deb2c9e986f 100644 --- a/services/packagegroup/include/bundle_active_group_controller.h +++ b/services/packagegroup/include/bundle_active_group_controller.h @@ -83,7 +83,8 @@ public: bool IsScreenOn(); int IsBundleIdle(const std::string& bundleName, const int userId); int QueryPackageGroup(const int userId, const std::string& bundleName); - void ShutDown(const int64_t bootBasedTimeStamp); + void ShutDown(const int64_t bootBasedTimeStamp, const int userId); + void OnUserSwitched(const int userId); private: std::mutex mutex_; @@ -93,7 +94,7 @@ private: int64_t timeoutForDirectlyUse_ = debug_ ? THREE_MINUTE : ONE_HOUR; int64_t timeoutForNotifySeen_ = debug_ ? ONE_MINUTE : TWELVE_HOUR; int64_t timeoutForSystemInteraction_ = debug_ ? ONE_MINUTE : TEN_MINUTE; - int64_t timeoutCalculated_; + int64_t timeoutCalculated_ = 0; sptr sptrBundleMgr_; bool calculationTimeOut(const std::shared_ptr& oneBundleHistory, const int64_t bootBasedTimeStamp); diff --git a/services/packagegroup/include/bundle_active_package_history.h b/services/packagegroup/include/bundle_active_package_history.h index ff25c7ab9e91bb052944f4f20fb0952802229060..bfced5544d64252cdde0e666702413a16f2f3ad4 100644 --- a/services/packagegroup/include/bundle_active_package_history.h +++ b/services/packagegroup/include/bundle_active_package_history.h @@ -30,6 +30,7 @@ public: uint32_t reasonInGroup_; int64_t bundleAliveTimeoutTimeStamp_; int64_t bundleDailyTimeoutTimeStamp_; + bool isChanged_; BundleActivePackageHistory(); ~BundleActivePackageHistory() {}; }; diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index f89d4bf08a94e3bfd1a4e55ec13d40f18c4b9515..97b32975d019f353732c15f573b9b6a7e261d0d5 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -45,6 +45,18 @@ void BundleActiveGroupController::OnUserRemoved(const int userId) { std::lock_guard lock(mutex_); bundleUserHistory_->userHistory_.erase(userId); + if (!activeGroupHandler_.expired()) { + activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE); + } +} + +void BundleActiveGroupController::OnUserSwitched(const int userId) +{ + std::lock_guard lock(mutex_); + if (!activeGroupHandler_.expired()) { + activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE); + } + PeriodCheckBundleState(userId); } void BundleActiveGroupController::OnScreenChanged(const bool& isScreenOn, const int64_t bootFromTimeStamp) @@ -209,7 +221,7 @@ void BundleActiveGroupController::ReportEvent(const BundleActiveEvent& event, co return; } int64_t timeUntilNextCheck; - int eventReason = EventToGroupReason(eventId); + uint32_t eventReason = EventToGroupReason(eventId); switch (eventId) { case BundleActiveEvent::NOTIFICATION_SEEN: bundleUserHistory_->ReportUsage(bundleUsageHistory, event.bundleName_, ACTIVE_GROUP_DAILY, @@ -265,17 +277,22 @@ void BundleActiveGroupController::CheckAndUpdateGroup(const std::string& bundleN groupReason = GROUP_CONTROL_REASON_TIMEOUT; } int64_t bootBasedTimeStampAdjusted = bundleUserHistory_->GetBootBasedTimeStamp(bootBasedTimeStamp); + bool notTimeout = false; if (newGroup >= ACTIVE_GROUP_ALIVE && oneBundleHistory->bundleAliveTimeoutTimeStamp_ > bootBasedTimeStampAdjusted) { newGroup = ACTIVE_GROUP_ALIVE; groupReason = oneBundleHistory->reasonInGroup_; + groupReason = (newGroup == oldGroup) ? oneBundleHistory->reasonInGroup_ : GROUP_CONTROL_REASON_USAGE | + GROUP_EVENT_REASON_ALIVE_NOT_TIMEOUT; + notTimeout = true; } else if (newGroup >= ACTIVE_GROUP_DAILY && oneBundleHistory->bundleDailyTimeoutTimeStamp_ > bootBasedTimeStampAdjusted) { newGroup = ACTIVE_GROUP_DAILY; groupReason = (newGroup == oldGroup) ? oneBundleHistory->reasonInGroup_ : GROUP_CONTROL_REASON_USAGE | GROUP_EVENT_REASON_ALIVE_TIMEOUT; + notTimeout = true; } - if (oldGroup < newGroup) { + if (oldGroup < newGroup || notTimeout) { BUNDLE_ACTIVE_LOGI("CheckAndUpdateGroup called SetBundleGroup"); bundleUserHistory_->SetBundleGroup(bundleName, userId, bootBasedTimeStamp, newGroup, groupReason, false); } @@ -362,9 +379,10 @@ bool BundleActiveGroupController::IsBundleInstalled(const std::string& bundleNam return true; } -void BundleActiveGroupController::ShutDown(const int64_t bootBasedTimeStamp) +void BundleActiveGroupController::ShutDown(const int64_t bootBasedTimeStamp, const int userId) { BUNDLE_ACTIVE_LOGI("ShutDown called"); + CheckEachBundleState(userId); bundleUserHistory_->UpdateBootBasedAndScreenTime(false, bootBasedTimeStamp, true); } diff --git a/services/packagegroup/src/bundle_active_user_history.cpp b/services/packagegroup/src/bundle_active_user_history.cpp index 5179f8fec2590dc021ce82c4e28b6f5572643ddf..e1d59b5179dc0cb95a23200d4b7d94fe5e27b6b4 100644 --- a/services/packagegroup/src/bundle_active_user_history.cpp +++ b/services/packagegroup/src/bundle_active_user_history.cpp @@ -31,6 +31,8 @@ BundleActivePackageHistory::BundleActivePackageHistory() reasonInGroup_ = DeviceUsageStatsGroupConst::GROUP_CONTROL_REASON_DEFAULT; bundleAliveTimeoutTimeStamp_ = 0; bundleDailyTimeoutTimeStamp_ = 0; + lastCalculatedGroup_ = ACTIVE_GROUP_NEVER; + isChanged_ = false; }; void BundleActiveUserHistory::WriteDeviceDuration() @@ -177,6 +179,7 @@ void BundleActiveUserHistory::ReportUsage(shared_ptr oneBundleUsageHistory->currentGroup_ = newGroup; } oneBundleUsageHistory->reasonInGroup_ = GROUP_CONTROL_REASON_USAGE | groupReason; + oneBundleUsageHistory->isChanged_ = true; } void BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int userId, @@ -201,6 +204,7 @@ void BundleActiveUserHistory::SetBundleGroup(const string& bundleName, const int oneBundleHistory->bundleAliveTimeoutTimeStamp_ = setTimeStamp; oneBundleHistory->bundleDailyTimeoutTimeStamp_ = setTimeStamp; } + oneBundleHistory->isChanged_ = true; } void BundleActiveUserHistory::UpdateBootBasedAndScreenTime(const bool& isScreenOn, const int64_t bootBasedTimeStamp, diff --git a/services/packageusage/include/bundle_active_report_handler.h b/services/packageusage/include/bundle_active_report_handler.h index bc9ea44107018c56147b28fc1a0706073fd5393a..ad2714dedaff5416d998b5e04be44b9c2cb3d975 100644 --- a/services/packageusage/include/bundle_active_report_handler.h +++ b/services/packageusage/include/bundle_active_report_handler.h @@ -39,8 +39,8 @@ public: static const int MSG_REPORT_EVENT_TO_ALL_USER = 1; static const int MSG_FLUSH_TO_DISK = 2; static const int MSG_REMOVE_USER = 3; - static const int MSG_DEVICE_SHUTDOWN = 4; - static const int MSG_BUNDLE_UNINSTALLED = 5; + static const int MSG_BUNDLE_UNINSTALLED = 4; + static const int MSG_SWITCH_USER = 5; private: std::shared_ptr bundleActiveCore_; diff --git a/services/packageusage/include/bundle_active_user_service.h b/services/packageusage/include/bundle_active_user_service.h index 6aa13e79464ec01e237502bc8d9580eb69d15800..2bce5f34f9952224ef37e5c54a53702fbecffbe9 100644 --- a/services/packageusage/include/bundle_active_user_service.h +++ b/services/packageusage/include/bundle_active_user_service.h @@ -71,7 +71,8 @@ private: BundleActiveCalendar::YEAR_MILLISECONDS}; void NotifyStatsChanged(); void NotifyNewUpdate(); - void printstat(); + void PrintInMemPackageStats(const int idx); + void PrintInMemEventStats(); }; } } diff --git a/services/packageusage/src/bundle_active_event_stats.cpp b/services/packageusage/src/bundle_active_event_stats.cpp index 4dfa187ada9a155923a4604cf46893cf64c21095..3bb55e0e93c99d38715f263ca575abdf1d4f79db 100644 --- a/services/packageusage/src/bundle_active_event_stats.cpp +++ b/services/packageusage/src/bundle_active_event_stats.cpp @@ -19,6 +19,7 @@ namespace OHOS { namespace DeviceUsageStats { BundleActiveEventStats::BundleActiveEventStats() { + eventId_ = 0; beginTimeStamp_ = 0; endTimeStamp_ = 0; lastEventTime_ = 0; diff --git a/services/packageusage/src/bundle_active_package_stats.cpp b/services/packageusage/src/bundle_active_package_stats.cpp index 95205f0dee2e2571c838a55899b65fb42557e952..022bfc4e31f71123fb5c68cca9e231e207b0c7d3 100644 --- a/services/packageusage/src/bundle_active_package_stats.cpp +++ b/services/packageusage/src/bundle_active_package_stats.cpp @@ -22,7 +22,7 @@ BundleActivePackageStats::BundleActivePackageStats() bundleName_.clear(); beginTimeStamp_ = 0; // start time of counting endTimeStamp_ = 0; // stop time of counting - lastTimeUsed_ = 0; // the timestamp of last launch + lastTimeUsed_ = -1; // the timestamp of last launch totalInFrontTime_ = 0; // the total time of bundle in front. lastContiniousTaskUsed_ = -1; // the timestamp of bundle calling a continuous task. totalContiniousTaskUsedTime_ = 0; // the total time of bundle use continuous tasks. diff --git a/services/packageusage/src/bundle_active_report_handler.cpp b/services/packageusage/src/bundle_active_report_handler.cpp index d02a40d18cdee7cbb6443cd1c4810529c6789aa5..3fc4a797a813b1bd92f892c6656dd1769b14b6e3 100644 --- a/services/packageusage/src/bundle_active_report_handler.cpp +++ b/services/packageusage/src/bundle_active_report_handler.cpp @@ -61,10 +61,6 @@ void BundleActiveReportHandler::ProcessEvent(const AppExecFwk::InnerEvent::Point bundleActiveCore_->OnUserRemoved(tmpHandlerobj.userId_); break; } - case MSG_DEVICE_SHUTDOWN: { - bundleActiveCore_->ShutDown(); - break; - } case MSG_BUNDLE_UNINSTALLED: { BUNDLE_ACTIVE_LOGI("MSG_BUNDLE_UNINSTALLED CALLED"); auto ptrToHandlerobj = event->GetSharedObject(); @@ -72,6 +68,12 @@ void BundleActiveReportHandler::ProcessEvent(const AppExecFwk::InnerEvent::Point bundleActiveCore_->OnBundleUninstalled(tmpHandlerobj.userId_, tmpHandlerobj.bundleName_); break; } + case MSG_SWITCH_USER: { + BUNDLE_ACTIVE_LOGI("MSG_SWITCH_USER CALLED"); + auto ptrToHandlerobj = event->GetSharedObject(); + BundleActiveReportHandlerObject tmpHandlerobj = *ptrToHandlerobj; + bundleActiveCore_->OnUserSwitched(tmpHandlerobj.userId_); + } default: { break; } diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index 4686d761c353be675076c5f65eec21066476da10..9682bbc69ee390a4378825e5fddc1a7680ff7cb6 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -161,13 +161,12 @@ void BundleActiveUserService::RestoreStats(bool forced) if (statsChanged_ || forced) { BUNDLE_ACTIVE_LOGI("RestoreStats() stat changed is true"); for (uint32_t i = 0; i < currentStats_.size(); i++) { - if (currentStats_[i] != nullptr) { + if (currentStats_[i]) { + if (currentStats_[i]->bundleStats_.empty() && currentStats_[i]->events_.events_.empty()) { + continue; + } database_.UpdateUsageData(i, *(currentStats_[i])); } - if (i == 0) { - BUNDLE_ACTIVE_LOGI("RESOTRE EVENT SIZE IS %{public}d, USER ID IS %{public}d", - currentStats_[i]->events_.Size(), userId_); - } } currentStats_[BundleActivePeriodStats::PERIOD_DAILY]->events_.Clear(); statsChanged_ = false; @@ -304,7 +303,12 @@ std::vector BundleActiveUserService::QueryPackageStats return result; } int64_t truncatedEndTime = std::min(currentStats->beginTime_, endTime); + BUNDLE_ACTIVE_LOGI("Query package data in db from %{public}lld to %{public}lld, current begin %{public}lld", + beginTime, truncatedEndTime, currentStats->beginTime_); result = database_.QueryDatabaseUsageStats(intervalType, beginTime, truncatedEndTime, userId); + BUNDLE_ACTIVE_LOGI("Query package data in db result size is %{public}d", + static_cast(result.size())); + PrintInMemPackageStats(intervalType); // if we need a in-memory stats, combine current stats with result from database. if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { BUNDLE_ACTIVE_LOGI("QueryPackageStats need in memory stats"); @@ -339,9 +343,10 @@ std::vector BundleActiveUserService::QueryEvents(const int64_ if (beginTime >= currentStats->endTime_) { return result; } - BUNDLE_ACTIVE_LOGI("QueryEvents bundle name is %{public}s", bundleName.c_str()); + BUNDLE_ACTIVE_LOGI("Query event bundle name is %{public}s", bundleName.c_str()); result = database_.QueryDatabaseEvents(beginTime, endTime, userId, bundleName); - BUNDLE_ACTIVE_LOGI("event database query size is %{public}d", result.size()); + BUNDLE_ACTIVE_LOGI("Query event data in db result size is %{public}d", result.size()); + PrintInMemEventStats(); // if we need a in-memory stats, combine current stats with result from database. if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { BUNDLE_ACTIVE_LOGI("QueryEvents need in memory stats"); @@ -358,17 +363,25 @@ std::vector BundleActiveUserService::QueryEvents(const int64_ return result; } -void BundleActiveUserService::printstat() +void BundleActiveUserService::PrintInMemPackageStats(const int idx) { - BUNDLE_ACTIVE_LOGI("printstat called"); - int idx = 0; + BUNDLE_ACTIVE_LOGI("PrintInMemPackageStats called"); for (auto it : currentStats_[idx]->bundleStats_) { - BUNDLE_ACTIVE_LOGI("bundle name is %{public}s", it.first.c_str()); - int64_t lasttimeused = it.second->lastTimeUsed_; - int64_t totalusedtime = it.second->totalInFrontTime_; - BUNDLE_ACTIVE_LOGI("event stat is, totaltime is %{public}lld, lasttimeused is %{public}lld", - totalusedtime, lasttimeused); + BUNDLE_ACTIVE_LOGI("In mem, bundle name is %{public}s", it.first.c_str()); + int64_t lastTimeUsed = it.second->lastTimeUsed_; + int64_t totalUsedTime = it.second->totalInFrontTime_; + int64_t lastTimeContinuousTaskUsed = it.second->lastContiniousTaskUsed_; + int64_t totalTimeContinuousTaskUsed = it.second->totalContiniousTaskUsedTime_; + BUNDLE_ACTIVE_LOGI("bundle stat is, totaltime is %{public}lld, lastTimeUsed is %{public}lld" + "total continuous task is %{public}lld, lastTimeContinuousTaskUsed is %{public}lld", + totalUsedTime, lastTimeUsed, totalTimeContinuousTaskUsed, lastTimeContinuousTaskUsed); } +} + +void BundleActiveUserService::PrintInMemEventStats() +{ + BUNDLE_ACTIVE_LOGI("PrintInMemEventStats called"); + int idx = 0; int size = static_cast(currentStats_[idx]->events_.events_.size()); for (int i = 0; i < size; i++) { std::string abilityId = currentStats_[idx]->events_.events_[i].abilityId_; @@ -376,7 +389,7 @@ void BundleActiveUserService::printstat() std::string bundlename = currentStats_[idx]->events_.events_[i].bundleName_; int eventid = currentStats_[idx]->events_.events_[i].eventId_; int64_t timestamp = currentStats_[idx]->events_.events_[i].timeStamp_; - BUNDLE_ACTIVE_LOGI("event stat is, abilityid is %{public}s, abilityname is %{public}s, " + BUNDLE_ACTIVE_LOGI("In mem, event stat is, abilityid is %{public}s, abilityname is %{public}s, " "bundlename is %{public}s, eventid is %{public}d, timestamp is %{public}lld", abilityId.c_str(), abilityname.c_str(), bundlename.c_str(), eventid, timestamp); }