1 /*
2  * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "time_service_client.h"
17 
18 #include "bundle_active_log.h"
19 #include "bundle_active_user_history.h"
20 #include "bundle_active_group_handler.h"
21 #include "ibundle_active_service.h"
22 #include "bundle_active_group_controller.h"
23 #include "bundle_active_util.h"
24 
25 namespace OHOS {
26 namespace DeviceUsageStats {
27 using namespace DeviceUsageStatsGroupConst;
28     const int32_t MAIN_APP_INDEX = 0;
BundleActiveGroupHandlerObject()29 BundleActiveGroupHandlerObject::BundleActiveGroupHandlerObject()
30 {
31         bundleName_ = "";
32         userId_ = -1;
33         uid_ = -1;
34 }
35 
36 
BundleActiveGroupController(const bool debug)37 BundleActiveGroupController::BundleActiveGroupController(const bool debug)
38 {
39     timeoutForDirectlyUse_ = debug ? THREE_MINUTE : ONE_HOUR;
40     timeoutForNotifySeen_ = debug ? ONE_MINUTE : TWELVE_HOUR;
41     timeoutForSystemInteraction_ = debug ? ONE_MINUTE : TEN_MINUTE;
42     screenTimeLevel_ = {0, 0, debug ? TWO_MINUTE : ONE_HOUR, debug ? FOUR_MINUTE : TWO_HOUR};
43     bootTimeLevel_ = {0, debug ? TWO_MINUTE : TWELVE_HOUR, debug ? FOUR_MINUTE : TWENTY_FOUR_HOUR,
44         debug ? SIXTEEN_MINUTE : FOURTY_EIGHT_HOUR};
45     eventIdMatchReason_ = {
46         {BundleActiveEvent::ABILITY_FOREGROUND, GROUP_EVENT_REASON_FOREGROUND},
47         {BundleActiveEvent::ABILITY_BACKGROUND, GROUP_EVENT_REASON_BACKGROUND},
48         {BundleActiveEvent::SYSTEM_INTERACTIVE, GROUP_EVENT_REASON_SYSTEM},
49         {BundleActiveEvent::USER_INTERACTIVE, GROUP_EVENT_REASON_USER_INTERACTION},
50         {BundleActiveEvent::NOTIFICATION_SEEN, GROUP_EVENT_REASON_NOTIFY_SEEN},
51         {BundleActiveEvent::LONG_TIME_TASK_STARTTED, GROUP_EVENT_REASON_LONG_TIME_TASK_STARTTED},
52     };
53 }
54 
RestoreDurationToDatabase()55 void BundleActiveGroupController::RestoreDurationToDatabase()
56 {
57     std::lock_guard<ffrt::mutex> lock(mutex_);
58     bundleUserHistory_->WriteDeviceDuration();
59 }
60 
RestoreToDatabase(const int32_t userId)61 void BundleActiveGroupController::RestoreToDatabase(const int32_t userId)
62 {
63     std::lock_guard<ffrt::mutex> lock(mutex_);
64     bundleUserHistory_->WriteBundleUsage(userId);
65 }
66 
OnUserRemoved(const int32_t userId)67 void BundleActiveGroupController::OnUserRemoved(const int32_t userId)
68 {
69     std::lock_guard<ffrt::mutex> lock(mutex_);
70     bundleUserHistory_->userHistory_.erase(userId);
71     if (!activeGroupHandler_.expired()) {
72         activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE);
73     }
74 }
75 
OnUserSwitched(const int32_t userId, const int32_t currentUsedUser)76 void BundleActiveGroupController::OnUserSwitched(const int32_t userId, const int32_t currentUsedUser)
77 {
78     BUNDLE_ACTIVE_LOGI("last time check for user %{public}d", currentUsedUser);
79     CheckEachBundleState(currentUsedUser);
80     bundleUserHistory_->WriteBundleUsage(currentUsedUser);
81     std::lock_guard<ffrt::mutex> lock(mutex_);
82     auto activeGroupHandler = activeGroupHandler_.lock();
83     if (!activeGroupHandler_.expired()) {
84         activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_IDLE_STATE);
85         activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_DEFAULT_BUNDLE_STATE);
86         activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_NOTIFICATION_SEEN_BUNDLE_STATE);
87         activeGroupHandler_.lock()->RemoveEvent(BundleActiveGroupHandler::MSG_CHECK_SYSTEM_INTERACTIVE_BUNDLE_STATE);
88     }
89     PeriodCheckBundleState(userId);
90 }
91 
OnScreenChanged(const bool& isScreenOn, const int64_t bootFromTimeStamp)92 void BundleActiveGroupController::OnScreenChanged(const bool& isScreenOn, const int64_t bootFromTimeStamp)
93 {
94     if (!activeGroupHandler_.expired()) {
95         std::shared_ptr<BundleActiveGroupController> bundleActiveGroupController = shared_from_this();
96         activeGroupHandler_.lock()->PostTask([bundleActiveGroupController, isScreenOn, bootFromTimeStamp]() {
97             std::lock_guard<ffrt::mutex> lock(bundleActiveGroupController->mutex_);
98             bundleActiveGroupController->bundleUserHistory_->UpdateBootBasedAndScreenTime(isScreenOn,
99                 bootFromTimeStamp);
100         });
101     }
102 }
103 
SetHandlerAndCreateUserHistory( const std::shared_ptr<BundleActiveGroupHandler>& groupHandler, const int64_t bootFromTimeStamp, const std::shared_ptr<BundleActiveCore>& bundleActiveCore)104 void BundleActiveGroupController::SetHandlerAndCreateUserHistory(
105     const std::shared_ptr<BundleActiveGroupHandler>& groupHandler, const int64_t bootFromTimeStamp,
106     const std::shared_ptr<BundleActiveCore>& bundleActiveCore)
107 {
108     if (bundleUserHistory_ == nullptr) {
109         BUNDLE_ACTIVE_LOGI("SetHandlerAndCreateUserHistory bundleUserHistory_ is null, "
110             "called constructor, bootstamp is %{public}lld", (long long)bootFromTimeStamp);
111         bundleUserHistory_ = std::make_shared<BundleActiveUserHistory>(bootFromTimeStamp, bundleActiveCore);
112     }
113     OnScreenChanged(IsScreenOn(), bootFromTimeStamp);
114     activeGroupHandler_ = groupHandler;
115 }
116 
OnBundleUninstalled(const int32_t userId, const std::string& bundleName, const int32_t uid, const int32_t appIndex)117 void BundleActiveGroupController::OnBundleUninstalled(const int32_t userId, const std::string& bundleName,
118     const int32_t uid, const int32_t appIndex)
119 {
120     std::lock_guard<ffrt::mutex> lock(mutex_);
121     BUNDLE_ACTIVE_LOGI("OnBundleUninstalled called, userId is %{public}d, bundlename is %{public}s",
122         userId, bundleName.c_str());
123     auto oneUserHistory = bundleUserHistory_->GetUserHistory(userId, false);
124     if (oneUserHistory == nullptr) {
125         return;
126     }
127     DeleteUsageGroupCache(oneUserHistory, bundleName, uid, appIndex);
128     bundleUserHistory_->OnBundleUninstalled(userId, bundleName, uid, appIndex);
129 }
130 
DeleteUsageGroupCache( const std::shared_ptr<std::map<std::string, std::shared_ptr<BundleActivePackageHistory>>>& userHostory, const std::string& bundleName, const int32_t uid, const int32_t appIndex)131 void BundleActiveGroupController::DeleteUsageGroupCache(
132     const std::shared_ptr<std::map<std::string, std::shared_ptr<BundleActivePackageHistory>>>& userHostory,
133     const std::string& bundleName, const int32_t uid, const int32_t appIndex)
134 {
135     if (appIndex != MAIN_APP_INDEX) {
136         std::string moduleKey = BundleActiveUtil::GetBundleUsageKey(bundleName, uid);
137         userHostory->erase(moduleKey);
138     }
139     for (auto it = userHostory->begin(); it != userHostory->end();) {
140         if (it->first.find(bundleName) != std::string::npos) {
141             it = userHostory->erase(it);
142         } else {
143             it++;
144         }
145     }
146 }
147 
GetBundleMgrProxy()148 bool BundleActiveGroupController::GetBundleMgrProxy()
149 {
150     if (!sptrBundleMgr_) {
151         sptr<ISystemAbilityManager> systemAbilityManager =
152             SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
153         if (!systemAbilityManager) {
154             BUNDLE_ACTIVE_LOGE("Failed to get system ability mgr.");
155             return false;
156         }
157         sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
158         if (!remoteObject) {
159                 BUNDLE_ACTIVE_LOGE("Failed to get bundle manager service.");
160                 return false;
161         }
162         sptrBundleMgr_ = iface_cast<IBundleMgr>(remoteObject);
163         if (!sptrBundleMgr_) {
164             BUNDLE_ACTIVE_LOGE("Failed to get system bundle manager services ability, sptrBundleMgr_");
165             return false;
166         }
167         auto object = sptrBundleMgr_->AsObject();
168         if (!object) {
169             BUNDLE_ACTIVE_LOGE("Failed to get system bundle manager services ability");
170             return false;
171         }
172     }
173     return true;
174 }
175 
PeriodCheckBundleState(const int32_t userId)176 void BundleActiveGroupController::PeriodCheckBundleState(const int32_t userId)
177 {
178     BUNDLE_ACTIVE_LOGI("PeriodCheckBundleState called");
179     if (!activeGroupHandler_.expired()) {
180         BundleActiveGroupHandlerObject tmpGroupHandlerObj;
181         tmpGroupHandlerObj.userId_ = userId;
182         std::shared_ptr<BundleActiveGroupHandlerObject> handlerobjToPtr =
183             std::make_shared<BundleActiveGroupHandlerObject>(tmpGroupHandlerObj);
184         activeGroupHandler_.lock()->SendEvent(BundleActiveGroupHandler::MSG_CHECK_DEFAULT_BUNDLE_STATE,
185             handlerobjToPtr, FIVE_SECOND);
186     }
187 }
188 
CheckEachBundleState(const int32_t userId)189 bool BundleActiveGroupController::CheckEachBundleState(const int32_t userId)
190 {
191     BUNDLE_ACTIVE_LOGI("CheckEachBundleState called, userid is %{public}d", userId);
192     std::vector<ApplicationInfo> allBundlesForUser;
193     if (!GetBundleMgrProxy()) {
194         BUNDLE_ACTIVE_LOGE("CheckEachBundleState get bundle manager proxy failed!");
195         return false;
196     }
197     sptrBundleMgr_->GetApplicationInfos(flag, userId, allBundlesForUser);
198     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
199     int64_t bootBasedTimeStamp = timer->GetBootTimeMs();
200     for (auto oneBundle : allBundlesForUser) {
201         CheckAndUpdateGroup(oneBundle.bundleName, userId, oneBundle.uid, bootBasedTimeStamp);
202     }
203     return true;
204 }
205 
CheckIdleStatsOneTime()206 void BundleActiveGroupController::CheckIdleStatsOneTime()
207 {
208     BundleActiveGroupHandlerObject tmpGroupHandlerObj;
209     std::shared_ptr<BundleActiveGroupHandlerObject> handlerobjToPtr =
210         std::make_shared<BundleActiveGroupHandlerObject>(tmpGroupHandlerObj);
211     auto handlerEvent = AppExecFwk::InnerEvent::Get(
212         BundleActiveGroupHandler::MSG_ONE_TIME_CHECK_BUNDLE_STATE);
213     auto activeGroupHandler = activeGroupHandler_.lock();
214     if (!activeGroupHandler_.expired()) {
215         activeGroupHandler_.lock()->SendEvent(BundleActiveGroupHandler::MSG_ONE_TIME_CHECK_BUNDLE_STATE,
216             handlerobjToPtr);
217     }
218 }
219 
GetNewGroup(const std::string& bundleName, const int32_t userId, const int64_t bootBasedTimeStamp, const int32_t uid)220 int32_t BundleActiveGroupController::GetNewGroup(const std::string& bundleName, const int32_t userId,
221     const int64_t bootBasedTimeStamp, const int32_t uid)
222 {
223     int32_t groupIndex = bundleUserHistory_->GetLevelIndex(bundleName, userId, bootBasedTimeStamp, screenTimeLevel_,
224         bootTimeLevel_, uid);
225     if (groupIndex < 0) {
226         return -1;
227     }
228     return LEVEL_GROUP[groupIndex];
229 }
230 
calculationTimeOut( const std::shared_ptr<BundleActivePackageHistory>& oneBundleHistory, const int64_t bootBasedTimeStamp)231 bool BundleActiveGroupController::calculationTimeOut(
232     const std::shared_ptr<BundleActivePackageHistory>& oneBundleHistory, const int64_t bootBasedTimeStamp)
233 {
234     if (oneBundleHistory == nullptr) {
235         return false;
236     }
237     int64_t lastGroupCalculatedTimeStamp = oneBundleHistory->lastGroupCalculatedTimeStamp_;
238     return lastGroupCalculatedTimeStamp > 0 && bundleUserHistory_->GetBootBasedTimeStamp(bootBasedTimeStamp)
239         - lastGroupCalculatedTimeStamp > timeoutCalculated_;
240 }
241 
ReportEvent(const BundleActiveEvent& event, const int64_t bootBasedTimeStamp, const int32_t userId)242 void BundleActiveGroupController::ReportEvent(const BundleActiveEvent& event, const int64_t bootBasedTimeStamp,
243     const int32_t userId)
244 {
245     if (bundleGroupEnable_ == false) {
246         return;
247     }
248     std::lock_guard<ffrt::mutex> lock(mutex_);
249     if (IsBundleInstalled(event.bundleName_, userId) == false) {
250         BUNDLE_ACTIVE_LOGE("Report an uninstalled package event, return!");
251         return;
252     }
253     int32_t eventId = event.eventId_;
254     auto item  = eventIdMatchReason_.find(eventId);
255     if (item != eventIdMatchReason_.end()) {
256         std::shared_ptr<BundleActivePackageHistory> bundleUsageHistory = bundleUserHistory_->GetUsageHistoryForBundle(
257             event.bundleName_, userId, bootBasedTimeStamp, true, event.uid_);
258         if (bundleUsageHistory == nullptr) {
259             return;
260         }
261         int64_t timeUntilNextCheck;
262         uint32_t eventReason = item->second;
263         int32_t checkBundleMsgEventId = BundleActiveGroupHandler::MSG_CHECK_DEFAULT_BUNDLE_STATE;
264         switch (eventId) {
265             case BundleActiveEvent::NOTIFICATION_SEEN:
266                 bundleUserHistory_->ReportUsage(bundleUsageHistory, event.bundleName_, ACTIVE_GROUP_DAILY,
267                     eventReason, 0, bootBasedTimeStamp + timeoutForNotifySeen_, userId, event.uid_);
268                 timeUntilNextCheck = timeoutForNotifySeen_;
269                 checkBundleMsgEventId = BundleActiveGroupHandler::MSG_CHECK_NOTIFICATION_SEEN_BUNDLE_STATE;
270                 break;
271             case BundleActiveEvent::SYSTEM_INTERACTIVE:
272                 bundleUserHistory_->ReportUsage(bundleUsageHistory, event.bundleName_, ACTIVE_GROUP_ALIVE,
273                     eventReason, 0, bootBasedTimeStamp + timeoutForSystemInteraction_, userId, event.uid_);
274                 timeUntilNextCheck = timeoutForSystemInteraction_;
275                 checkBundleMsgEventId = BundleActiveGroupHandler::MSG_CHECK_SYSTEM_INTERACTIVE_BUNDLE_STATE;
276                 break;
277             default:
278                 bundleUserHistory_->ReportUsage(bundleUsageHistory, event.bundleName_, ACTIVE_GROUP_ALIVE,
279                     eventReason, bootBasedTimeStamp, bootBasedTimeStamp + timeoutForDirectlyUse_, userId, event.uid_);
280                 timeUntilNextCheck = timeoutForDirectlyUse_;
281                 break;
282         }
283         SendCheckBundleMsg(event, userId, timeUntilNextCheck, checkBundleMsgEventId);
284     }
285 }
286 
SendCheckBundleMsg(const BundleActiveEvent& event, const int32_t& userId, const int64_t& timeUntilNextCheck, const int64_t& checkBundleMsgEventId)287 void BundleActiveGroupController::SendCheckBundleMsg(const BundleActiveEvent& event, const int32_t& userId,
288     const int64_t& timeUntilNextCheck, const int64_t& checkBundleMsgEventId)
289 {
290     BundleActiveGroupHandlerObject tmpGroupHandlerObj;
291     tmpGroupHandlerObj.userId_ = userId;
292     tmpGroupHandlerObj.bundleName_ = event.bundleName_;
293     tmpGroupHandlerObj.uid_ = event.uid_;
294     std::shared_ptr<BundleActiveGroupHandlerObject> handlerobjToPtr =
295         std::make_shared<BundleActiveGroupHandlerObject>(tmpGroupHandlerObj);
296     if (!activeGroupHandler_.expired()) {
297         activeGroupHandler_.lock()->SendCheckBundleMsg(checkBundleMsgEventId, handlerobjToPtr, timeUntilNextCheck);
298     }
299 }
300 
CheckAndUpdateGroup(const std::string& bundleName, const int32_t userId, const int32_t uid, const int64_t bootBasedTimeStamp)301 void BundleActiveGroupController::CheckAndUpdateGroup(const std::string& bundleName, const int32_t userId,
302     const int32_t uid, const int64_t bootBasedTimeStamp)
303 {
304     std::lock_guard<ffrt::mutex> lock(mutex_);
305     auto oneBundleHistory = bundleUserHistory_->GetUsageHistoryForBundle(bundleName, userId,
306         bootBasedTimeStamp, true, uid);
307     if (oneBundleHistory == nullptr) {
308         return;
309     }
310     uint32_t groupReason = oneBundleHistory->reasonInGroup_;
311     uint32_t oldGroupControlReason = groupReason & GROUP_CONTROL_REASON_MASK;
312     if (oldGroupControlReason == GROUP_CONTROL_REASON_FORCED) {
313         BUNDLE_ACTIVE_LOGI("%{public}s is forced set, return", bundleName.c_str());
314         return;
315     }
316     int32_t oldGroup = oneBundleHistory->currentGroup_;
317     int32_t newGroup = std::max(oldGroup, ACTIVE_GROUP_ALIVE);
318     if (oldGroupControlReason == GROUP_CONTROL_REASON_DEFAULT ||
319         oldGroupControlReason == GROUP_CONTROL_REASON_USAGE ||
320         oldGroupControlReason == GROUP_CONTROL_REASON_TIMEOUT) {
321         newGroup = GetNewGroup(bundleName, userId, bootBasedTimeStamp, uid);
322         if (newGroup < 0) {
323             return;
324         }
325         groupReason = GROUP_CONTROL_REASON_TIMEOUT;
326     }
327     int64_t bootBasedTimeStampAdjusted = bundleUserHistory_->GetBootBasedTimeStamp(bootBasedTimeStamp);
328     bool notTimeout = false;
329     if (newGroup >= ACTIVE_GROUP_ALIVE && oneBundleHistory->bundleAliveTimeoutTimeStamp_ >
330         bootBasedTimeStampAdjusted) {
331         newGroup = ACTIVE_GROUP_ALIVE;
332         groupReason = GROUP_CONTROL_REASON_USAGE | GROUP_EVENT_REASON_ALIVE_NOT_TIMEOUT;
333         notTimeout = true;
334     } else if (newGroup >= ACTIVE_GROUP_DAILY && oneBundleHistory->bundleDailyTimeoutTimeStamp_ >
335         bootBasedTimeStampAdjusted) {
336         newGroup = ACTIVE_GROUP_DAILY;
337         groupReason = GROUP_CONTROL_REASON_USAGE | GROUP_EVENT_REASON_ALIVE_TIMEOUT;
338         notTimeout = true;
339     }
340     if (oldGroup < newGroup || notTimeout) {
341         BUNDLE_ACTIVE_LOGI("CheckAndUpdateGroup called SetAppGroup");
342         bundleUserHistory_->SetAppGroup(bundleName, userId, bootBasedTimeStamp, newGroup,
343             groupReason, false, uid);
344     }
345 }
346 
SetAppGroup(const std::string& bundleName, const int32_t userId, int32_t newGroup, uint32_t reason, const int64_t bootBasedTimeStamp, const bool isFlush)347 ErrCode BundleActiveGroupController::SetAppGroup(const std::string& bundleName, const int32_t userId,
348     int32_t newGroup, uint32_t reason, const int64_t bootBasedTimeStamp, const bool isFlush)
349 {
350     std::lock_guard<ffrt::mutex> lock(mutex_);
351     if (!IsBundleInstalled(bundleName, userId)) {
352         return ERR_NO_APP_GROUP_INFO_IN_DATABASE;
353     }
354     auto iter = bundleUserHistory_->userHistory_.find(userId);
355     if (iter == bundleUserHistory_->userHistory_.end()) {
356         return ERR_NO_APP_GROUP_INFO_IN_DATABASE;
357     }
358     auto packageHistoryMap = iter->second;
359     int32_t result = 0;
360     int32_t tempResult = 0;
361     for (auto packageHistoryIter : *packageHistoryMap) {
362         if (packageHistoryIter.first.find(bundleName) == std::string::npos || packageHistoryIter.second == nullptr) {
363             continue;
364         }
365         auto oneBundleHistory = bundleUserHistory_->GetUsageHistoryForBundle(bundleName,
366             userId, bootBasedTimeStamp, true, packageHistoryIter.second->uid_);
367         if (!oneBundleHistory) {
368             continue;
369         }
370         tempResult = bundleUserHistory_->SetAppGroup(bundleName, userId,
371             packageHistoryIter.second->uid_, bootBasedTimeStamp, newGroup, reason, isFlush);
372         if (tempResult != ERR_OK) {
373             result = tempResult;
374         }
375     }
376     return result;
377 }
378 
IsBundleIdle(const std::string& bundleName, const int32_t userId)379 int32_t BundleActiveGroupController::IsBundleIdle(const std::string& bundleName, const int32_t userId)
380 {
381     std::lock_guard<ffrt::mutex> lock(mutex_);
382     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
383     if (IsBundleInstalled(bundleName, userId) == false) {
384         return -1;
385     }
386     int64_t bootBasedTimeStamp = timer->GetBootTimeMs();
387     auto iter = bundleUserHistory_->userHistory_.find(userId);
388     if (iter == bundleUserHistory_->userHistory_.end()) {
389         return -1;
390     }
391     auto packageHistoryMap = iter->second;
392     int32_t IsBundleIdle = 1;
393     for (auto packageHistoryIter : *packageHistoryMap) {
394         if (packageHistoryIter.first.find(bundleName) == std::string::npos || packageHistoryIter.second == nullptr) {
395             continue;
396         }
397         auto oneBundleHistory = bundleUserHistory_->GetUsageHistoryForBundle(bundleName,
398             userId, bootBasedTimeStamp, false, packageHistoryIter.second->uid_);
399         if (!oneBundleHistory) {
400             continue;
401         }
402         if (oneBundleHistory->currentGroup_ <= ACTIVE_GROUP_RARE) {
403             IsBundleIdle = 0;
404         }
405     }
406     return IsBundleIdle;
407 }
408 
QueryAppGroup(int32_t& appGroup, const std::string& bundleName, const int32_t userId)409 ErrCode BundleActiveGroupController::QueryAppGroup(int32_t& appGroup,
410     const std::string& bundleName, const int32_t userId)
411 {
412     std::lock_guard<ffrt::mutex> lock(mutex_);
413     if (bundleName.empty()) {
414         BUNDLE_ACTIVE_LOGE("bundleName can not get by userId");
415         return ERR_NO_APP_GROUP_INFO_IN_DATABASE;
416     }
417     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
418     if (!IsBundleInstalled(bundleName, userId)) {
419         BUNDLE_ACTIVE_LOGI("QueryAppGroup is not bundleInstalled");
420         return ERR_APPLICATION_IS_NOT_INSTALLED;
421     }
422     int64_t bootBasedTimeStamp = timer->GetBootTimeMs();
423     auto iter = bundleUserHistory_->userHistory_.find(userId);
424     if (iter == bundleUserHistory_->userHistory_.end()) {
425         return ERR_NO_APP_GROUP_INFO_IN_DATABASE;
426     }
427     appGroup = ACTIVE_GROUP_NEVER;
428     auto packageHistoryMap = iter->second;
429     for (auto packageHistoryIter : *packageHistoryMap) {
430         if (packageHistoryIter.first.find(bundleName) == std::string::npos || packageHistoryIter.second == nullptr) {
431             continue;
432         }
433         auto oneBundleHistory = bundleUserHistory_->GetUsageHistoryForBundle(bundleName,
434             userId, bootBasedTimeStamp, false, packageHistoryIter.second->uid_);
435         if (!oneBundleHistory) {
436             continue;
437         }
438         BUNDLE_ACTIVE_LOGI("QueryAppGroup group is %{public}d", oneBundleHistory->currentGroup_);
439         appGroup = std::min(oneBundleHistory->currentGroup_, appGroup);
440     }
441     return ERR_OK;
442 }
443 
IsBundleInstalled(const std::string& bundleName, const int32_t userId)444 bool BundleActiveGroupController::IsBundleInstalled(const std::string& bundleName, const int32_t userId)
445 {
446     ApplicationInfo bundleInfo;
447     if (!sptrBundleMgr_) {
448         return false;
449     }
450     bool getInfoIsSuccess = sptrBundleMgr_->GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO,
451         userId, bundleInfo);
452     if (getInfoIsSuccess == false) {
453         BUNDLE_ACTIVE_LOGE("IsBundleInstalled bundle is not installed!");
454         return false;
455     }
456     return true;
457 }
458 
ShutDown(const int64_t bootBasedTimeStamp, const int32_t userId)459 void BundleActiveGroupController::ShutDown(const int64_t bootBasedTimeStamp, const int32_t userId)
460 {
461     BUNDLE_ACTIVE_LOGI("ShutDown called");
462     CheckEachBundleState(userId);
463     bundleUserHistory_->UpdateBootBasedAndScreenTime(false, bootBasedTimeStamp, true);
464 }
465 
IsScreenOn()466 bool BundleActiveGroupController::IsScreenOn()
467 {
468     bool result = true;
469 #ifdef DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE
470     result = PowerMgrClient::GetInstance().IsScreenOn();
471 #endif
472     BUNDLE_ACTIVE_LOGI("IsScreenOn() is %{public}d", result);
473     return result;
474 }
475 }  // namespace DeviceUsageStats
476 }  // namespace OHOS
477 
478