diff --git a/BUILD.gn b/BUILD.gn
index 4eea17eb3e3502218d0a179a03fa6996ede6d872..2c759b844c5304ac0d9c7645f320f664354a8504 100644
--- a/BUILD.gn
+++ b/BUILD.gn
@@ -31,6 +31,9 @@ config("usagestatsinner_public_config") {
ohos_shared_library("usagestatsinner") {
sources = [
"interfaces/innerkits/src/bundle_active_client.cpp",
+ "interfaces/innerkits/src/bundle_active_group_callback_info.cpp",
+ "interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp",
+ "interfaces/innerkits/src/bundle_active_group_callback_stub.cpp",
"interfaces/innerkits/src/bundle_active_proxy.cpp",
"services/packageusage/src/bundle_active_event.cpp",
"services/packageusage/src/bundle_active_package_stats.cpp",
@@ -38,6 +41,7 @@ ohos_shared_library("usagestatsinner") {
public_configs = [ ":usagestatsinner_public_config" ]
public_deps = [ ":usagestatservice" ]
external_deps = [
+ "eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
@@ -58,6 +62,7 @@ ohos_prebuilt_etc("device_usage_statistics_service_init") {
ohos_shared_library("bundlestate") {
sources = [
+ "frameworks/src/bundle_active_group_observer.cpp",
"frameworks/src/bundle_state_common.cpp",
"frameworks/src/bundle_state_init.cpp",
"frameworks/src/bundle_state_query.cpp",
@@ -67,6 +72,7 @@ ohos_shared_library("bundlestate") {
"services/common/include",
"interfaces/innerkits/include",
"services/packageusage/include",
+ "services/packagegroup/include",
]
deps = [
@@ -75,6 +81,7 @@ ohos_shared_library("bundlestate") {
]
external_deps = [
+ "eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"napi:ace_napi",
@@ -90,6 +97,8 @@ ohos_shared_library("bundlestate") {
ohos_shared_library("usagestatservice") {
cflags_cc = []
sources = [
+ "interfaces/innerkits/src/bundle_active_group_callback_info.cpp",
+ "interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp",
"services/common/src/bundle_active_account_helper.cpp",
"services/common/src/bundle_active_app_state_obsever.cpp",
"services/common/src/bundle_active_binary_search.cpp",
@@ -98,6 +107,9 @@ ohos_shared_library("usagestatservice") {
"services/common/src/bundle_active_debug_mode.cpp",
"services/common/src/bundle_active_log.cpp",
"services/common/src/bundle_active_open_callback.cpp",
+ "services/common/src/bundle_active_power_state_callback_proxy.cpp",
+ "services/common/src/bundle_active_power_state_callback_service.cpp",
+ "services/common/src/bundle_active_power_state_callback_stub.cpp",
"services/common/src/bundle_active_service.cpp",
"services/common/src/bundle_active_shutdown_callback_proxy.cpp",
"services/common/src/bundle_active_shutdown_callback_service.cpp",
@@ -125,9 +137,12 @@ ohos_shared_library("usagestatservice") {
"services/common/include",
"services/packageusage/include",
"services/packagegroup/include",
+ "interfaces/innerkits/include",
+ "interfaces/kits/bundlestats/napi/include",
]
external_deps = [
+ "ability_base:configuration",
"ability_base:want",
"ability_runtime:app_manager",
"ability_runtime:wantagent_innerkits",
@@ -138,13 +153,12 @@ ohos_shared_library("usagestatservice") {
"common_event_service:cesfwk_innerkits",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
+ "init:libbegetutil",
"ipc:ipc_core",
- "native_appdatamgr:native_rdb",
- "permission_standard:libpermissionsdk_standard",
"power_manager_native:powermgr_client",
+ "relational_store:native_rdb",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy",
- "startup_l2:syspara",
"time_native:time_service",
"utils_base:utils",
]
@@ -157,36 +171,3 @@ ohos_shared_library("usagestatservice") {
part_name = "${device_usage_statistics_part_name}"
subsystem_name = "resourceschedule"
}
-
-ohos_executable("deviceusagestats") {
- include_dirs = [
- "services/common/include",
- "services/packageusage/include",
- "services/packagegroup/include",
- "interfaces/innerkits/include",
- "utils/dump/include",
- ]
-
- sources = [
- "utils/dump/src/bundle_active_shell_command.cpp",
- "utils/dump/src/main.cpp",
- "utils/dump/src/shell_command.cpp",
- ]
-
- deps = [ ":usagestatsinner" ]
-
- configs = []
-
- external_deps = [
- "ability_base:want",
- "ability_runtime:wantagent_innerkits",
- "hiviewdfx_hilog_native:libhilog",
- "ipc:ipc_core",
- "safwk:system_ability_fwk",
- "samgr_standard:samgr_proxy",
- "utils_base:utils",
- ]
-
- install_enable = true
- part_name = "${device_usage_statistics_part_name}"
-}
diff --git a/README.md b/README.md
index f28be986a2664edae4fb546d7b98beeabcd843b9..27262a6a75137c83aa85ca14dd89395460db56c6 100644
--- a/README.md
+++ b/README.md
@@ -40,37 +40,69 @@ Taking app usage interface as an example, the main exposed interfaces are as fol
API name
|
-API description
+ | API description
|
-queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void
- |
-Queries the event collection of all applications through time interval.
- |
-
-queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback<BundleActiveInfoResponse>): void
- |
-Uses the start and end time to query the application usage time statistics.
- |
-
-queryCurrentBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void
- |
-Queries the event collection of the current application through the time interval.
- |
queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback<Array<BundleStateInfo>>): void
- |
-Queries application usage duration statistics by time interval.
- |
queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void
- |
-Queries (returns) the priority group used by the current caller application.
- |
isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void
- |
-Judges whether the application of the specified bundle name is currently idle.
+ |
queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void
+ | Queries the event collection of all applications through time interval(callback).
+ |
queryBundleActiveStates(begin: number, end: number): Promise<Array<BundleActiveState>>
+ | Queries the event collection of all applications through time interval(Promise).
+ |
queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback<BundleActiveInfoResponse>): void
+ | Uses the start and end time to query the application usage time statistics(callback).
+ |
queryBundleStateInfos(begin: number, end: number): Promise<BundleActiveInfoResponse>
+ | Uses the start and end time to query the application usage time statistics(Promise).
+ |
queryCurrentBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void
+ | Queries the event collection of the current application through the time interval(callback).
+ |
queryCurrentBundleActiveStates(begin: number, end: number): Promise<Array<BundleActiveState>>
+ | Queries the event collection of the current application through the time interval(Promise).
+ |
queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback<Array<BundleStateInfo>>): void
+ | Queries application usage duration statistics by time interval(callback).
+ |
queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number): Promise<Array<BundleStateInfo>>
+ | Queries application usage duration statistics by time interval(Promise).
+ |
queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void
+ | Query the priority group of the application.
+ |
queryAppUsagePriorityGroup(): Promise<number>
+ | Query the priority group of the application.
+ |
isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void
+ | Judges whether the application of the specified bundle name is currently idle(callback).
+ |
isIdleState(bundleName: string): Promise<boolean>
+ | Judges whether the application of the specified bundle name is currently idle(Promise).
+ |
queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void
+ | Query the statistical information of system events (sleep, wake-up, unlock and screen lock) according to the start and end time(callback).
+ |
queryBundleActiveEventStates(begin: number, end: number): Promise<Array<BundleActiveEventState>>
+ | Query the statistical information of system events (sleep, wake-up, unlock and screen lock) according to the start and end time(Promise).
+ |
queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void
+ | Query the application notification times according to the start and end time(callback).
+ |
queryAppNotificationNumber(begin: number, end: number): Promise<Array<BundleActiveEventState>>
+ | Query the application notification times according to the start and end time(Promise).
+ |
getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback<Array<BundleActiveModuleInfo>>): void
+ | Query FA usage records. The maximum returned quantity does not exceed the value set by maxnum. FA usage records are sorted from near to far. The maximum maxnum is 1000. If the maxnum parameter is not filled in, the default maxnum is 1000(callback).
+ |
getRecentlyUsedModules(maxNum?: number): Promise<Array<BundleActiveModuleInfo>>
+ | Query FA usage records. The maximum returned quantity does not exceed the value set by maxnum. FA usage records are sorted from near to far. The maximum maxnum is 1000. If the maxnum parameter is not filled in, the default maxnum is 1000(Promise).
+ |
queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback<number>): void
+ | Query the group of the current application or the application of specified bundlename.
+ |
queryAppUsagePriorityGroup(bundleName? : string): Promise<number>
+ | Query the group of the current application or the application of specified bundlename.
+ |
setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback<void>): void
+ | Set the group of the specified application as the group provided by the parameter(callback).
+ |
setBundleGroup(bundleName: string, newGroup: GroupType): Promise<void>
+ | Set the group of the specified application as the group provided by the parameter(Promise).
+ |
registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>, callback: AsyncCallback<void>): void
+ | Register callback for application group change(callback).
+ |
registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>): Promise<void>
+ | Register callback for application group change(Promise).
+ |
unRegisterGroupCallBack(callback: AsyncCallback<void>): void
+ | Unregister the registered application group callback(callback).
+ |
unRegisterGroupCallBack(): Promise<void>
+ | Unregister the registered application group callback(Promise).
|
+
+
### Usage Guidelines
There are many interfaces for device usage statistics. Take app usage interface as an example to introduce the interface logic.
@@ -84,8 +116,15 @@ There are many interfaces for device usage statistics. Take app usage interface
>2. Query the usage duration of the application according to the start and end time;
>3. Query the event collection of the current application according to the start and end time;
>4. Query the usage duration of the application according to the type of interval (day, week, month, year) and the start and end time;
->5. Query the priority group of the caller application;
+>5. Query the priority group of the application;
>6. Judge whether the specified application is currently idle;
+>7. Query the statistical information of system events (sleep, wake-up, unlock and screen lock) according to the start and end time;
+>8. Query the application notification times according to the start and end time;
+>9. Query FA usage records. The maximum returned quantity does not exceed the value set by maxnum. FA usage records are sorted from near to far. The maximum maxnum is 1000. If the maxnum parameter is not filled in, the default maxnum is 1000;
+>10. Query the group of the current application or the application of specified bundlename;
+>11. Set the group of the specified application as the group provided by the parameter;
+>12. Register callback for application group change;
+>13. Unregister the registered application group callback;
## Repositories Involved
@@ -97,4 +136,4 @@ resource_schedule_service
appexecfwk_standard
-native_appdatamgr
\ No newline at end of file
+relational_store
\ No newline at end of file
diff --git a/README_zh.md b/README_zh.md
index 4910fdf7a7e31e268df1b286d53afcb7863d70e8..9fabc001ff5343b00ce71ff5b4a494c671daf42f 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -37,37 +37,70 @@
接口名
|
-接口描述
+ | 接口描述
|
-queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void
+ |
+queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void
+ | 通过指定起始和结束时间查询所有应用的事件集合(callback形式)。
+ |
queryBundleActiveStates(begin: number, end: number): Promise<Array<BundleActiveState>>
+ | 通过指定起始和结束时间查询所有应用的事件集合(Promise形式)。
+ |
queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback<BundleActiveInfoResponse>): void
+ | 通过指定起始和结束时间查询应用使用时长统计信息(callback形式)。
+ |
queryBundleStateInfos(begin: number, end: number): Promise<BundleActiveInfoResponse>
+ | 通过指定起始和结束时间查询应用使用时长统计信息(Promise形式)。
+ |
queryCurrentBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void
+ | 通过指定起始和结束时间查询当前应用的事件集合(callback形式)。
+ |
queryCurrentBundleActiveStates(begin: number, end: number): Promise<Array<BundleActiveState>>
+ | 通过指定起始和结束时间查询当前应用的事件集合(Promise形式)。
+ |
queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback<Array<BundleStateInfo>>): void
+ | 通过指定时间段间隔(天、周、月、年)查询应用使用时长统计信息(callback形式)。
+ |
queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number): Promise<Array<BundleStateInfo>>
+ | 通过指定时间段间隔(天、周、月、年)查询应用使用时长统计信息(Promise形式)。
+ |
queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void
+ | 查询当前应用的优先级分组(callback形式)。
+ |
queryAppUsagePriorityGroup(): Promise<number>
+ | 查询当前应用的优先级分组(Promise形式)。
+ |
isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void
+ | 判断指定Bundle Name的应用当前是否是空闲状态(callback形式)。
+ |
isIdleState(bundleName: string): Promise<boolean>
+ | 判断指定Bundle Name的应用当前是否是空闲状态(Promise形式)。
+ |
queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void
+ | 根据起止时间查询系统事件(休眠、唤醒、解锁、锁屏)统计信息(callback形式)。
+ |
queryBundleActiveEventStates(begin: number, end: number): Promise<Array<BundleActiveEventState>>
+ | 根据起止时间查询系统事件(休眠、唤醒、解锁、锁屏)统计信息(Promise形式)。
+ |
queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void
+ | 根据起止时间查询应用通知次数(callback形式)。
+ |
queryAppNotificationNumber(begin: number, end: number): Promise<Array<BundleActiveEventState>>
+ | 根据起止时间查询应用通知次数(Promise形式)。
+ |
getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback<Array<BundleActiveModuleInfo>>): void
+ | 查询FA使用记录。返回数量最大不超过maxNum设置的值,FA使用记录由近及远排序,maxNum最大为1000,若不填写maxNum参数,则maxNum默认为1000(callback形式)。
+ |
getRecentlyUsedModules(maxNum?: number): Promise<Array<BundleActiveModuleInfo>>
+ | 查询FA使用记录。返回数量最大不超过maxNum设置的值,FA使用记录由近及远排序,maxNum最大为1000,若不填写maxNum参数,则maxNum默认为1000(Promise形式)。
+ |
queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback<number>): void
+ | 使用可选参数查询当前调用者应用的使用优先级群组(callback形式)。
+ |
queryAppUsagePriorityGroup(bundleName? : string): Promise<number>
+ | 使用可选参数查询当前调用者应用的使用优先级群组(Promise形式)。
+ |
setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback<void>): void
+ | 将指定应用的分组设置为参数提供的分组(callback形式)。
+ |
setBundleGroup(bundleName: string, newGroup: GroupType): Promise<void>
+ | 将指定应用的分组设置为参数提供的分组(Promise形式)。
+ |
registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>, callback: AsyncCallback<void>): void
+ | 给应用分组变化注册回调(callback形式)。
+ |
registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>): Promise<void>
+ | 给应用分组变化注册回调(Promise形式)。
+ |
unRegisterGroupCallBack(callback: AsyncCallback<void>): void
+ | 将已注册过的应用分组回调解除注册(callback形式)。
+ |
unRegisterGroupCallBack(): Promise<void>
+ | 将已注册过的应用分组回调解除注册(Promise形式)。
|
-通过指定起始和结束时间查询所有应用的事件集合。
- |
-
-queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback<BundleActiveInfoResponse>): void
- |
-通过指定起始和结束时间查询应用使用时长统计信息。
- |
-
-queryCurrentBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void
- |
-通过指定起始和结束时间查询当前应用的事件集合。
- |
queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback<Array<BundleStateInfo>>): void
- |
-通过指定时间段间隔(天、周、月、年)查询应用使用时长统计信息。
- |
queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void
- |
-查询(返回)当前调用者应用的使用优先级群组。
- |
isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void
- |
-判断指定Bundle Name的应用当前是否是空闲状态。
|
+
### 使用说明
设备使用信息统计接口众多,以应用使用详情(app usage)接口为例,介绍接口逻辑。
@@ -81,8 +114,15 @@
>2. 根据起止时间查询应用的使用时长;
>3. 根据起止时间查询当前应用的事件集合;
>4. 根据interval(日、周、月、年)类型和起止时间查询应用的使用时长;
->5. 查询调用者应用的优先级群组;
+>5. 查询当前应用的优先级分组;
>6. 判断指定应用当前是否是空闲状态;
+>7. 根据起止时间查询系统事件(休眠、唤醒、解锁、锁屏)统计信息;
+>8. 根据起止时间查询应用通知次数;
+>9. 查询FA使用记录。返回数量最大不超过maxNum设置的值,FA使用记录由近及远排序,maxNum最大为1000,若不填写maxNum参数,则maxNum默认为1000;
+>10. 查询当前应用或指定bundlename对应的应用的分组;
+>11. 将指定应用的分组设置为参数提供的分组;
+>12. 给应用分组变化注册回调;
+>13. 将已注册过的应用分组回调解除注册;
## 相关仓
diff --git a/bundle.json b/bundle.json
index cccf5f4b1588a4a293505b2ff6e4e874bf97284c..aca71c9c2a87a9b5f731aee77141accc43485399 100644
--- a/bundle.json
+++ b/bundle.json
@@ -23,25 +23,24 @@
"ram": "10240KB",
"deps": {
"components": [
- "libhilog",
- "libpermissionsdk_standard",
- "powermgr_client",
- "cesfwk_innerkits",
- "wantagent_innerkits",
- "want",
- "appexecfwk_base",
- "appexecfwk_core",
- "base",
- "time_service",
- "utils",
- "ipc_core",
- "system_ability_fwk",
- "samgr_proxy",
- "distributedschedsvr",
- "libeventhandler",
- "native_rdb",
- "os_account_innerkits",
- "libaccesstoken_sdk"
+ "bundle_framework",
+ "relational_store",
+ "safwk",
+ "common_event_service",
+ "os_account",
+ "ipc",
+ "access_token",
+ "ability_runtime",
+ "hiviewdfx_hilog_native",
+ "samgr_standard",
+ "utils_base",
+ "napi",
+ "startup_l2",
+ "ability_base",
+ "background_task_mgr",
+ "eventhandler",
+ "power_manager_native",
+ "time_native"
],
"third_party": [ "googletest" ]
},
@@ -51,8 +50,7 @@
"//foundation/resourceschedule/device_usage_statistics:usagestatservice",
"//foundation/resourceschedule/device_usage_statistics:device_usage_statistics_sa_profile",
"//foundation/resourceschedule/device_usage_statistics:device_usage_statistics_service_init",
- "//foundation/resourceschedule/device_usage_statistics:bundlestate",
- "//foundation/resourceschedule/device_usage_statistics:deviceusagestats"
+ "//foundation/resourceschedule/device_usage_statistics:bundlestate"
],
"inner_kits": [
{
diff --git a/frameworks/src/bundle_active_group_observer.cpp b/frameworks/src/bundle_active_group_observer.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..15aefc4b4752c71a0767459a2ee067753aff08d8
--- /dev/null
+++ b/frameworks/src/bundle_active_group_observer.cpp
@@ -0,0 +1,341 @@
+/*
+ * Copyright (c) 2022 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include
+
+#include
+#include "securec.h"
+
+#include "bundle_active_log.h"
+#include "bundle_state_common.h"
+#include "bundle_state_data.h"
+#include "bundle_state_inner_errors.h"
+#include "bundle_active_group_callback_info.h"
+
+#include "bundle_active_group_observer.h"
+
+namespace OHOS {
+namespace DeviceUsageStats {
+const uint32_t UN_REGISTER_GROUP_CALLBACK_MIN_PARAMS = 0;
+const uint32_t UN_REGISTER_GROUP_CALLBACK_PARAMS = 1;
+const uint32_t REGISTER_GROUP_CALLBACK_MIN_PARAMS = 1;
+const uint32_t REGISTER_GROUP_CALLBACK_PARAMS = 2;
+
+static sptr registerObserver = nullptr;
+
+BundleActiveGroupObserver::~BundleActiveGroupObserver()
+{
+ if (bundleGroupCallbackInfo_.ref) {
+ napi_delete_reference(bundleGroupCallbackInfo_.env, bundleGroupCallbackInfo_.ref);
+ }
+}
+
+void BundleActiveGroupObserver::SetCallbackInfo(const napi_env &env, const napi_ref &ref)
+{
+ bundleGroupCallbackInfo_.env = env;
+ bundleGroupCallbackInfo_.ref = ref;
+}
+
+napi_value SetBundleGroupChangedData(const CallbackReceiveDataWorker *commonEventDataWorkerData, napi_value &result)
+{
+ if (!commonEventDataWorkerData) {
+ BUNDLE_ACTIVE_LOGE("commonEventDataWorkerData is null");
+ return nullptr;
+ }
+ napi_value value = nullptr;
+
+ // oldGroup
+ napi_create_int32(commonEventDataWorkerData->env, commonEventDataWorkerData->oldGroup, &value);
+ napi_set_named_property(commonEventDataWorkerData->env, result, "appUsageOldGroup", value);
+
+ // newGroup
+ napi_create_int32(commonEventDataWorkerData->env, commonEventDataWorkerData->newGroup, &value);
+ napi_set_named_property(commonEventDataWorkerData->env, result, "appUsageNewGroup", value);
+
+ // userId
+ napi_create_int32(commonEventDataWorkerData->env, commonEventDataWorkerData->userId, &value);
+ napi_set_named_property(commonEventDataWorkerData->env, result, "userId", value);
+
+ // changeReason
+ napi_create_uint32(commonEventDataWorkerData->env, commonEventDataWorkerData->changeReason, &value);
+ napi_set_named_property(commonEventDataWorkerData->env, result, "changeReason", value);
+ // bundleName
+ napi_create_string_utf8(
+ commonEventDataWorkerData->env, commonEventDataWorkerData->bundleName.c_str(), NAPI_AUTO_LENGTH, &value);
+ napi_set_named_property(commonEventDataWorkerData->env, result, "bundleName", value);
+ BUNDLE_ACTIVE_LOGD(
+ "RegisterGroupCallBack appUsageOldGroup = %{public}d, appUsageNewGroup = %{public}d, userId=%{public}d, "
+ "changeReason=%{public}d, bundleName=%{public}s",
+ commonEventDataWorkerData->oldGroup, commonEventDataWorkerData->newGroup, commonEventDataWorkerData->userId,
+ commonEventDataWorkerData->changeReason, commonEventDataWorkerData->bundleName.c_str());
+
+ return BundleStateCommon::NapiGetNull(commonEventDataWorkerData->env);
+}
+
+void UvQueueWorkOnBundleGroupChanged(uv_work_t *work, int status)
+{
+ BUNDLE_ACTIVE_LOGD("OnBundleGroupChanged uv_work_t start");
+ if (!work) {
+ return;
+ }
+ CallbackReceiveDataWorker *callbackReceiveDataWorkerData = (CallbackReceiveDataWorker *)work->data;
+ if (!callbackReceiveDataWorkerData || !callbackReceiveDataWorkerData->ref) {
+ BUNDLE_ACTIVE_LOGE("OnBundleGroupChanged commonEventDataWorkerData or ref is null");
+ delete work;
+ work = nullptr;
+ return;
+ }
+
+ napi_value result = nullptr;
+ napi_create_object(callbackReceiveDataWorkerData->env, &result);
+ if (!SetBundleGroupChangedData(callbackReceiveDataWorkerData, result)) {
+ delete work;
+ work = nullptr;
+ delete callbackReceiveDataWorkerData;
+ callbackReceiveDataWorkerData = nullptr;
+ return;
+ }
+
+ napi_value undefined = nullptr;
+ napi_get_undefined(callbackReceiveDataWorkerData->env, &undefined);
+
+ napi_value callback = nullptr;
+ napi_value resultout = nullptr;
+ napi_get_reference_value(callbackReceiveDataWorkerData->env, callbackReceiveDataWorkerData->ref, &callback);
+
+ napi_value results[ARGS_TWO] = {nullptr};
+ results[PARAM_FIRST] = BundleStateCommon::GetErrorValue(callbackReceiveDataWorkerData->env, NO_ERROR);
+ results[PARAM_SECOND] = result;
+ NAPI_CALL_RETURN_VOID(callbackReceiveDataWorkerData->env, napi_call_function(callbackReceiveDataWorkerData->env,
+ undefined, callback, ARGS_TWO, &results[PARAM_FIRST], &resultout));
+ delete callbackReceiveDataWorkerData;
+ callbackReceiveDataWorkerData = nullptr;
+ delete work;
+ work = nullptr;
+}
+
+/*
+* observer callback when group change
+*/
+void BundleActiveGroupObserver::OnBundleGroupChanged(const BundleActiveGroupCallbackInfo &bundleActiveGroupCallbackInfo)
+{
+ BUNDLE_ACTIVE_LOGD("OnBundleGroupChanged start");
+ uv_loop_s *loop = nullptr;
+ napi_get_uv_event_loop(bundleGroupCallbackInfo_.env, &loop);
+ if (!loop) {
+ BUNDLE_ACTIVE_LOGE("loop instance is nullptr");
+ return;
+ }
+ uv_work_t* work = new (std::nothrow) uv_work_t;
+ if (!work) {
+ BUNDLE_ACTIVE_LOGE("work is null");
+ return;
+ }
+ CallbackReceiveDataWorker* callbackReceiveDataWorker = new (std::nothrow) CallbackReceiveDataWorker();
+ if (!callbackReceiveDataWorker) {
+ BUNDLE_ACTIVE_LOGE("callbackReceiveDataWorker is null");
+ delete work;
+ work = nullptr;
+ return;
+ }
+ MessageParcel data;
+ if (!bundleActiveGroupCallbackInfo.Marshalling(data)) {
+ BUNDLE_ACTIVE_LOGE("Marshalling fail");
+ }
+ BundleActiveGroupCallbackInfo* callBackInfo = bundleActiveGroupCallbackInfo.Unmarshalling(data);
+ callbackReceiveDataWorker->oldGroup = callBackInfo->GetOldGroup();
+ callbackReceiveDataWorker->newGroup = callBackInfo->GetNewGroup();
+ callbackReceiveDataWorker->changeReason = callBackInfo->GetChangeReason();
+ callbackReceiveDataWorker->userId = callBackInfo->GetUserId();
+ callbackReceiveDataWorker->bundleName = callBackInfo->GetBundleName();
+ callbackReceiveDataWorker->env = bundleGroupCallbackInfo_.env;
+ callbackReceiveDataWorker->ref = bundleGroupCallbackInfo_.ref;
+
+ work->data = (void *)callbackReceiveDataWorker;
+ int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnBundleGroupChanged);
+ if (ret != 0) {
+ delete callbackReceiveDataWorker;
+ callbackReceiveDataWorker = nullptr;
+ delete work;
+ work = nullptr;
+ }
+}
+
+napi_value GetBundleGroupChangeCallback(const napi_env &env, const napi_value &value)
+{
+ napi_ref result = nullptr;
+
+ registerObserver = new (std::nothrow) BundleActiveGroupObserver();
+ if (!registerObserver) {
+ BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack callback is null");
+ return BundleStateCommon::NapiGetNull(env);
+ }
+ napi_create_reference(env, value, 1, &result);
+ registerObserver->SetCallbackInfo(env, result);
+
+ return BundleStateCommon::NapiGetNull(env);
+}
+
+napi_value ParseRegisterGroupCallBackParameters(const napi_env &env, const napi_callback_info &info,
+ RegisterCallbackInfo ¶ms, AsyncRegisterCallbackInfo* &asyncCallbackInfo)
+{
+ size_t argc = REGISTER_GROUP_CALLBACK_PARAMS;
+ napi_value argv[REGISTER_GROUP_CALLBACK_PARAMS] = {nullptr};
+ NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL));
+ NAPI_ASSERT(env, argc == REGISTER_GROUP_CALLBACK_MIN_PARAMS || argc == REGISTER_GROUP_CALLBACK_PARAMS,
+ "Invalid number of parameters");
+
+ // arg[0] : callback
+ napi_valuetype valuetype = napi_undefined;
+ NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype));
+ if (registerObserver) {
+ BUNDLE_ACTIVE_LOGI("RegisterGroupCallBack repeat!");
+ params.errorCode = ERR_REPEAT_OPERATION;
+ } else if (valuetype != napi_function || !GetBundleGroupChangeCallback(env, argv[0])) {
+ BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack bundleActiveGroupObserverInfo parse failed");
+ params.errorCode = ERR_OBSERVER_CALLBACK_IS_INVALID;
+ }
+
+ // argv[1]: asyncCallback
+ if (argc == REGISTER_GROUP_CALLBACK_PARAMS) {
+ napi_valuetype valuetype = napi_undefined;
+ NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype));
+ NAPI_ASSERT(env, valuetype == napi_function, "ParseStatesParameters invalid parameter type. Function expected");
+ napi_create_reference(env, argv[1], 1, ¶ms.callback);
+ }
+ BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo);
+ return BundleStateCommon::NapiGetNull(env);
+}
+
+napi_value RegisterGroupCallBack(napi_env env, napi_callback_info info)
+{
+ RegisterCallbackInfo params;
+ AsyncRegisterCallbackInfo *asyncCallbackInfo = nullptr;
+ ParseRegisterGroupCallBackParameters(env, info, params, asyncCallbackInfo);
+ if (params.errorCode != ERR_OK) {
+ return BundleStateCommon::JSParaError(env, params.callback, params.errorCode);
+ }
+ std::unique_ptr callbackPtr {asyncCallbackInfo};
+ callbackPtr->observer = registerObserver;
+ napi_value promise = nullptr;
+ BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise);
+ napi_value resourceName = nullptr;
+ NAPI_CALL(env, napi_create_string_latin1(env, "RegisterGroupCallBack", NAPI_AUTO_LENGTH, &resourceName));
+ NAPI_CALL(env, napi_create_async_work(env,
+ nullptr,
+ resourceName,
+ [](napi_env env, void *data) {
+ AsyncRegisterCallbackInfo *asyncCallbackInfo = (AsyncRegisterCallbackInfo *)data;
+ if (asyncCallbackInfo) {
+ asyncCallbackInfo->errorCode =
+ BundleActiveClient::GetInstance().RegisterGroupCallBack(asyncCallbackInfo->observer);
+ } else {
+ BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack, asyncCallbackInfo == nullptr");
+ }
+ },
+ [](napi_env env, napi_status status, void *data) {
+ AsyncRegisterCallbackInfo *asyncCallbackInfo = (AsyncRegisterCallbackInfo *)data;
+ if (asyncCallbackInfo) {
+ napi_value result = nullptr;
+ napi_get_null(env, &result);
+ BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result);
+ }
+ },
+ (void *)asyncCallbackInfo,
+ &asyncCallbackInfo->asyncWork));
+ NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork));
+ if (callbackPtr->isCallback) {
+ callbackPtr.release();
+ return BundleStateCommon::NapiGetNull(env);
+ } else {
+ callbackPtr.release();
+ return promise;
+ }
+}
+
+napi_value ParseUnRegisterGroupCallBackParameters(const napi_env &env, const napi_callback_info &info,
+ UnRegisterCallbackInfo ¶ms, AsyncUnRegisterCallbackInfo* &asyncCallbackInfo)
+{
+ size_t argc = UN_REGISTER_GROUP_CALLBACK_PARAMS;
+ napi_value argv[UN_REGISTER_GROUP_CALLBACK_PARAMS] = {nullptr};
+ NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL));
+ NAPI_ASSERT(env, argc == UN_REGISTER_GROUP_CALLBACK_MIN_PARAMS || argc == UN_REGISTER_GROUP_CALLBACK_PARAMS,
+ "Invalid number of parameters");
+
+ // argv[1]: callback
+ if (argc == UN_REGISTER_GROUP_CALLBACK_PARAMS) {
+ napi_valuetype valuetype = napi_undefined;
+ NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype));
+ NAPI_ASSERT(env, valuetype == napi_function, "ParseStatesParameters invalid parameter type. "
+ "Function expected.");
+ napi_create_reference(env, argv[0], 1, ¶ms.callback);
+ }
+ if (!registerObserver) {
+ BUNDLE_ACTIVE_LOGI("UnRegisterGroupCallBack observer is not exist");
+ params.errorCode = ERR_REGISTER_OBSERVER_IS_NULL;
+ return BundleStateCommon::NapiGetNull(env);
+ }
+ BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo);
+ return BundleStateCommon::NapiGetNull(env);
+}
+
+napi_value UnRegisterGroupCallBack(napi_env env, napi_callback_info info)
+{
+ UnRegisterCallbackInfo params;
+ AsyncUnRegisterCallbackInfo *asyncCallbackInfo = nullptr;
+ ParseUnRegisterGroupCallBackParameters(env, info, params, asyncCallbackInfo);
+ if (params.errorCode != ERR_OK) {
+ return BundleStateCommon::JSParaError(env, params.callback, params.errorCode);
+ }
+ std::unique_ptr callbackPtr {asyncCallbackInfo};
+ callbackPtr->observer = registerObserver;
+ napi_value promise = nullptr;
+ BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise);
+ napi_value resourceName = nullptr;
+ NAPI_CALL(env, napi_create_string_latin1(env, "UnRegisterGroupCallBack", NAPI_AUTO_LENGTH, &resourceName));
+ NAPI_CALL(env, napi_create_async_work(env,
+ nullptr,
+ resourceName,
+ [](napi_env env, void *data) {
+ AsyncUnRegisterCallbackInfo *asyncCallbackInfo = (AsyncUnRegisterCallbackInfo *)data;
+ if (asyncCallbackInfo != nullptr) {
+ asyncCallbackInfo->errorCode =
+ BundleActiveClient::GetInstance().UnregisterGroupCallBack(asyncCallbackInfo->observer);
+ } else {
+ BUNDLE_ACTIVE_LOGE("UnRegisterGroupCallBack, asyncCallbackInfo == nullptr");
+ }
+ },
+ [](napi_env env, napi_status status, void *data) {
+ AsyncUnRegisterCallbackInfo *asyncCallbackInfo = (AsyncUnRegisterCallbackInfo *)data;
+ if (asyncCallbackInfo != nullptr) {
+ napi_value result = nullptr;
+ napi_get_null(env, &result);
+ BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result);
+ }
+ },
+ (void *)asyncCallbackInfo,
+ &asyncCallbackInfo->asyncWork));
+ NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork));
+ registerObserver = nullptr;
+ if (callbackPtr->isCallback) {
+ callbackPtr.release();
+ return BundleStateCommon::NapiGetNull(env);
+ } else {
+ callbackPtr.release();
+ return promise;
+ }
+}
+} // namespace DeviceUsageStats
+} // namespace OHOS
\ No newline at end of file
diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp
index ae6a6d52bb30833861798993a034fd65150da467..9bcc0a8456a9db75cdc812a20dd5b3100f17eb6d 100644
--- a/frameworks/src/bundle_state_common.cpp
+++ b/frameworks/src/bundle_state_common.cpp
@@ -16,7 +16,6 @@
#include "securec.h"
#include "bundle_active_log.h"
-#include "bundle_state_data.h"
#include "bundle_state_common.h"
namespace OHOS {
@@ -67,7 +66,13 @@ void BundleStateCommon::SetCallbackInfo(
napi_value resultout = nullptr;
napi_get_reference_value(env, callbackIn, &callback);
napi_value results[ARGS_TWO] = {nullptr};
- results[PARAM_FIRST] = GetErrorValue(env, errorCode);
+ if (errorCode == -1) {
+ results[PARAM_FIRST] = GetErrorValue(env, ERR_SERVICE_FAILED);
+ } else if (errorCode == 1) {
+ results[PARAM_FIRST] = GetErrorValue(env, ERR_REPEAT_OPERATION);
+ } else {
+ results[PARAM_FIRST] = GetErrorValue(env, errorCode);
+ }
results[PARAM_SECOND] = result;
NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &results[PARAM_FIRST],
&resultout));
@@ -128,6 +133,58 @@ void BundleStateCommon::GetBundleStateInfoByIntervalForResult(
}
}
+void BundleStateCommon::GetBundleActiveEventStatsForResult(napi_env env,
+ const std::vector &eventStats, napi_value result)
+{
+ int32_t index = 0;
+ for (const auto &item : eventStats) {
+ napi_value eventStatsObject = nullptr;
+ NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &eventStatsObject));
+
+ napi_value name = nullptr;
+ NAPI_CALL_RETURN_VOID(
+ env, napi_create_string_utf8(env, item.name_.c_str(), NAPI_AUTO_LENGTH, &name));
+ NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "name", name));
+
+ napi_value eventId = nullptr;
+ NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.eventId_, &eventId));
+ NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "eventId", eventId));
+
+ napi_value count = nullptr;
+ NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.count_, &count));
+ NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "count", count));
+
+ NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, eventStatsObject));
+ index++;
+ }
+}
+
+void BundleStateCommon::GetBundleActiveNotificationNumberForResult(napi_env env,
+ const std::vector &eventStats, napi_value result)
+{
+ int32_t index = 0;
+ for (const auto &item : eventStats) {
+ napi_value eventStatsObject = nullptr;
+ NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &eventStatsObject));
+
+ napi_value name = nullptr;
+ NAPI_CALL_RETURN_VOID(
+ env, napi_create_string_utf8(env, item.name_.c_str(), NAPI_AUTO_LENGTH, &name));
+ NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "name", name));
+
+ napi_value eventId = nullptr;
+ NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.eventId_, &eventId));
+ NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "eventId", eventId));
+
+ napi_value count = nullptr;
+ NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.count_, &count));
+ NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, eventStatsObject, "count", count));
+
+ NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, eventStatsObject));
+ index++;
+ }
+}
+
void BundleStateCommon::GetBundleStateInfoForResult(napi_env env,
const std::shared_ptr> &packageStats, napi_value result)
{
@@ -248,10 +305,19 @@ void BundleStateCommon::GetModuleRecordForResult(napi_env env,
void BundleStateCommon::SetPromiseInfo(const napi_env &env, const napi_deferred &deferred,
const napi_value &result, const int32_t &errorCode)
{
- if (errorCode == ERR_OK) {
- napi_resolve_deferred(env, deferred, result);
- } else {
- napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode));
+ switch (errorCode) {
+ case ERR_OK:
+ napi_resolve_deferred(env, deferred, result);
+ break;
+ case -1:
+ napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_SERVICE_FAILED));
+ break;
+ case 1:
+ napi_reject_deferred(env, deferred, GetErrorValue(env, ERR_REPEAT_OPERATION));
+ break;
+ default:
+ napi_reject_deferred(env, deferred, GetErrorValue(env, errorCode));
+ break;
}
}
@@ -394,6 +460,27 @@ void BundleStateCommon::MergePackageStats(BundleActivePackageStats &left, const
left.totalContiniousTaskUsedTime_ += right.totalContiniousTaskUsedTime_;
left.bundleStartedCount_ += right.bundleStartedCount_;
}
+
+std::unique_ptr BundleStateCommon::HandleEventStatsInfo(
+ AsyncCallbackInfoEventStats *asyncCallbackInfo, EventStatesParamsInfo ¶ms)
+{
+ if (!asyncCallbackInfo) {
+ params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR;
+ return nullptr;
+ }
+ if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) != EOK) {
+ params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED;
+ delete asyncCallbackInfo;
+ asyncCallbackInfo = nullptr;
+ return nullptr;
+ }
+ std::unique_ptr callbackPtr {asyncCallbackInfo};
+ callbackPtr->beginTime = params.beginTime;
+ callbackPtr->endTime = params.endTime;
+ BUNDLE_ACTIVE_LOGI("CallbackPtr->beginTime: %{public}lld, callbackPtr->endTime: %{public}lld",
+ (long long)callbackPtr->beginTime, (long long)callbackPtr->endTime);
+ return callbackPtr;
+}
} // namespace DeviceUsageStats
} // namespace OHOS
diff --git a/frameworks/src/bundle_state_init.cpp b/frameworks/src/bundle_state_init.cpp
index 56e36f89b19d0ca4be68425304fcf744fb134228..99dddd2fc59cfb91799c180d69570b240e069d73 100644
--- a/frameworks/src/bundle_state_init.cpp
+++ b/frameworks/src/bundle_state_init.cpp
@@ -15,6 +15,7 @@
#include "bundle_state_condition.h"
#include "bundle_state_query.h"
+#include "bundle_active_group_observer.h"
#include "bundle_state_init.h"
namespace OHOS {
@@ -23,7 +24,7 @@ EXTERN_C_START
static const uint8_t ARG_FIRST = 1;
-napi_ref intervalTypeConstructor_ = nullptr;
+napi_ref typeConstructor_ = nullptr;
/*
* Module export function
@@ -40,12 +41,18 @@ static napi_value BundleStateInit(napi_env env, napi_value exports)
DECLARE_NAPI_FUNCTION("queryBundleActiveStates", QueryBundleActiveStates),
DECLARE_NAPI_FUNCTION("queryBundleStateInfoByInterval", QueryBundleStateInfoByInterval),
DECLARE_NAPI_FUNCTION("queryBundleStateInfos", QueryBundleStateInfos),
- DECLARE_NAPI_FUNCTION("getRecentlyUsedModules", GetModuleUsageRecord)
+ DECLARE_NAPI_FUNCTION("getRecentlyUsedModules", GetModuleUsageRecord),
+ DECLARE_NAPI_FUNCTION("setBundleGroup", SetBundleGroup),
+ DECLARE_NAPI_FUNCTION("registerGroupCallBack", RegisterGroupCallBack),
+ DECLARE_NAPI_FUNCTION("unRegisterGroupCallBack", UnRegisterGroupCallBack),
+ DECLARE_NAPI_FUNCTION("queryBundleActiveEventStates", QueryBundleActiveEventStates),
+ DECLARE_NAPI_FUNCTION("queryAppNotificationNumber", QueryAppNotificationNumber)
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
InitIntervalType(env, exports);
+ InitGroupType(env, exports);
return exports;
}
@@ -78,14 +85,54 @@ napi_value InitIntervalType(napi_env env, napi_value exports)
};
napi_value result = nullptr;
- napi_define_class(env, "IntervalType", NAPI_AUTO_LENGTH, EnumIntervalTypeConstructor,
+ napi_define_class(env, "IntervalType", NAPI_AUTO_LENGTH, EnumTypeConstructor,
nullptr, sizeof(desc) / sizeof(*desc), desc, &result);
- napi_create_reference(env, result, refCount, &intervalTypeConstructor_);
+ napi_create_reference(env, result, refCount, &typeConstructor_);
napi_set_named_property(env, exports, "IntervalType", result);
return exports;
}
-napi_value EnumIntervalTypeConstructor(napi_env env, napi_callback_info info)
+napi_value InitGroupType(napi_env env, napi_value exports)
+{
+ napi_value active_group_alive;
+ napi_value active_group_daily;
+ napi_value active_group_fixed;
+ napi_value active_group_rare;
+ napi_value active_group_limit;
+ napi_value active_group_never;
+ int32_t refCount = 1;
+
+ napi_create_uint32(env, static_cast(BundleStateCondition::GroupType::ACTIVE_GROUP_ALIVE),
+ &active_group_alive);
+ napi_create_uint32(env, static_cast(BundleStateCondition::GroupType::ACTIVE_GROUP_DAILY),
+ &active_group_daily);
+ napi_create_uint32(env, static_cast(BundleStateCondition::GroupType::ACTIVE_GROUP_FIXED),
+ &active_group_fixed);
+ napi_create_uint32(env, static_cast(BundleStateCondition::GroupType::ACTIVE_GROUP_RARE),
+ &active_group_rare);
+ napi_create_uint32(env, static_cast(BundleStateCondition::GroupType::ACTIVE_GROUP_LIMIT),
+ &active_group_limit);
+ napi_create_uint32(env, static_cast(BundleStateCondition::GroupType::ACTIVE_GROUP_NEVER),
+ &active_group_never);
+
+ napi_property_descriptor desc[] = {
+ DECLARE_NAPI_STATIC_PROPERTY("ACTIVE_GROUP_ALIVE", active_group_alive),
+ DECLARE_NAPI_STATIC_PROPERTY("ACTIVE_GROUP_DAILY", active_group_daily),
+ DECLARE_NAPI_STATIC_PROPERTY("ACTIVE_GROUP_FIXED", active_group_fixed),
+ DECLARE_NAPI_STATIC_PROPERTY("ACTIVE_GROUP_RARE", active_group_rare),
+ DECLARE_NAPI_STATIC_PROPERTY("ACTIVE_GROUP_LIMIT", active_group_limit),
+ DECLARE_NAPI_STATIC_PROPERTY("ACTIVE_GROUP_NEVER", active_group_never),
+ };
+
+ napi_value result = nullptr;
+ napi_define_class(env, "GroupType", NAPI_AUTO_LENGTH, EnumTypeConstructor,
+ nullptr, sizeof(desc) / sizeof(*desc), desc, &result);
+ napi_create_reference(env, result, refCount, &typeConstructor_);
+ napi_set_named_property(env, exports, "GroupType", result);
+ return exports;
+}
+
+napi_value EnumTypeConstructor(napi_env env, napi_callback_info info)
{
size_t argc = 0;
napi_value args[ARG_FIRST] = {0};
diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp
index 7b840ef2e1889b1c220f3b79fb1a8df34223bee5..ab28cbc76e3133436726fa3ab2dd741ce5b902b7 100644
--- a/frameworks/src/bundle_state_query.cpp
+++ b/frameworks/src/bundle_state_query.cpp
@@ -19,6 +19,7 @@
#include "bundle_active_log.h"
#include "bundle_state_common.h"
#include "bundle_state_data.h"
+#include "bundle_active_group_observer.h"
#include "bundle_state_inner_errors.h"
namespace OHOS {
@@ -26,11 +27,14 @@ namespace DeviceUsageStats {
const uint32_t IS_IDLE_STATE_MIN_PARAMS = 1;
const uint32_t IS_IDLE_STATE_PARAMS = 2;
const uint32_t PRIORITY_GROUP_MIN_PARAMS = 0;
-const uint32_t PRIORITY_GROUP_PARAMS = 1;
+const uint32_t PRIORITY_GROUP_MIDDLE_PARAMS = 1;
+const uint32_t PRIORITY_GROUP_PARAMS = 2;
const uint32_t STATES_MIN_PARAMS = 2;
const uint32_t STATES_PARAMS = 3;
const uint32_t APP_USAGE_MIN_PARAMS_BY_INTERVAL = 3;
const uint32_t APP_USAGE_PARAMS_BY_INTERVAL = 4;
+const uint32_t APP_USAGE_MIN_PARAMS_BUNDLE_GROUP = 2;
+const uint32_t APP_USAGE_PARAMS_BUNDLE_GROUP = 3;
const uint32_t APP_USAGE_MIN_PARAMS = 2;
const uint32_t APP_USAGE_PARAMS = 3;
const uint32_t MODULE_RECORDS_MIN_PARAMS = 0;
@@ -39,6 +43,9 @@ const uint32_t MODULE_RECORDS_PARAMS = 2;
const uint32_t SECOND_ARG = 2;
const uint32_t THIRD_ARG = 3;
const int32_t MAXNUM_UP_LIMIT = 1000;
+const std::vector GROUP_TYPE {10, 20, 30, 40, 50, 60};
+const uint32_t EVENT_STATES_MIN_PARAMS = 2;
+const uint32_t EVENT_STATES_PARAMS = 3;
napi_value ParseModuleRecordsParameters(const napi_env &env, const napi_callback_info &info,
ModuleRecordParamsInfo ¶ms)
@@ -214,7 +221,7 @@ napi_value IsIdleState(napi_env env, napi_callback_info info)
AsyncCallbackInfoIsIdleState *asyncCallbackInfo = (AsyncCallbackInfoIsIdleState *)data;
if (asyncCallbackInfo != nullptr) {
asyncCallbackInfo->state = BundleActiveClient::GetInstance().IsBundleIdle(
- asyncCallbackInfo->bundleName);
+ asyncCallbackInfo->bundleName, asyncCallbackInfo->errorCode);
} else {
BUNDLE_ACTIVE_LOGE("IsIdleState, asyncCallbackInfo == nullptr");
}
@@ -240,43 +247,64 @@ napi_value IsIdleState(napi_env env, napi_callback_info info)
}
napi_value ParsePriorityGroupParameters(const napi_env &env, const napi_callback_info &info,
- PriorityGroupParamsInfo ¶ms)
+ PriorityGroupParamsInfo ¶ms, AsyncCallbackInfoPriorityGroup* &asyncCallbackInfo)
{
size_t argc = PRIORITY_GROUP_PARAMS;
napi_value argv[PRIORITY_GROUP_PARAMS] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL));
- NAPI_ASSERT(env, argc == PRIORITY_GROUP_MIN_PARAMS || argc == PRIORITY_GROUP_PARAMS,
- "Invalid number of parameters");
-
- // argv[0]: callback
- if (argc == PRIORITY_GROUP_PARAMS) {
+ NAPI_ASSERT(env, argc == PRIORITY_GROUP_MIN_PARAMS || argc == PRIORITY_GROUP_MIDDLE_PARAMS ||
+ argc == PRIORITY_GROUP_PARAMS, "Invalid number of parameters");
+ std::string result = "";
+ params.bundleName = "";
+ if (argc == PRIORITY_GROUP_MIDDLE_PARAMS) {
napi_valuetype valuetype = napi_undefined;
NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype));
- NAPI_ASSERT(env, valuetype == napi_function, "ParsePriorityGroupParameters invalid parameter type. "
- "Function expected.");
- napi_create_reference(env, argv[0], 1, ¶ms.callback);
+ if (valuetype == napi_function) {
+ napi_valuetype valuetype = napi_undefined;
+ NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype));
+ NAPI_ASSERT(env, valuetype == napi_function, "ParsePriorityGroupParameters invalid parameter type. "
+ "Function expected.");
+ napi_create_reference(env, argv[0], 1, ¶ms.callback);
+ } else {
+ params.bundleName = BundleStateCommon::GetTypeStringValue(env, argv[0], result);
+ if (params.bundleName.empty()) {
+ BUNDLE_ACTIVE_LOGE("ParsePriorityGroupParameters failed, bundleName is empty.");
+ params.errorCode = ERR_USAGE_STATS_BUNDLENAME_EMPTY;
+ }
+ }
+ } else if (argc == PRIORITY_GROUP_PARAMS) {
+ // argv[0] : bundleName
+ params.bundleName = BundleStateCommon::GetTypeStringValue(env, argv[0], result);
+ if (params.bundleName.empty()) {
+ BUNDLE_ACTIVE_LOGE("ParsePriorityGroupParameters failed, bundleName is empty.");
+ params.errorCode = ERR_USAGE_STATS_BUNDLENAME_EMPTY;
+ }
+ // argv[1]: callback
+ if (argc == PRIORITY_GROUP_PARAMS) {
+ napi_valuetype valuetype = napi_undefined;
+ NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype));
+ NAPI_ASSERT(env, valuetype == napi_function, "ParsePriorityGroupParameters invalid parameter type. "
+ "Function expected.");
+ napi_create_reference(env, argv[1], 1, ¶ms.callback);
+ }
}
+ BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo);
return BundleStateCommon::NapiGetNull(env);
}
napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info)
{
PriorityGroupParamsInfo params;
- ParsePriorityGroupParameters(env, info, params);
- napi_value promise = nullptr;
- AsyncCallbackInfoPriorityGroup *asyncCallbackInfo =
- new (std::nothrow) AsyncCallbackInfoPriorityGroup(env);
- if (!asyncCallbackInfo) {
- params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_NULLPTR;
- return BundleStateCommon::JSParaError(env, params.callback, params.errorCode);
- }
- if (memset_s(asyncCallbackInfo, sizeof(*asyncCallbackInfo), 0, sizeof(*asyncCallbackInfo)) != EOK) {
- params.errorCode = ERR_USAGE_STATS_ASYNC_CALLBACK_INIT_FAILED;
- delete asyncCallbackInfo;
- asyncCallbackInfo = nullptr;
+ AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = nullptr;
+ ParsePriorityGroupParameters(env, info, params, asyncCallbackInfo);
+ if (params.errorCode != ERR_OK) {
return BundleStateCommon::JSParaError(env, params.callback, params.errorCode);
}
std::unique_ptr callbackPtr {asyncCallbackInfo};
+ callbackPtr->bundleName = params.bundleName;
+ BUNDLE_ACTIVE_LOGD("QueryPackageGroup callbackPtr->bundleName: %{public}s",
+ callbackPtr->bundleName.c_str());
+ napi_value promise = nullptr;
BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise);
napi_value resourceName = nullptr;
NAPI_CALL(env, napi_create_string_latin1(env, "QueryAppUsagePriorityGroup", NAPI_AUTO_LENGTH, &resourceName));
@@ -285,15 +313,19 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info)
resourceName,
[](napi_env env, void *data) {
AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data;
- if (asyncCallbackInfo != nullptr) {
- asyncCallbackInfo->priorityGroup = BundleActiveClient::GetInstance().QueryPackageGroup();
+ if (asyncCallbackInfo) {
+ asyncCallbackInfo->priorityGroup =
+ BundleActiveClient::GetInstance().QueryPackageGroup(asyncCallbackInfo->bundleName);
} else {
BUNDLE_ACTIVE_LOGE("QueryAppUsagePriorityGroup, asyncCallbackInfo == nullptr");
}
},
[](napi_env env, napi_status status, void *data) {
AsyncCallbackInfoPriorityGroup *asyncCallbackInfo = (AsyncCallbackInfoPriorityGroup *)data;
- if (asyncCallbackInfo != nullptr) {
+ if (asyncCallbackInfo) {
+ if (asyncCallbackInfo->priorityGroup == -1) {
+ asyncCallbackInfo->errorCode = ERR_SERVICE_FAILED;
+ }
napi_value result = nullptr;
napi_create_int32(env, asyncCallbackInfo->priorityGroup, &result);
BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result);
@@ -380,10 +412,10 @@ napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info)
}
std::unique_ptr callbackPtr {asyncCallbackInfo};
callbackPtr->beginTime = params.beginTime;
- BUNDLE_ACTIVE_LOGI("QueryCurrentBundleActiveStates callbackPtr->beginTime: %{public}lld",
+ BUNDLE_ACTIVE_LOGD("QueryCurrentBundleActiveStates callbackPtr->beginTime: %{public}lld",
(long long)callbackPtr->beginTime);
callbackPtr->endTime = params.endTime;
- BUNDLE_ACTIVE_LOGI("QueryCurrentBundleActiveStates callbackPtr->endTime: %{public}lld",
+ BUNDLE_ACTIVE_LOGD("QueryCurrentBundleActiveStates callbackPtr->endTime: %{public}lld",
(long long)callbackPtr->endTime);
BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise);
@@ -413,7 +445,6 @@ napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info)
},
(void *)asyncCallbackInfo,
&asyncCallbackInfo->asyncWork));
-
NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork));
if (callbackPtr->isCallback) {
callbackPtr.release();
@@ -446,10 +477,10 @@ napi_value QueryBundleActiveStates(napi_env env, napi_callback_info info)
}
std::unique_ptr callbackPtr {asyncCallbackInfo};
callbackPtr->beginTime = params.beginTime;
- BUNDLE_ACTIVE_LOGI("QueryBundleActiveStates callbackPtr->beginTime: %{public}lld",
+ BUNDLE_ACTIVE_LOGD("QueryBundleActiveStates callbackPtr->beginTime: %{public}lld",
(long long)callbackPtr->beginTime);
callbackPtr->endTime = params.endTime;
- BUNDLE_ACTIVE_LOGI("QueryBundleActiveStates callbackPtr->endTime: %{public}lld",
+ BUNDLE_ACTIVE_LOGD("QueryBundleActiveStates callbackPtr->endTime: %{public}lld",
(long long)callbackPtr->endTime);
BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise);
@@ -572,13 +603,13 @@ napi_value QueryBundleStateInfoByInterval(napi_env env, napi_callback_info info)
}
std::unique_ptr callbackPtr {asyncCallbackInfo};
callbackPtr->intervalType = params.intervalType;
- BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval callbackPtr->intervalType: %{public}d",
+ BUNDLE_ACTIVE_LOGD("QueryBundleStateInfoByInterval callbackPtr->intervalType: %{public}d",
callbackPtr->intervalType);
callbackPtr->beginTime = params.beginTime;
- BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval callbackPtr->beginTime: %{public}lld",
+ BUNDLE_ACTIVE_LOGD("QueryBundleStateInfoByInterval callbackPtr->beginTime: %{public}lld",
(long long)callbackPtr->beginTime);
callbackPtr->endTime = params.endTime;
- BUNDLE_ACTIVE_LOGI("QueryBundleStateInfoByInterval callbackPtr->endTime: %{public}lld",
+ BUNDLE_ACTIVE_LOGD("QueryBundleStateInfoByInterval callbackPtr->endTime: %{public}lld",
(long long)callbackPtr->endTime);
BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise);
napi_value resourceName = nullptr;
@@ -684,10 +715,10 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info)
}
std::unique_ptr callbackPtr {asyncCallbackInfo};
callbackPtr->beginTime = params.beginTime;
- BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos callbackPtr->beginTime: %{public}lld",
+ BUNDLE_ACTIVE_LOGD("QueryBundleStateInfos callbackPtr->beginTime: %{public}lld",
(long long)callbackPtr->beginTime);
callbackPtr->endTime = params.endTime;
- BUNDLE_ACTIVE_LOGI("QueryBundleStateInfos callbackPtr->endTime: %{public}lld",
+ BUNDLE_ACTIVE_LOGD("QueryBundleStateInfos callbackPtr->endTime: %{public}lld",
(long long)callbackPtr->endTime);
BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise);
napi_value resourceName = nullptr;
@@ -724,6 +755,254 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info)
return promise;
}
}
+
+napi_value ParseAppUsageBundleGroupInfoParameters(const napi_env &env, const napi_callback_info &info,
+ ParamsBundleGroupInfo ¶ms, AsyncCallbackInfoSetBundleGroup* &asyncCallbackInfo)
+{
+ size_t argc = APP_USAGE_PARAMS_BUNDLE_GROUP;
+ napi_value argv[APP_USAGE_PARAMS_BUNDLE_GROUP] = {nullptr};
+ NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL));
+ NAPI_ASSERT(env, argc == APP_USAGE_MIN_PARAMS_BUNDLE_GROUP || argc == APP_USAGE_PARAMS_BUNDLE_GROUP,
+ "Invalid number of parameters");
+
+ // argv[0] : bundleName
+ std::string result = "";
+ params.bundleName = BundleStateCommon::GetTypeStringValue(env, argv[0], result);
+ if (params.bundleName.empty()) {
+ BUNDLE_ACTIVE_LOGE("ParseAppUsageBundleGroupInfoParameters failed, bundleName is empty.");
+ params.errorCode = ERR_USAGE_STATS_BUNDLENAME_EMPTY;
+ }
+ napi_valuetype valuetype;
+ NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype));
+ if ((valuetype != napi_string) && (params.errorCode == ERR_OK)) {
+ BUNDLE_ACTIVE_LOGE("Wrong argument type, string expected.");
+ params.errorCode = ERR_USAGE_STATS_BUNDLENAME_TYPE;
+ }
+ // argv[1] : newGroup
+ if ((params.errorCode == ERR_OK)
+ && (BundleStateCommon::GetInt32NumberValue(env, argv[1], params.newGroup) == nullptr)) {
+ BUNDLE_ACTIVE_LOGE("ParseAppUsageBundleGroupInfoParameters failed, newGroup type is invalid.");
+ params.errorCode = ERR_USAGE_STATS_GROUP_INVALID;
+ }
+ bool flag = false;
+ if (params.errorCode == ERR_OK) {
+ for (const auto& item : GROUP_TYPE) {
+ if (item == params.newGroup) {
+ flag = true;
+ break;
+ }
+ }
+ }
+ if ((params.errorCode == ERR_OK) && !flag) {
+ BUNDLE_ACTIVE_LOGE("ParseAppUsageBundleGroupInfoParameters failed, newGroup value is invalid.");
+ params.errorCode = ERR_USAGE_STATS_GROUP_INVALID;
+ }
+ // argv[SECOND_ARG]: callback
+ if (argc == APP_USAGE_PARAMS_BUNDLE_GROUP) {
+ napi_valuetype valuetype = napi_undefined;
+ NAPI_CALL(env, napi_typeof(env, argv[SECOND_ARG], &valuetype));
+ NAPI_ASSERT(env, valuetype == napi_function, "ParseAppUsageBundleGroupInfoParameters invalid parameter type. "
+ "Function expected.");
+ napi_create_reference(env, argv[SECOND_ARG], 1, ¶ms.callback);
+ }
+ BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo);
+ return BundleStateCommon::NapiGetNull(env);
+}
+
+napi_value SetBundleGroup(napi_env env, napi_callback_info info)
+{
+ ParamsBundleGroupInfo params;
+ AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = nullptr;
+ ParseAppUsageBundleGroupInfoParameters(env, info, params, asyncCallbackInfo);
+ if (params.errorCode != ERR_OK) {
+ return BundleStateCommon::JSParaError(env, params.callback, params.errorCode);
+ }
+ std::unique_ptr callbackPtr {asyncCallbackInfo};
+ callbackPtr->newGroup = params.newGroup;
+ callbackPtr->bundleName = params.bundleName;
+ BUNDLE_ACTIVE_LOGD("SetBundleGroup, bundleName is %{public}s, newGroup is %{public}d",
+ callbackPtr->bundleName.c_str(), callbackPtr->newGroup);
+ napi_value promise = nullptr;
+ BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise);
+ napi_value resourceName = nullptr;
+ NAPI_CALL(env, napi_create_string_latin1(env, "SetBundleGroup", NAPI_AUTO_LENGTH, &resourceName));
+ NAPI_CALL(env, napi_create_async_work(env,
+ nullptr,
+ resourceName,
+ [](napi_env env, void *data) {
+ AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = (AsyncCallbackInfoSetBundleGroup *)data;
+ if (asyncCallbackInfo) {
+ asyncCallbackInfo->errorCode = BundleActiveClient::GetInstance().SetBundleGroup(
+ asyncCallbackInfo->bundleName, asyncCallbackInfo->newGroup, asyncCallbackInfo->errorCode);
+ } else {
+ BUNDLE_ACTIVE_LOGE("SetBundleGroup, asyncCallbackInfo == nullptr");
+ }
+ },
+ [](napi_env env, napi_status status, void *data) {
+ AsyncCallbackInfoSetBundleGroup *asyncCallbackInfo = (AsyncCallbackInfoSetBundleGroup *)data;
+ if (asyncCallbackInfo) {
+ napi_value result = nullptr;
+ napi_get_null(env, &result);
+ BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result);
+ }
+ },
+ (void *)asyncCallbackInfo,
+ &asyncCallbackInfo->asyncWork));
+ NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork));
+ if (callbackPtr->isCallback) {
+ callbackPtr.release();
+ return BundleStateCommon::NapiGetNull(env);
+ } else {
+ callbackPtr.release();
+ return promise;
+ }
+}
+
+napi_value ParseEventStatesParameters(const napi_env &env, const napi_callback_info &info,
+ EventStatesParamsInfo ¶ms)
+{
+ size_t argc = EVENT_STATES_PARAMS;
+ napi_value argv[EVENT_STATES_PARAMS] = {nullptr};
+ NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL));
+ NAPI_ASSERT(env, argc == EVENT_STATES_MIN_PARAMS || argc == EVENT_STATES_PARAMS,
+ "Invalid number of parameters");
+
+ // argv[0] : beginTime
+ if ((params.errorCode == ERR_OK)
+ && ((BundleStateCommon::GetInt64NumberValue(env, argv[0], params.beginTime) == nullptr)
+ || (params.beginTime < TIME_NUMBER_MIN))) {
+ BUNDLE_ACTIVE_LOGE("ParseEventStatesParameters failed, beginTime is invalid.");
+ params.errorCode = ERR_USAGE_STATS_BEGIN_TIME_INVALID;
+ }
+
+ // argv[1] : endTime
+ if ((params.errorCode == ERR_OK)
+ && ((BundleStateCommon::GetInt64NumberValue(env, argv[1], params.endTime) == nullptr)
+ || (params.endTime < TIME_NUMBER_MIN))) {
+ BUNDLE_ACTIVE_LOGE("ParseEventStatesParameters failed, endTime is invalid.");
+ params.errorCode = ERR_USAGE_STATS_END_TIME_INVALID;
+ }
+ if ((params.errorCode == ERR_OK) && (params.endTime <= params.beginTime)) {
+ BUNDLE_ACTIVE_LOGE("ParseEventStatesParameters endTime(%{public}lld) <= beginTime(%{public}lld)",
+ (long long)params.endTime, (long long)params.beginTime);
+ params.errorCode = ERR_USAGE_STATS_TIME_INTERVAL;
+ }
+
+ // argv[SECOND_ARG]: callback
+ if (argc == EVENT_STATES_PARAMS) {
+ napi_valuetype valuetype = napi_undefined;
+ NAPI_CALL(env, napi_typeof(env, argv[SECOND_ARG], &valuetype));
+ NAPI_ASSERT(env, valuetype == napi_function, "ParseEventStatesParameters invalid parameter type. "
+ "Function expected.");
+ napi_create_reference(env, argv[SECOND_ARG], 1, ¶ms.callback);
+ }
+ return BundleStateCommon::NapiGetNull(env);
+}
+
+napi_value QueryBundleActiveEventStates(napi_env env, napi_callback_info info)
+{
+ EventStatesParamsInfo params;
+ ParseEventStatesParameters(env, info, params);
+ if (params.errorCode != ERR_OK) {
+ return BundleStateCommon::JSParaError(env, params.callback, params.errorCode);
+ }
+ napi_value promise = nullptr;
+ AsyncCallbackInfoEventStats *asyncCallbackInfo =
+ new (std::nothrow) AsyncCallbackInfoEventStats(env);
+ std::unique_ptr callbackPtr =
+ BundleStateCommon::HandleEventStatsInfo(asyncCallbackInfo, params);
+ if (!callbackPtr) {
+ return BundleStateCommon::JSParaError(env, params.callback, params.errorCode);
+ }
+ BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise);
+ napi_value resourceName = nullptr;
+ NAPI_CALL(env, napi_create_string_latin1(env, "QueryBundleActiveEventStates", NAPI_AUTO_LENGTH, &resourceName));
+ NAPI_CALL(env, napi_create_async_work(env,
+ nullptr,
+ resourceName,
+ [](napi_env env, void *data) {
+ AsyncCallbackInfoEventStats *asyncCallbackInfo = (AsyncCallbackInfoEventStats *)data;
+ if (asyncCallbackInfo != nullptr) {
+ asyncCallbackInfo->errorCode = BundleActiveClient::GetInstance()
+ .QueryEventStats(asyncCallbackInfo->beginTime,
+ asyncCallbackInfo->endTime, asyncCallbackInfo->eventStats);
+ } else {
+ BUNDLE_ACTIVE_LOGE("QueryBundleActiveEventStates, asyncCallbackInfo == nullptr");
+ }
+ },
+ [](napi_env env, napi_status status, void *data) {
+ AsyncCallbackInfoEventStats *asyncCallbackInfo = (AsyncCallbackInfoEventStats *)data;
+ if (asyncCallbackInfo != nullptr) {
+ napi_value result = nullptr;
+ napi_create_array(env, &result);
+ BundleStateCommon::GetBundleActiveEventStatsForResult(env, asyncCallbackInfo->eventStats, result);
+ BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result);
+ }
+ },
+ (void *)asyncCallbackInfo,
+ &asyncCallbackInfo->asyncWork));
+ NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork));
+ if (callbackPtr->isCallback) {
+ callbackPtr.release();
+ return BundleStateCommon::NapiGetNull(env);
+ } else {
+ callbackPtr.release();
+ return promise;
+ }
+}
+
+napi_value QueryAppNotificationNumber(napi_env env, napi_callback_info info)
+{
+ EventStatesParamsInfo params;
+ ParseEventStatesParameters(env, info, params);
+ if (params.errorCode != ERR_OK) {
+ return BundleStateCommon::JSParaError(env, params.callback, params.errorCode);
+ }
+ napi_value promise = nullptr;
+ AsyncCallbackInfoEventStats *asyncCallbackInfo =
+ new (std::nothrow) AsyncCallbackInfoEventStats(env);
+ std::unique_ptr callbackPtr =
+ BundleStateCommon::HandleEventStatsInfo(asyncCallbackInfo, params);
+ if (!callbackPtr) {
+ return BundleStateCommon::JSParaError(env, params.callback, params.errorCode);
+ }
+ BundleStateCommon::SettingAsyncWorkData(env, params.callback, *asyncCallbackInfo, promise);
+ napi_value resourceName = nullptr;
+ NAPI_CALL(env, napi_create_string_latin1(env, "QueryAppNotificationNumber", NAPI_AUTO_LENGTH, &resourceName));
+ NAPI_CALL(env, napi_create_async_work(env,
+ nullptr,
+ resourceName,
+ [](napi_env env, void *data) {
+ AsyncCallbackInfoEventStats *asyncCallbackInfo = (AsyncCallbackInfoEventStats *)data;
+ if (asyncCallbackInfo != nullptr) {
+ asyncCallbackInfo->errorCode = BundleActiveClient::GetInstance()
+ .QueryAppNotificationNumber(asyncCallbackInfo->beginTime,
+ asyncCallbackInfo->endTime, asyncCallbackInfo->eventStats);
+ } else {
+ BUNDLE_ACTIVE_LOGE("QueryAppNotificationNumber, asyncCallbackInfo == nullptr");
+ }
+ },
+ [](napi_env env, napi_status status, void *data) {
+ AsyncCallbackInfoEventStats *asyncCallbackInfo = (AsyncCallbackInfoEventStats *)data;
+ if (asyncCallbackInfo != nullptr) {
+ napi_value result = nullptr;
+ napi_create_array(env, &result);
+ BundleStateCommon::GetBundleActiveNotificationNumberForResult(env,
+ asyncCallbackInfo->eventStats, result);
+ BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result);
+ }
+ },
+ (void *)asyncCallbackInfo,
+ &asyncCallbackInfo->asyncWork));
+ NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork));
+ if (callbackPtr->isCallback) {
+ callbackPtr.release();
+ return BundleStateCommon::NapiGetNull(env);
+ } else {
+ callbackPtr.release();
+ return promise;
+ }
+}
} // namespace DeviceUsageStats
} // namespace OHOS
diff --git a/init/device_usage_statistics_service.cfg b/init/device_usage_statistics_service.cfg
index 193ac5da3de3bfd67ba68bfb10797288be375ad5..fe224844abef7213d1e3c861f79fc4e64892623f 100644
--- a/init/device_usage_statistics_service.cfg
+++ b/init/device_usage_statistics_service.cfg
@@ -2,6 +2,7 @@
"jobs" : [{
"name" : "post-fs-data",
"cmds" : [
+ "mkdir /data/service/el1/public/bundle_usage 0711 device_usage_stats device_usage_stats",
"start device_usage_stats_service"
]
}
@@ -9,9 +10,10 @@
"services" : [{
"name" : "device_usage_stats_service",
"path" : ["/system/bin/sa_main", "/system/profile/device_usage_stats_service.xml"],
- "uid" : "system",
- "gid" : ["system", "shell"],
- "secon" : "u:r:device_usage_stats_service:s0"
+ "uid" : "device_usage_stats",
+ "gid" : ["device_usage_stats", "shell"],
+ "secon" : "u:r:device_usage_stats_service:s0",
+ "apl" : "system_basic"
}
]
}
\ No newline at end of file
diff --git a/interfaces/innerkits/include/bundle_active_client.h b/interfaces/innerkits/include/bundle_active_client.h
index 3e60e1c5a45a18df265baf8e351adb3bfdd48302..a21e779499bbaf5f39bef4d0c49b1e7b509e31a4 100644
--- a/interfaces/innerkits/include/bundle_active_client.h
+++ b/interfaces/innerkits/include/bundle_active_client.h
@@ -16,11 +16,16 @@
#ifndef BUNDLE_ACTIVE_CLIENT_H
#define BUNDLE_ACTIVE_CLIENT_H
+#include
+
#include "ibundle_active_service.h"
#include "bundle_active_package_stats.h"
#include "bundle_active_event.h"
+#include "bundle_active_event_stats.h"
#include "bundle_active_package_stats.h"
#include "bundle_active_module_record.h"
+#include "event_handler.h"
+#include "event_runner.h"
namespace OHOS {
namespace DeviceUsageStats {
@@ -39,7 +44,7 @@ public:
* parameters: bundleName
* return: if bundle is idle, return true. if bundle is not idle, return false.
*/
- bool IsBundleIdle(const std::string& bundleName);
+ bool IsBundleIdle(const std::string& bundleName, int32_t& errCode, int32_t userId = -1);
/*
* function: QueryPackageStats, query all bundle usage statistics in specific time span for calling user.
* parameters: intervalType, beginTime, endTime, errCode
@@ -57,8 +62,9 @@ public:
/*
* function: SetBundleGroup, set specific bundle of specific user to a priority group.
* parameters: bundleName, newGroup, userId
+ * return : void
*/
- void SetBundleGroup(std::string bundleName, const int32_t newGroup, const int32_t userId);
+ int32_t SetBundleGroup(std::string bundleName, const int32_t newGroup, int32_t errCode, int32_t userId = -1);
/*
* function: QueryCurrentPackageStats, query bundle usage statistics in specific time span for calling bundle.
* parameters: intervalType, beginTime, endTime
@@ -74,34 +80,88 @@ public:
std::vector QueryCurrentEvents(const int64_t beginTime, const int64_t endTime);
/*
* function: QueryPackageGroup, query bundle priority group calling bundle.
+ * parameters: bundleName,userId
* return: the priority group of calling bundle.
*/
- int32_t QueryPackageGroup();
+ int32_t QueryPackageGroup(std::string& bundleName, const int32_t userId = -1);
/*
* function: QueryFormStatistics, query all from usage statistics in specific time span for calling user.
* parameters: maxNum, results, userId, default userId is -1 for JS API,
- * if other SAs call this API, they should explicit define userId
+ * if other SAs call this API, they should explicit define userId.
* return: errorcode.
*/
int32_t QueryFormStatistics(int32_t maxNum, std::vector& results, int32_t userId = -1);
/*
- * function: GetInstance, get instance of client.
- * return: object of BundleActiveClient.
+ * function: observe bundle group change event
+ * parameters: observer
+ * return: errorcode.
*/
- static BundleActiveClient& GetInstance();
+ int32_t RegisterGroupCallBack(const sptr &observer);
/*
- * function: BundleActiveClient, default constructor.
+ * function: unobserve bundle group change event
+ * parameters: observer
+ * return: errorcode.
*/
- BundleActiveClient() {}
+ int32_t UnregisterGroupCallBack(const sptr &observer);
+
/*
- * function: ~BundleActiveClient, default destructor.
+ * function: QueryEventStats, query all from event stats in specific time span for calling user.
+ * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API,
+ * if other SAs call this API, they should explicit define userId.
+ * return: errorcode.
*/
- ~BundleActiveClient() {}
+ int32_t QueryEventStats(int64_t beginTime, int64_t endTime,
+ std::vector& eventStats, int32_t userId = -1);
+
+ /*
+ * function: QueryAppNotificationNumber, query all app notification number in specific time span for calling user.
+ * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API,
+ * if other SAs call this API, they should explicit define userId.
+ * return: errorcode.
+ */
+ int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime,
+ std::vector& eventStats, int32_t userId = -1);
+ /*
+ * function: GetInstance, get instance of client.
+ * return: object of BundleActiveClient.
+ */
+ static BundleActiveClient& GetInstance();
+private:
+ class BundleActiveClientDeathRecipient : public IRemoteObject::DeathRecipient {
+ public:
+ /*
+ * function: BundleActiveClientDeathRecipient, default constructor.
+ */
+ BundleActiveClientDeathRecipient() = default;
+ /*
+ * function: ~BundleActiveClientDeathRecipient, default destructor.
+ */
+ ~BundleActiveClientDeathRecipient() = default;
+ /*
+ * function: setObserver.
+ */
+ void setObserver(const sptr &observer);
+ /*
+ * function: OnRemoteDied, PostTask when service(bundleActiveProxy_) is died.
+ */
+ void OnRemoteDied(const wptr &object) override;
+ /*
+ * function: OnServiceDiedInner, get bundleActiveProxy_ and registerGroupCallBack again.
+ */
+ void OnServiceDiedInner(const wptr &object);
- int32_t ShellDump(const std::vector &dumpOption, std::vector &dumpInfo);
+ private:
+ sptr observer_ = nullptr;
+ };
private:
bool GetBundleActiveProxy();
+ BundleActiveClient() {}
+ ~BundleActiveClient() {}
sptr bundleActiveProxy_;
+ sptr recipient_;
+ std::shared_ptr bundleClientRunner_ {nullptr};
+ std::shared_ptr bundleClientHandler_ {nullptr};
+ std::mutex mutex_;
};
} // namespace DeviceUsageStats
} // namespace OHOS
diff --git a/interfaces/innerkits/include/bundle_active_group_callback_info.h b/interfaces/innerkits/include/bundle_active_group_callback_info.h
new file mode 100644
index 0000000000000000000000000000000000000000..b774fcf624a3a3b1cfbf7c1457daafabd17b7d2a
--- /dev/null
+++ b/interfaces/innerkits/include/bundle_active_group_callback_info.h
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2022 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef BUNDLE_ACTIVE_GROUP_CALLBACK_INFO_H
+#define BUNDLE_ACTIVE_GROUP_CALLBACK_INFO_H
+
+#include
+#include
+
+#include "parcel.h"
+
+namespace OHOS {
+namespace DeviceUsageStats {
+class BundleActiveGroupCallbackInfo : public Parcelable {
+public:
+ BundleActiveGroupCallbackInfo() {};
+ BundleActiveGroupCallbackInfo(int32_t userId, int32_t oldGroup, int32_t newGroup, uint32_t changeReason,
+ std::string bundleName);
+
+ /**
+ * @brief Get the user id.
+ *
+ * @return The id of user.
+ */
+ int32_t GetUserId() const;
+
+ /**
+ * @brief Get the old group.
+ *
+ * @return old group of app.
+ */
+ int32_t GetOldGroup() const;
+
+ /**
+ * @brief Get the new group.
+ *
+ * @return the new group of app.
+ */
+ int32_t GetNewGroup() const;
+
+ /**
+ * @brief Get the reason of change group.
+ *
+ * @return the reason of change group.
+ */
+ uint32_t GetChangeReason() const;
+
+ /**
+ * @brief Get the name of bundle.
+ *
+ * @return The name of bundle.
+ */
+ std::string GetBundleName() const;
+
+ /**
+ * @brief Marshals a purpose into a parcel.
+ *
+ * @param parcel Indicates the parcel object for marshalling.
+ * @return True if success, else false.
+ */
+ bool Marshalling(Parcel &parcel) const;
+ static BundleActiveGroupCallbackInfo* Unmarshalling(Parcel &parcel);
+
+private:
+ bool ReadFromParcel(Parcel &parcel);
+
+private:
+ int32_t oldGroup_ {0};
+ int32_t newGroup_ {0};
+ int32_t userId_ {-1};
+ uint32_t changeReason_ {0};
+ std::string bundleName_ {""};
+};
+} // namespace DeviceUsageStats
+} // namespace OHOS
+#endif // BUNDLE_ACTIVE_GROUP_CALLBACK_INFO_H
\ No newline at end of file
diff --git a/interfaces/innerkits/include/bundle_active_group_callback_proxy.h b/interfaces/innerkits/include/bundle_active_group_callback_proxy.h
new file mode 100644
index 0000000000000000000000000000000000000000..a3b29e726bab2dff25e310c2ac988861b7dc26a2
--- /dev/null
+++ b/interfaces/innerkits/include/bundle_active_group_callback_proxy.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2022 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef BUNDLE_ACTIVE_GROUP_CALLBACK_PROXY_H
+#define BUNDLE_ACTIVE_GROUP_CALLBACK_PROXY_H
+
+#include "iremote_proxy.h"
+#include "ibundle_active_group_callback.h"
+
+namespace OHOS {
+namespace DeviceUsageStats {
+class BundleActiveGroupCallbackProxy : public IRemoteProxy {
+public:
+ explicit BundleActiveGroupCallbackProxy(const sptr& impl);
+ virtual ~BundleActiveGroupCallbackProxy() override;
+ DISALLOW_COPY_AND_MOVE(BundleActiveGroupCallbackProxy);
+ /*
+ * function: OnBundleGroupChanged, bundleGroupChanged callback, IPC proxy, send message to stub.
+ * parameters: bundleActiveGroupCallbackInfo
+ * return: void.
+ */
+ virtual void OnBundleGroupChanged(
+ const BundleActiveGroupCallbackInfo& continuousTaskCallbackInfo) override;
+
+private:
+ static inline BrokerDelegator delegator_;
+};
+} // namespace DeviceUsageStats
+} // namespace OHOS
+#endif // BUNDLE_ACTIVE_GROUP_CALLBACK_PROXY_H
\ No newline at end of file
diff --git a/interfaces/innerkits/include/bundle_active_group_callback_stub.h b/interfaces/innerkits/include/bundle_active_group_callback_stub.h
new file mode 100644
index 0000000000000000000000000000000000000000..a748c873c32cb52a99522df01199cbdcc187e64e
--- /dev/null
+++ b/interfaces/innerkits/include/bundle_active_group_callback_stub.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2021 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef BUNDLE_ACTIVE_GROUP_CALLBACK_STUB_H
+#define BUNDLE_ACTIVE_GROUP_CALLBACK_STUB_H
+
+#include "iremote_stub.h"
+#include "ibundle_active_group_callback.h"
+
+namespace OHOS {
+namespace DeviceUsageStats {
+class BundleActiveGroupCallbackStub : public IRemoteStub {
+public:
+ BundleActiveGroupCallbackStub()=default;
+ virtual ~BundleActiveGroupCallbackStub()=default;
+ /*
+ * function: OnRemoteRequest, handle message from proxy.
+ * parameters: code, data, reply, option
+ * return: errorcode.
+ */
+ virtual int OnRemoteRequest(
+ uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
+ /*
+ * function: OnBundleGroupChanged, bundleGroupChanged callback, handle message from proxy.
+ * parameters: bundleActiveGroupCallbackInfo
+ * return: void.
+ */
+ virtual void OnBundleGroupChanged(
+ const BundleActiveGroupCallbackInfo &bundleActiveGroupCallbackInfo) override;
+private:
+ DISALLOW_COPY_AND_MOVE(BundleActiveGroupCallbackStub);
+};
+} // namespace DeviceUsageStats
+} // namespace OHOS
+#endif // BUNDLE_ACTIVE_GROUP_CALLBACK_STUB_H
diff --git a/interfaces/innerkits/include/bundle_active_proxy.h b/interfaces/innerkits/include/bundle_active_proxy.h
index 50db119b8562420253f222480a039971aa6cc1ff..9e0a205ce81a8235735cf91e4a6b1fbf90184c24 100644
--- a/interfaces/innerkits/include/bundle_active_proxy.h
+++ b/interfaces/innerkits/include/bundle_active_proxy.h
@@ -18,9 +18,10 @@
#include "ibundle_active_service.h"
#include "bundle_active_event.h"
-#include "bundle_active_package_stats.h"
+#include "bundle_active_event_stats.h"
#include "bundle_active_package_stats.h"
#include "bundle_active_module_record.h"
+#include "ibundle_active_group_callback.h"
namespace OHOS {
namespace DeviceUsageStats {
@@ -37,7 +38,7 @@ public:
* parameters: bundleName
* return: if bundle is idle, return true. if bundle is not idle, return false.
*/
- bool IsBundleIdle(const std::string& bundleName) override;
+ bool IsBundleIdle(const std::string& bundleName, int32_t& errCode, int32_t userId = -1) override;
/*
* function: QueryPackageStats, query all bundle usage statistics in specific time span for calling user.
* parameters: intervalType, beginTime, endTime, errCode
@@ -56,7 +57,7 @@ public:
* function: SetBundleGroup, set specific bundle of specific user to a priority group.
* parameters: bundleName, newGroup, userId
*/
- void SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t userId) override;
+ int32_t SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t errCode, int32_t userId) override;
/*
* function: QueryCurrentPackageStats, query bundle usage statistics in specific time span for calling bundle.
* parameters: intervalType, beginTime, endTime
@@ -74,28 +75,58 @@ public:
* function: QueryPackageGroup, query bundle priority group calling bundle.
* return: the priority group of calling bundle.
*/
- int32_t QueryPackageGroup() override;
+ int32_t QueryPackageGroup(std::string& bundleName, const int32_t userId) override;
/*
* function: QueryFormStatistics, query all from usage statistics in specific time span for calling user.
* parameters: maxNum, results, userId, default userId is -1 for JS API,
- * if other SAs call this API, they should explicit define userId
+ * if other SAs call this API, they should explicit define userId.
* return: errorcode.
*/
int32_t QueryFormStatistics(int32_t maxNum, std::vector& results,
int32_t userId = -1) override;
/*
+ * function: QueryEventStats, query all from event stats in specific time span for calling user.
+ * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API,
+ * if other SAs call this API, they should explicit define userId.
+ * return: errorcode.
+ */
+ int32_t QueryEventStats(int64_t beginTime, int64_t endTime,
+ std::vector& eventStats, int32_t userId) override;
+ /*
+ * function: QueryAppNotificationNumber, query all app notification number in specific time span for calling user.
+ * parameters: beginTime, endTime, eventStats, userId, default userId is -1 for JS API,
+ * if other SAs call this API, they should explicit define userId.
+ * return: errorcode.
+ */
+ int32_t QueryAppNotificationNumber(int64_t beginTime, int64_t endTime,
+ std::vector& eventStats, int32_t userId) override;
+ /*
* function: BundleActiveProxy, default constructor.
* parameters: impl
*/
explicit BundleActiveProxy(const sptr& impl)
: IRemoteProxy(impl) {}
/*
+ * function: RegisterGroupCallBack, register the observer to groupObservers.
+ * parameters: observer
+ * return: result of RegisterGroupCallBack, true or false.
+ */
+ int32_t RegisterGroupCallBack(const sptr &observer) override;
+ /*
+ * function: UnregisterGroupCallBack, remove the observer from groupObservers.
+ * parameters: observer
+ * return: result of UnregisterGroupCallBack, true or false.
+ */
+ int32_t UnregisterGroupCallBack(const sptr &observer) override;
+ /*
* function: ~BundleActiveProxy, default destructor.
*/
virtual ~BundleActiveProxy() {}
private:
static inline BrokerDelegator delegator_;
+ int32_t IPCCommunication(int64_t beginTime, int64_t endTime, std::vector& eventStats,
+ int32_t userId, int32_t communicationFlag);
};
} // namespace DeviceUsageStats
} // namespace OHOS
diff --git a/interfaces/innerkits/include/ibundle_active_group_callback.h b/interfaces/innerkits/include/ibundle_active_group_callback.h
new file mode 100644
index 0000000000000000000000000000000000000000..296ed9f619e2225361a3045ec7e7fc13eb947ca5
--- /dev/null
+++ b/interfaces/innerkits/include/ibundle_active_group_callback.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2022 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef IBUNDLE_ACTIVE_GROUP_CALLBACK
+#define IBUNDLE_ACTIVE_GROUP_CALLBACK
+
+#include
+#include
+#include "iremote_object.h"
+
+#include "bundle_active_log.h"
+#include "bundle_active_group_callback_info.h"
+
+namespace OHOS {
+namespace DeviceUsageStats {
+class IBundleActiveGroupCallback : public IRemoteBroker {
+public:
+
+ /**
+ * @brief Called back when a continuous task stop.
+ *
+ * @param continuousTaskCallbackInfo Continuous task app info.
+ */
+ virtual void OnBundleGroupChanged(
+ const BundleActiveGroupCallbackInfo &bundleActiveGroupCallbackInfo) = 0;
+public:
+ DECLARE_INTERFACE_DESCRIPTOR(u"Resourceschedule.IBundleActiveGroupCallback");
+
+protected:
+ enum class message {
+ ON_BUNDLE_GROUP_CHANGED = 1
+ };
+};
+} // namespace BackgroundTaskMgr
+} // namespace OHOS
+#endif // IBUNDLE_ACTIVE_GROUP_CALLBACK
\ No newline at end of file
diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp
index ae9f26322e15ab40394d62a5db1d5eed1c763af5..0cd2f54efec4c8c82ac2e2dbd2f91d0ec46332b0 100644
--- a/interfaces/innerkits/src/bundle_active_client.cpp
+++ b/interfaces/innerkits/src/bundle_active_client.cpp
@@ -18,9 +18,8 @@
namespace OHOS {
namespace DeviceUsageStats {
namespace {
- const int32_t EVENTS_PARAM = 5;
- const int32_t PACKAGE_USAGE_PARAM = 6;
- const int32_t MODULE_USAGE_PARAM = 4;
+ const std::string BUNDLE_ACTIVE_CLIENT_NAME = "bundleActiveName";
+ static const int32_t DELAY_TIME = 5000;
}
BundleActiveClient& BundleActiveClient::GetInstance()
{
@@ -30,6 +29,10 @@ BundleActiveClient& BundleActiveClient::GetInstance()
bool BundleActiveClient::GetBundleActiveProxy()
{
+ if (bundleActiveProxy_ != nullptr) {
+ return true;
+ }
+ std::lock_guard lock(mutex_);
sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (!samgr) {
BUNDLE_ACTIVE_LOGE("Failed to get SystemAbilityManager.");
@@ -38,13 +41,26 @@ bool BundleActiveClient::GetBundleActiveProxy()
sptr object = samgr->GetSystemAbility(DEVICE_USAGE_STATISTICS_SYS_ABILITY_ID);
if (!object) {
- BUNDLE_ACTIVE_LOGE("Failed to get SystemAbility[1920] .");
+ BUNDLE_ACTIVE_LOGE("Failed to get SystemAbility[1907] .");
return false;
}
bundleActiveProxy_ = iface_cast(object);
if (!bundleActiveProxy_) {
- BUNDLE_ACTIVE_LOGE("Failed to get BundleActiveClient.");
+ BUNDLE_ACTIVE_LOGE("Failed to get BundleActiveProxy.");
+ return false;
+ }
+ if (!recipient_) {
+ recipient_ = new (std::nothrow) BundleActiveClientDeathRecipient();
+ }
+ bundleClientRunner_ = AppExecFwk::EventRunner::Create(BUNDLE_ACTIVE_CLIENT_NAME);
+ if (!bundleClientRunner_) {
+ BUNDLE_ACTIVE_LOGE("BundleActiveClient runner create failed!");
+ return false;
+ }
+ bundleClientHandler_ = std::make_shared(bundleClientRunner_);
+ if (!bundleClientHandler_) {
+ BUNDLE_ACTIVE_LOGE("BundleActiveClient handler create failed!");
return false;
}
return true;
@@ -59,12 +75,12 @@ int32_t BundleActiveClient::ReportEvent(BundleActiveEvent event, const int32_t u
return bundleActiveProxy_->ReportEvent(event, userId);
}
-bool BundleActiveClient::IsBundleIdle(const std::string& bundleName)
+bool BundleActiveClient::IsBundleIdle(const std::string& bundleName, int32_t& errCode, int32_t userId)
{
if (!GetBundleActiveProxy()) {
return -1;
}
- return bundleActiveProxy_->IsBundleIdle(bundleName);
+ return bundleActiveProxy_->IsBundleIdle(bundleName, errCode, userId);
}
std::vector BundleActiveClient::QueryPackageStats(const int32_t intervalType,
@@ -85,13 +101,13 @@ std::vector BundleActiveClient::QueryEvents(const int64_t beg
return bundleActiveProxy_->QueryEvents(beginTime, endTime, errCode, userId);
}
-void BundleActiveClient::SetBundleGroup(std::string bundleName, const int32_t newGroup, const int32_t userId)
+int32_t BundleActiveClient::SetBundleGroup(std::string bundleName, const int32_t newGroup,
+ int32_t errCode, int32_t userId)
{
if (!GetBundleActiveProxy()) {
- return;
+ return -1;
}
- bundleActiveProxy_->SetBundleGroup(bundleName, newGroup, userId);
- return;
+ return bundleActiveProxy_->SetBundleGroup(bundleName, newGroup, errCode, userId);
}
std::vector BundleActiveClient::QueryCurrentPackageStats(const int32_t intervalType,
@@ -111,12 +127,13 @@ std::vector BundleActiveClient::QueryCurrentEvents(const int6
return bundleActiveProxy_->QueryCurrentEvents(beginTime, endTime);
}
-int32_t BundleActiveClient::QueryPackageGroup()
+int32_t BundleActiveClient::QueryPackageGroup(std::string& bundleName, const int32_t userId)
{
if (!GetBundleActiveProxy()) {
return -1;
}
- return bundleActiveProxy_->QueryPackageGroup();
+ int32_t result = bundleActiveProxy_->QueryPackageGroup(bundleName, userId);
+ return result;
}
int32_t BundleActiveClient::QueryFormStatistics(int32_t maxNum, std::vector& results,
@@ -132,54 +149,73 @@ int32_t BundleActiveClient::QueryFormStatistics(int32_t maxNum, std::vectorQueryFormStatistics(maxNum, results, userId);
}
-int32_t BundleActiveClient::ShellDump(const std::vector &dumpOption, std::vector &dumpInfo)
-{
- int32_t ret = -1;
-
- if (dumpOption[1] == "Events") {
- std::vector eventResult;
- if (static_cast(dumpOption.size()) != EVENTS_PARAM) {
- return ret;
- }
- int64_t beginTime = std::stoll(dumpOption[2]);
- int64_t endTime = std::stoll(dumpOption[3]);
- int32_t userId = std::stoi(dumpOption[4]);
- eventResult = this->QueryEvents(beginTime, endTime, ret, userId);
- for (auto& oneEvent : eventResult) {
- dumpInfo.emplace_back(oneEvent.ToString());
- }
- } else if (dumpOption[1] == "PackageUsage") {
- std::vector packageUsageResult;
- if (static_cast(dumpOption.size()) != PACKAGE_USAGE_PARAM) {
- return ret;
- }
- int32_t intervalType = std::stoi(dumpOption[2]);
- int64_t beginTime = std::stoll(dumpOption[3]);
- int64_t endTime = std::stoll(dumpOption[4]);
- int32_t userId = std::stoi(dumpOption[5]);
- packageUsageResult = this->QueryPackageStats(intervalType, beginTime, endTime, ret, userId);
- for (auto& onePackageRecord : packageUsageResult) {
- dumpInfo.emplace_back(onePackageRecord.ToString());
- }
- } else if (dumpOption[1] == "ModuleUsage") {
- std::vector moduleResult;
- if (static_cast(dumpOption.size()) != MODULE_USAGE_PARAM) {
- return ret;
- }
- int32_t maxNum = std::stoi(dumpOption[2]);
- int32_t userId = std::stoi(dumpOption[3]);
- BUNDLE_ACTIVE_LOGI("M is %{public}d, u is %{public}d", maxNum, userId);
- ret = this->QueryFormStatistics(maxNum, moduleResult, userId);
- for (auto& oneModuleRecord : moduleResult) {
- dumpInfo.emplace_back(oneModuleRecord.ToString());
- for (uint32_t i = 0; i < oneModuleRecord.formRecords_.size(); i++) {
- std::string oneFormInfo = "form " + std::to_string(static_cast(i) + 1) + ", ";
- dumpInfo.emplace_back(oneFormInfo + oneModuleRecord.formRecords_[i].ToString());
- }
- }
- }
-
- return ret;
+int32_t BundleActiveClient::RegisterGroupCallBack(const sptr &observer)
+{
+ if (!GetBundleActiveProxy()) {
+ return -1;
+ }
+ int32_t result = bundleActiveProxy_->RegisterGroupCallBack(observer);
+ // AddDeathRecipient when RegisterGroupCallBack success
+ if (recipient_ && result == ERR_OK) {
+ recipient_->setObserver(observer);
+ bundleActiveProxy_->AsObject()->AddDeathRecipient(recipient_);
+ }
+ return result;
+}
+
+int32_t BundleActiveClient::UnregisterGroupCallBack(const sptr &observer)
+{
+ if (!GetBundleActiveProxy()) {
+ return -1;
+ }
+ int32_t result = bundleActiveProxy_->UnregisterGroupCallBack(observer);
+ if (recipient_) {
+ bundleActiveProxy_->AsObject()->RemoveDeathRecipient(recipient_);
+ }
+ return result;
+}
+
+int32_t BundleActiveClient::QueryEventStats(int64_t beginTime, int64_t endTime,
+ std::vector& eventStats, int32_t userId)
+{
+ if (!GetBundleActiveProxy()) {
+ return -1;
+ }
+ return bundleActiveProxy_->QueryEventStats(beginTime, endTime, eventStats, userId);
+}
+
+int32_t BundleActiveClient::QueryAppNotificationNumber(int64_t beginTime, int64_t endTime,
+ std::vector& eventStats, int32_t userId)
+{
+ if (!GetBundleActiveProxy()) {
+ return -1;
+ }
+ return bundleActiveProxy_->QueryAppNotificationNumber(beginTime, endTime, eventStats, userId);
+}
+
+void BundleActiveClient::BundleActiveClientDeathRecipient::setObserver(const sptr &observer)
+{
+ if (observer) {
+ observer_ = observer;
+ }
+}
+void BundleActiveClient::BundleActiveClientDeathRecipient::OnRemoteDied(const wptr &object)
+{
+ if (object == nullptr) {
+ BUNDLE_ACTIVE_LOGE("remote object is null.");
+ return;
+ }
+ BundleActiveClient::GetInstance().bundleActiveProxy_ = nullptr;
+ BundleActiveClient::GetInstance().bundleClientHandler_->PostTask([this, &object]() {
+ this->OnServiceDiedInner(object);
+ },
+ DELAY_TIME);
+}
+
+void BundleActiveClient::BundleActiveClientDeathRecipient::OnServiceDiedInner(const wptr &object)
+{
+ while (!BundleActiveClient::GetInstance().GetBundleActiveProxy()) { }
+ BundleActiveClient::GetInstance().RegisterGroupCallBack(observer_);
}
} // namespace DeviceUsageStats
} // namespace OHOS
diff --git a/interfaces/innerkits/src/bundle_active_group_callback_info.cpp b/interfaces/innerkits/src/bundle_active_group_callback_info.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..9e21f4cc7927ede524a1511311f4e8f72f9e9cb8
--- /dev/null
+++ b/interfaces/innerkits/src/bundle_active_group_callback_info.cpp
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2022 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "bundle_active_log.h"
+#include "bundle_active_group_callback_info.h"
+
+namespace OHOS {
+namespace DeviceUsageStats {
+BundleActiveGroupCallbackInfo::BundleActiveGroupCallbackInfo(int32_t userId, int32_t oldGroup, int32_t newGroup,
+ uint32_t changeReason, std::string bundleName)
+{
+ userId_ = userId;
+ oldGroup_ = oldGroup;
+ newGroup_ = newGroup;
+ changeReason_ = changeReason;
+ bundleName_ = bundleName;
+}
+
+int32_t BundleActiveGroupCallbackInfo::GetUserId() const
+{
+ return userId_;
+}
+
+int32_t BundleActiveGroupCallbackInfo::GetOldGroup() const
+{
+ return oldGroup_;
+}
+
+int32_t BundleActiveGroupCallbackInfo::GetNewGroup() const
+{
+ return newGroup_;
+}
+
+uint32_t BundleActiveGroupCallbackInfo::GetChangeReason() const
+{
+ return changeReason_;
+}
+
+std::string BundleActiveGroupCallbackInfo::GetBundleName() const
+{
+ return bundleName_;
+}
+
+bool BundleActiveGroupCallbackInfo::Marshalling(Parcel &parcel) const
+{
+ if (!parcel.WriteInt32(userId_)) {
+ BUNDLE_ACTIVE_LOGE("Failed to write userId_");
+ return false;
+ }
+
+ if (!parcel.WriteInt32(oldGroup_)) {
+ BUNDLE_ACTIVE_LOGE("Failed to write creator oldGroup_");
+ return false;
+ }
+
+ if (!parcel.WriteInt32(newGroup_)) {
+ BUNDLE_ACTIVE_LOGE("Failed to write creator newGroup_");
+ return false;
+ }
+
+ if (!parcel.WriteUint32(changeReason_)) {
+ BUNDLE_ACTIVE_LOGE("Failed to write creator changeReason_");
+ return false;
+ }
+
+ if (!parcel.WriteString(bundleName_)) {
+ BUNDLE_ACTIVE_LOGE("Failed to write bundleName_");
+ return false;
+ }
+ return true;
+}
+
+BundleActiveGroupCallbackInfo* BundleActiveGroupCallbackInfo::Unmarshalling(Parcel &parcel)
+{
+ BundleActiveGroupCallbackInfo* result = new (std::nothrow) BundleActiveGroupCallbackInfo();
+ result->userId_ = parcel.ReadInt32();
+ result->oldGroup_ = parcel.ReadInt32();
+ result->newGroup_ = parcel.ReadInt32();
+ result->changeReason_ = parcel.ReadUint32();
+ result->bundleName_ = parcel.ReadString();
+ return result;
+}
+}
+}
+
diff --git a/interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp b/interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..768d8093614a77445cdb2d432cc38cf8d7a15972
--- /dev/null
+++ b/interfaces/innerkits/src/bundle_active_group_callback_proxy.cpp
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2022 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include
+#include "errors.h"
+#include "bundle_active_log.h"
+#include "bundle_active_group_callback_proxy.h"
+
+namespace OHOS {
+namespace DeviceUsageStats {
+BundleActiveGroupCallbackProxy::BundleActiveGroupCallbackProxy(const sptr& impl)
+ : IRemoteProxy(impl) {}
+BundleActiveGroupCallbackProxy::~BundleActiveGroupCallbackProxy() {}
+
+void BundleActiveGroupCallbackProxy::OnBundleGroupChanged(
+ const BundleActiveGroupCallbackInfo &bundleActiveGroupCallbackInfo)
+{
+ sptr remote = Remote();
+ if (remote == nullptr) {
+ BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack remote is dead.");
+ return;
+ }
+ MessageParcel data;
+ if (!data.WriteInterfaceToken(BundleActiveGroupCallbackProxy::GetDescriptor())) {
+ BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack write interface token failed.");
+ return;
+ }
+ if (!data.WriteParcelable(&bundleActiveGroupCallbackInfo)) {
+ BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack write parcel failed.");
+ return;
+ }
+ MessageParcel reply;
+ MessageOption option = {MessageOption::TF_ASYNC};
+ int32_t ret = remote->SendRequest(
+ static_cast(IBundleActiveGroupCallback::message::ON_BUNDLE_GROUP_CHANGED), data, reply, option);
+ if (ret!= ERR_OK) {
+ BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack SendRequest failed, error code: %{public}d", ret);
+ }
+}
+} // namespace BackgroundTaskMgr
+} // namespace OHOS
\ No newline at end of file
diff --git a/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..266ff17dc4d9a5a583ecf111df314a126cb89382
--- /dev/null
+++ b/interfaces/innerkits/src/bundle_active_group_callback_stub.cpp
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2022 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "bundle_active_group_callback_stub.h"
+
+namespace OHOS {
+namespace DeviceUsageStats {
+int32_t BundleActiveGroupCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply,
+ MessageOption &option)
+{
+ std::u16string descriptor = BundleActiveGroupCallbackStub::GetDescriptor();
+ std::u16string remoteDescriptor = data.ReadInterfaceToken();
+ if (descriptor != remoteDescriptor) {
+ BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack OnRemoteRequest cannot get power mgr service");
+ return -1;
+ }
+ switch (code) {
+ case static_cast(IBundleActiveGroupCallback::message::ON_BUNDLE_GROUP_CHANGED): {
+ std::shared_ptr groupInfo(
+ data.ReadParcelable());
+ if (!groupInfo) {
+ BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack ReadParcelable failed");
+ return -1;
+ }
+ OnBundleGroupChanged(*(groupInfo.get()));
+ groupInfo = nullptr;
+ break;
+ }
+ default:
+ return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
+ }
+ return 0;
+}
+
+void BundleActiveGroupCallbackStub::OnBundleGroupChanged(
+ const BundleActiveGroupCallbackInfo &bundleActiveGroupCallbackInfo)
+{
+}
+} // namespace DeviceUsageStats
+} // namespace OHOS
+
diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp
index 43cfd63e8681295e3d7a08d577c8521bcda09e03..f9844895001348c194ef4ec0632d141556093fdf 100644
--- a/interfaces/innerkits/src/bundle_active_proxy.cpp
+++ b/interfaces/innerkits/src/bundle_active_proxy.cpp
@@ -33,18 +33,20 @@ int32_t BundleActiveProxy::ReportEvent(BundleActiveEvent& event, const int32_t u
return result;
}
-bool BundleActiveProxy::IsBundleIdle(const std::string& bundleName)
+bool BundleActiveProxy::IsBundleIdle(const std::string& bundleName, int32_t& errCode, int32_t userId)
{
MessageParcel data;
MessageParcel reply;
MessageOption option;
- if (!data.WriteInterfaceToken(GetDescriptor())) {
+ if (!data.WriteInterfaceToken(GetDescriptor()) ||
+ !data.WriteString(bundleName) ||
+ !data.WriteInt32(errCode) ||
+ !data.WriteInt32(userId)) {
return false;
}
- data.WriteString(bundleName);
Remote() -> SendRequest(IS_BUNDLE_IDLE, data, reply, option);
- int32_t result = reply.ReadInt32();
- BUNDLE_ACTIVE_LOGI("result is %{public}d", result);
+ bool result = reply.ReadInt32();
+ errCode = reply.ReadInt32();
return result;
}
@@ -75,7 +77,7 @@ std::vector BundleActiveProxy::QueryPackageStats(const
result.push_back(*tmp);
}
for (uint32_t i = 0; i < result.size(); i++) {
- BUNDLE_ACTIVE_LOGI("QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, "
+ BUNDLE_ACTIVE_LOGD("QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, "
"lastTimeUsed_ is %{public}lld, lastContiniousTaskUsed_ is %{public}lld, "
"totalInFrontTime_ is %{public}lld, totalContiniousTaskUsedTime_ is %{public}lld",
i + 1, result[i].bundleName_.c_str(),
@@ -116,18 +118,22 @@ std::vector BundleActiveProxy::QueryEvents(const int64_t begi
return result;
}
-void BundleActiveProxy::SetBundleGroup(const std::string& bundleName, int32_t newGroup, int32_t userId)
+int32_t BundleActiveProxy::SetBundleGroup(const std::string& bundleName, int32_t newGroup,
+ int32_t errCode, int32_t userId)
{
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(GetDescriptor())) {
- return;
+ return -1;
}
data.WriteString(bundleName);
data.WriteInt32(newGroup);
+ data.WriteInt32(errCode);
data.WriteInt32(userId);
+
Remote() -> SendRequest(SET_BUNDLE_GROUP, data, reply, option);
+ return reply.ReadInt32();
}
std::vector BundleActiveProxy::QueryCurrentPackageStats(const int32_t intervalType,
@@ -154,7 +160,7 @@ std::vector BundleActiveProxy::QueryCurrentPackageStat
result.push_back(*tmp);
}
for (uint32_t i = 0; i < result.size(); i++) {
- BUNDLE_ACTIVE_LOGI("QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, "
+ BUNDLE_ACTIVE_LOGD("QueryPackageStats result idx is %{public}d, bundleName_ is %{public}s, "
"lastTimeUsed_ is %{public}lld, lastContiniousTaskUsed_ is %{public}lld, "
"totalInFrontTime_ is %{public}lld, totalContiniousTaskUsedTime_ is %{public}lld",
i + 1, result[i].bundleName_.c_str(),
@@ -186,25 +192,27 @@ std::vector BundleActiveProxy::QueryCurrentEvents(const int64
result.push_back(*tmp);
}
for (uint32_t i = 0; i < result.size(); i++) {
- BUNDLE_ACTIVE_LOGI("QueryCurrentEvents event id is %{public}d, bundle name is %{public}s,"
+ BUNDLE_ACTIVE_LOGD("QueryCurrentEvents event id is %{public}d, bundle name is %{public}s,"
"time stamp is %{public}lld",
result[i].eventId_, result[i].bundleName_.c_str(), (long long)result[i].timeStamp_);
}
return result;
}
-int32_t BundleActiveProxy::QueryPackageGroup()
+int32_t BundleActiveProxy::QueryPackageGroup(std::string& bundleName, const int32_t userId)
{
MessageParcel data;
MessageParcel reply;
MessageOption option;
+
if (!data.WriteInterfaceToken(GetDescriptor())) {
return -1;
}
+ data.WriteString(bundleName);
+ data.WriteInt32(userId);
Remote() -> SendRequest(QUERY_BUNDLE_GROUP, data, reply, option);
- int32_t packageGroup = reply.ReadInt32();
- BUNDLE_ACTIVE_LOGI("QueryPackageGroup result is %{public}d", packageGroup);
- return packageGroup;
+ int32_t result = reply.ReadInt32();
+ return result;
}
int32_t BundleActiveProxy::QueryFormStatistics(int32_t maxNum, std::vector& results,
@@ -230,11 +238,11 @@ int32_t BundleActiveProxy::QueryFormStatistics(int32_t maxNum, std::vector &observer)
+{
+ if (!observer) {
+ BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack observer is nullptr");
+ return false;
+ }
+ MessageParcel data;
+ MessageParcel reply;
+ MessageOption option;
+ if (!data.WriteInterfaceToken(GetDescriptor())) {
+ BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack WriteInterfaceToken fail");
+ return false;
+ }
+ if (!data.WriteRemoteObject(observer->AsObject())) {
+ BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack observer write failed.");
+ return false;
+ }
+ int32_t ret = Remote()->SendRequest(REGISTER_GROUP_CALLBACK, data, reply, option);
+ if (ret!= ERR_OK) {
+ BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack SendRequest failed, error code: %{public}d", ret);
+ }
+ return reply.ReadInt32();
+}
+
+int32_t BundleActiveProxy::UnregisterGroupCallBack(const sptr &observer)
+{
+ if (!observer) {
+ BUNDLE_ACTIVE_LOGE("UnregisterGroupCallBack observer is nullptr");
+ return false;
+ }
+ MessageParcel data;
+ MessageParcel reply;
+ MessageOption option;
+ if (!data.WriteInterfaceToken(GetDescriptor())) {
+ return false;
+ }
+ if (!data.WriteRemoteObject(observer->AsObject())) {
+ BUNDLE_ACTIVE_LOGE("UnregisterGroupCallBack observer write failed.");
+ return false;
+ }
+ Remote()->SendRequest(UNREGISTER_GROUP_CALLBACK, data, reply, option);
+ return reply.ReadInt32();
+}
+
+int32_t BundleActiveProxy::QueryEventStats(int64_t beginTime, int64_t endTime,
+ std::vector& eventStats, int32_t userId)
+{
+ int32_t errCode = IPCCommunication(beginTime, endTime, eventStats, userId, QUERY_EVENT_STATS);
+ for (const auto& singleEvent : eventStats) {
+ BUNDLE_ACTIVE_LOGD("QueryEventStats name is %{public}s, eventId is %{public}d, count is %{public}d",
+ singleEvent.name_.c_str(), singleEvent.eventId_, singleEvent.count_);
+ }
+ return errCode;
+}
+
+int32_t BundleActiveProxy::QueryAppNotificationNumber(int64_t beginTime, int64_t endTime,
+ std::vector& eventStats, int32_t userId)
+{
+ int32_t errCode = IPCCommunication(beginTime, endTime, eventStats, userId, QUERY_APP_NOTIFICATION_NUMBER);
+ for (const auto& singleEvent : eventStats) {
+ BUNDLE_ACTIVE_LOGD("QueryAppNotificationNumber name is %{public}s, eventId is %{public}d, count is %{public}d",
+ singleEvent.name_.c_str(), singleEvent.eventId_, singleEvent.count_);
+ }
+ return errCode;
+}
+
+int32_t BundleActiveProxy::IPCCommunication(int64_t beginTime, int64_t endTime,
+ std::vector& eventStats, int32_t userId, int32_t communicationFlag)
+{
+ MessageParcel data;
+ MessageParcel reply;
+ MessageOption option;
+ if (!data.WriteInterfaceToken(GetDescriptor())) {
+ return -1;
+ }
+ data.WriteInt64(beginTime);
+ data.WriteInt64(endTime);
+ data.WriteInt32(userId);
+ Remote() -> SendRequest(communicationFlag, data, reply, option);
+ int32_t errCode = reply.ReadInt32();
+ int32_t size = reply.ReadInt32();
+ std::shared_ptr tmp;
+ for (int32_t i = 0; i < size; i++) {
+ tmp = tmp->UnMarshalling(reply);
+ if (!tmp) {
+ continue;
+ }
+ eventStats.emplace_back(*tmp);
+ }
+ return errCode;
+}
} // namespace DeviceUsageStats
} // namespace OHOS
diff --git a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts
index 100791b48bf5abf63c747a480b2f3a3fbbeb150b..2def2921ff3a1310fcf7debf92c7ae355184dd4f 100644
--- a/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts
+++ b/interfaces/kits/bundlestats/js/@ohos.bundleState.d.ts
@@ -13,7 +13,7 @@
* limitations under the License.
*/
-import { AsyncCallback } from './basic';
+import { AsyncCallback , Callback} from './basic';
/**
* Provides methods for managing bundle usage statistics,
@@ -174,6 +174,28 @@ declare namespace bundleState {
formRecords: Array;
}
+ /**
+ * @since 9
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App
+ * @systemapi Hide this for inner system use.
+ */
+ interface BundleActiveEventState {
+ /**
+ * the bundle name or system event name.
+ */
+ name: string;
+
+ /**
+ * the event id.
+ */
+ eventId: number;
+
+ /**
+ * the the event occurrence number.
+ */
+ count: number;
+ }
+
/**
* @since 7
* @syscap SystemCapability.ResourceSchedule.UsageStatistics.App
@@ -204,6 +226,32 @@ declare namespace bundleState {
*/
stateType?: number;
}
+ /**
+ * @since 9
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
+ */
+ interface BundleActiveGroupCallbackInfo {
+ /*
+ * the usage old group of the application
+ */
+ appUsageOldGroup: number;
+ /*
+ * the usage new group of the application
+ */
+ appUsageNewGroup: number;
+ /*
+ * the use id
+ */
+ userId: number;
+ /*
+ * the change reason
+ */
+ changeReason: number;
+ /*
+ * the bundle name
+ */
+ bundleName: string;
+ }
/**
* Checks whether the application with a specified bundle name is in the idle state.
@@ -332,17 +380,138 @@ declare namespace bundleState {
function queryCurrentBundleActiveStates(begin: number, end: number): Promise>;
/**
- * Queries module usage records.
+ * Queries recently module usage records.
*
* @since 9
* @syscap SystemCapability.ResourceSchedule.UsageStatistics.App
* @permission ohos.permission.BUNDLE_ACTIVE_INFO
* @systemapi Hide this for inner system use.
* @param maxNum Indicates max record number in result, max value is 1000, default value is 1000.
- * @return Returns the {@link BundleActiveModuleInfo} object Array containing the state data of the current module.
+ * @return Returns the {@link BundleActiveModuleInfo} object Array containing the usage data of the modules.
*/
function getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback>): void;
function getRecentlyUsedModules(maxNum?: number): Promise>;
+
+ /**
+ * Queries the usage priority group of the calling application.
+ *
+ * The priority defined in a priority group restricts the resource usage of an application,
+ * for example, restricting the running of background tasks.
+ *
+ * @since 9
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO
+ * @systemapi Hide this for inner system use.
+ * @param bundleName, name of the application.
+ * @return Returns the usage priority group of the calling application.
+ */
+ function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback): void;
+ function queryAppUsagePriorityGroup(bundleName? : string): Promise;
+
+ /**
+ * Declares group type.
+ *
+ * @since 9
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
+ */
+ export enum GroupType {
+ /**
+ * Indicates the alive group.
+ */
+ ACTIVE_GROUP_ALIVE = 10,
+
+ /**
+ * Indicates the daily group.
+ */
+ ACTIVE_GROUP_DAILY = 20,
+
+ /**
+ * Indicates the fixed group.
+ */
+ ACTIVE_GROUP_FIXED = 30,
+
+ /**
+ * Indicates the rare group.
+ */
+ ACTIVE_GROUP_RARE = 40,
+
+ /**
+ * Indicates the limit group.
+ */
+ ACTIVE_GROUP_LIMIT = 50,
+
+ /**
+ * Indicates the never group.
+ */
+ ACTIVE_GROUP_NEVER = 60
+ }
+
+ /**
+ * set bundle group by bundleName and number.
+ *
+ * @since 9
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO
+ * @systemapi Hide this for inner system use.
+ * @param bundleName, name of the application.
+ * @param newGroup,the group of the application whose name is bundleName.
+ * @return Returns the result of setBundleGroup, true of false.
+ */
+ function setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback): void;
+ function setBundleGroup(bundleName: string, newGroup: GroupType): Promise;
+
+ /**
+ * register callback to service.
+ *
+ * @since 9
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO
+ * @systemapi Hide this for inner system use.
+ * @param Callback, callback when application group change,return the BundleActiveGroupCallbackInfo.
+ * @return Returns BundleActiveGroupCallbackInfo when the group of bundle changed. the result of AsyncCallback is true or false.
+ */
+ function registerGroupCallBack(callback: Callback, callback: AsyncCallback): void;
+ function registerGroupCallBack(callback: Callback): Promise;
+
+ /**
+ * unRegister callback from service.
+ *
+ * @since 9
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO
+ * @systemapi Hide this for inner system use.
+ * @return Returns the result of unRegisterGroupCallBack, true of false.
+ */
+ function unRegisterGroupCallBack(callback: AsyncCallback): void;
+ function unRegisterGroupCallBack(): Promise;
+
+ /*
+ * Queries system event states data within a specified period identified by the start and end time.
+ *
+ * @since 9
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO
+ * @systemapi Hide this for inner system use.
+ * @param begin Indicates the start time of the query period, in milliseconds.
+ * @param end Indicates the end time of the query period, in milliseconds.
+ * @return Returns the {@link BundleActiveEventState} object Array containing the event states data.
+ */
+ function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback>): void;
+ function queryBundleActiveEventStates(begin: number, end: number): Promise>;
+
+ /**
+ * Queries app notification number within a specified period identified by the start and end time.
+ *
+ * @since 9
+ * @syscap SystemCapability.ResourceSchedule.UsageStatistics.App
+ * @permission ohos.permission.BUNDLE_ACTIVE_INFO
+ * @systemapi Hide this for inner system use.
+ * @param begin Indicates the start time of the query period, in milliseconds.
+ * @param end Indicates the end time of the query period, in milliseconds.
+ * @return Returns the {@link BundleActiveEventState} object Array containing the event states data.
+ */
+ function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback>): void;
+ function queryAppNotificationNumber(begin: number, end: number): Promise>;
}
export default bundleState;
diff --git a/interfaces/kits/bundlestats/napi/include/bundle_active_group_observer.h b/interfaces/kits/bundlestats/napi/include/bundle_active_group_observer.h
new file mode 100644
index 0000000000000000000000000000000000000000..3e7cd4fa8f1b687f3ab35ef40e62d1deec1f9161
--- /dev/null
+++ b/interfaces/kits/bundlestats/napi/include/bundle_active_group_observer.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2022 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_ACTIVE_GROUP_OBSERVER_H
+#define FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_ACTIVE_GROUP_OBSERVER_H
+
+#include