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 #include "bundle_active_core.h"
16 #include "accesstoken_kit.h"
17 #include "time_service_client.h"
18
19 #include "bundle_active_log.h"
20 #include "bundle_active_event.h"
21 #include "bundle_active_event_stats.h"
22 #include "bundle_active_report_handler.h"
23 #include "bundle_active_group_common.h"
24 #include "bundle_active_bundle_mgr_helper.h"
25 #include "bundle_active_constant.h"
26 #include "bundle_active_util.h"
27 #include "ffrt_inner.h"
28 #include "bundle_constants.h"
29
30
31 namespace OHOS {
32 namespace DeviceUsageStats {
33 #ifndef OS_ACCOUNT_PART_ENABLED
34 const int32_t DEFAULT_OS_ACCOUNT_ID = 0; // 0 is the default id when there is no os_account part
35 #endif // OS_ACCOUNT_PART_ENABLED
36 constexpr int32_t BUNDLE_UNINSTALL_DELAY_TIME = 5 * 1000 * 1000;
37
BundleActiveReportHandlerObject()38 BundleActiveReportHandlerObject::BundleActiveReportHandlerObject()
39 {
40 userId_ = -1;
41 bundleName_ = "";
42 }
43
BundleActiveReportHandlerObject(const int32_t userId,const std::string bundleName)44 BundleActiveReportHandlerObject::BundleActiveReportHandlerObject(const int32_t userId, const std::string bundleName)
45 {
46 userId_ = userId;
47 bundleName_ = bundleName;
48 }
49
BundleActiveReportHandlerObject(const BundleActiveReportHandlerObject & orig)50 BundleActiveReportHandlerObject::BundleActiveReportHandlerObject(const BundleActiveReportHandlerObject& orig)
51 {
52 event_ = orig.event_;
53 userId_ = orig.userId_;
54 bundleName_ = orig.bundleName_;
55 uid_ = orig.uid_;
56 appIndex_ = orig.appIndex_;
57 }
58
BundleActiveCore()59 BundleActiveCore::BundleActiveCore()
60 {
61 systemTimeShot_ = -1;
62 realTimeShot_ = -1;
63 currentUsedUser_ = -1;
64 if (DEBUG_ON) {
65 flushInterval_ = TWO_MINUTE;
66 debugCore_ = true;
67 } else {
68 flushInterval_ = THIRTY_MINUTE;
69 debugCore_ = false;
70 }
71 }
72
~BundleActiveCore()73 BundleActiveCore::~BundleActiveCore()
74 {
75 }
76
OnReceiveEvent(const CommonEventData & data)77 void BundleActiveCommonEventSubscriber::OnReceiveEvent(const CommonEventData &data)
78 {
79 std::lock_guard<ffrt::mutex> lock(mutex_);
80 std::string action = data.GetWant().GetAction();
81 if (action == CommonEventSupport::COMMON_EVENT_SCREEN_OFF ||
82 action == CommonEventSupport::COMMON_EVENT_SCREEN_ON) {
83 HandleScreenEvent();
84 } else if (action == CommonEventSupport::COMMON_EVENT_USER_REMOVED) {
85 HandleUserRemoveEvent(data);
86 } else if (action == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
87 HandleUserSwitchEvent(data);
88 } else if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED ||
89 action == CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED) {
90 HandlePackageRemoveEvent(data);
91 } else if (action == COMMON_EVENT_UNLOCK_SCREEN || action == COMMON_EVENT_LOCK_SCREEN) {
92 HandleLockEvent(data);
93 } else if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED) {
94 HandlePackageAddEvent(data);
95 }
96 }
97
HandleScreenEvent()98 void BundleActiveCommonEventSubscriber::HandleScreenEvent()
99 {
100 if (!bundleActiveReportHandler_.expired()) {
101 sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
102 auto groupController = activeGroupController_.lock();
103 if (groupController == nullptr) {
104 return;
105 }
106 bool isScreenOn = groupController->IsScreenOn();
107 BUNDLE_ACTIVE_LOGI("screen state change to %{public}d", isScreenOn);
108 groupController->OnScreenChanged(isScreenOn, timer->GetBootTimeMs());
109 }
110 }
111
HandleUserRemoveEvent(const CommonEventData & data)112 void BundleActiveCommonEventSubscriber::HandleUserRemoveEvent(const CommonEventData &data)
113 {
114 if (!bundleActiveReportHandler_.expired()) {
115 int32_t userId = data.GetCode();
116 BUNDLE_ACTIVE_LOGI("remove user id %{public}d", userId);
117 BundleActiveReportHandlerObject tmpHandlerObject(userId, "");
118 std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
119 std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
120 auto reportHandler = bundleActiveReportHandler_.lock();
121 if (reportHandler == nullptr) {
122 return;
123 }
124 reportHandler->SendEvent(BundleActiveReportHandler::MSG_REMOVE_USER, handlerobjToPtr);
125 }
126 }
127
HandleUserSwitchEvent(const CommonEventData & data)128 void BundleActiveCommonEventSubscriber::HandleUserSwitchEvent(const CommonEventData &data)
129 {
130 if (!bundleActiveReportHandler_.expired()) {
131 int32_t userId = data.GetCode();
132 BUNDLE_ACTIVE_LOGI("OnReceiveEvent receive switched user event, user id is %{public}d", userId);
133 BundleActiveReportHandlerObject tmpHandlerObject(userId, "");
134 std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
135 std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
136 auto reportHandler = bundleActiveReportHandler_.lock();
137 if (reportHandler == nullptr) {
138 return;
139 }
140 reportHandler->SendEvent(BundleActiveReportHandler::MSG_SWITCH_USER, handlerobjToPtr);
141 }
142 }
143
HandlePackageRemoveEvent(const CommonEventData & data)144 void BundleActiveCommonEventSubscriber::HandlePackageRemoveEvent(const CommonEventData &data)
145 {
146 std::string action = data.GetWant().GetAction();
147 int32_t userId = data.GetWant().GetIntParam("userId", 0);
148 std::string bundleName = data.GetWant().GetElement().GetBundleName();
149 BUNDLE_ACTIVE_LOGI("action is %{public}s, userID is %{public}d, bundlename is %{public}s",
150 action.c_str(), userId, bundleName.c_str());
151 if (!bundleActiveReportHandler_.expired()) {
152 BundleActiveReportHandlerObject tmpHandlerObject(userId, bundleName);
153 tmpHandlerObject.uid_ = data.GetWant().GetIntParam("uid", -1);
154 tmpHandlerObject.appIndex_ = data.GetWant().GetIntParam("appIndex", -1);
155 std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
156 std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
157 auto reportHandler = bundleActiveReportHandler_.lock();
158 if (reportHandler == nullptr) {
159 return;
160 }
161 reportHandler->SendEvent(BundleActiveReportHandler::MSG_BUNDLE_UNINSTALLED,
162 handlerobjToPtr);
163 }
164 }
165
HandlePackageAddEvent(const CommonEventData & data)166 void BundleActiveCommonEventSubscriber::HandlePackageAddEvent(const CommonEventData &data)
167 {
168 std::string action = data.GetWant().GetAction();
169 int32_t userId = data.GetWant().GetIntParam("userId", 0);
170 std::string bundleName = data.GetWant().GetElement().GetBundleName();
171 BUNDLE_ACTIVE_LOGI("action is %{public}s, userID is %{public}d, bundlename is %{public}s",
172 action.c_str(), userId, bundleName.c_str());
173 if (!bundleActiveReportHandler_.expired()) {
174 BundleActiveReportHandlerObject tmpHandlerObject(userId, bundleName);
175 tmpHandlerObject.uid_ = data.GetWant().GetIntParam("uid", -1);
176 tmpHandlerObject.appIndex_ = data.GetWant().GetIntParam("appIndex", -1);
177 std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
178 std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
179 auto reportHandler = bundleActiveReportHandler_.lock();
180 if (reportHandler == nullptr) {
181 return;
182 }
183 reportHandler->SendEvent(BundleActiveReportHandler::MSG_BUNDLE_INSTALLED,
184 handlerobjToPtr);
185 }
186 }
187
HandleLockEvent(const CommonEventData & data)188 void BundleActiveCommonEventSubscriber::HandleLockEvent(const CommonEventData &data)
189 {
190 std::string action = data.GetWant().GetAction();
191 int32_t userId = data.GetWant().GetIntParam("userId", 0);
192 BUNDLE_ACTIVE_LOGI("action is %{public}s, userID is %{public}d", action.c_str(), userId);
193 if (bundleActiveReportHandler_.expired()) {
194 return;
195 }
196 BundleActiveReportHandlerObject tmpHandlerObject(-1, "");
197 BundleActiveEvent newEvent;
198 tmpHandlerObject.event_ = newEvent;
199 if (action == COMMON_EVENT_UNLOCK_SCREEN) {
200 tmpHandlerObject.event_.eventId_ = BundleActiveEvent::SYSTEM_UNLOCK;
201 } else {
202 tmpHandlerObject.event_.eventId_ = BundleActiveEvent::SYSTEM_LOCK;
203 }
204 tmpHandlerObject.userId_ = userId;
205 sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
206 tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs();
207 auto handlerobjToPtr = std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
208 bundleActiveReportHandler_.lock()->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr);
209 }
210
RegisterSubscriber()211 void BundleActiveCore::RegisterSubscriber()
212 {
213 MatchingSkills matchingSkills;
214 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_OFF);
215 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_ON);
216 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED);
217 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
218 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
219 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED);
220 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED);
221 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED);
222 CommonEventSubscribeInfo subscriberInfo(matchingSkills);
223 commonEventSubscriber_ = std::make_shared<BundleActiveCommonEventSubscriber>(subscriberInfo,
224 bundleGroupController_, handler_);
225 bool subscribeResult = CommonEventManager::SubscribeCommonEvent(commonEventSubscriber_);
226 SubscriberLockScreenCommonEvent();
227 BUNDLE_ACTIVE_LOGD("Register for events result is %{public}d", subscribeResult);
228 }
229
SubscriberLockScreenCommonEvent()230 void BundleActiveCore::SubscriberLockScreenCommonEvent()
231 {
232 MatchingSkills matchingSkills;
233 matchingSkills.AddEvent(COMMON_EVENT_UNLOCK_SCREEN);
234 matchingSkills.AddEvent(COMMON_EVENT_LOCK_SCREEN);
235 CommonEventSubscribeInfo subscriberInfo(matchingSkills);
236 subscriberInfo.SetPublisherBundleName(AppExecFwk::Constants::SCENE_BOARD_BUNDLE_NAME);
237 lockScreenSubscriber_ = std::make_shared<BundleActiveCommonEventSubscriber>(subscriberInfo,
238 bundleGroupController_, handler_);
239 CommonEventManager::SubscribeCommonEvent(lockScreenSubscriber_);
240 }
241
UnRegisterSubscriber()242 void BundleActiveCore::UnRegisterSubscriber()
243 {
244 CommonEventManager::UnSubscribeCommonEvent(commonEventSubscriber_);
245 CommonEventManager::UnSubscribeCommonEvent(lockScreenSubscriber_);
246 }
247
Init()248 void BundleActiveCore::Init()
249 {
250 sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
251 do {
252 realTimeShot_ = timer->GetBootTimeMs();
253 systemTimeShot_ = GetSystemTimeMs();
254 } while (realTimeShot_ == -1 && systemTimeShot_ == -1);
255 realTimeShot_ = timer->GetBootTimeMs();
256 systemTimeShot_ = GetSystemTimeMs();
257 bundleGroupController_ = std::make_shared<BundleActiveGroupController>(debugCore_);
258 BUNDLE_ACTIVE_LOGD("system time shot is %{public}lld", (long long)systemTimeShot_);
259 bundleActiveConfigReader_ = std::make_shared<BundleActiveConfigReader>();
260 bundleActiveConfigReader_->LoadConfig();
261 }
262
InitBundleGroupController()263 void BundleActiveCore::InitBundleGroupController()
264 {
265 BUNDLE_ACTIVE_LOGD("InitBundleGroupController called");
266 bundleGroupHandler_ = std::make_shared<BundleActiveGroupHandler>(debugCore_);
267 if (bundleGroupHandler_ == nullptr) {
268 return;
269 }
270 if (bundleGroupController_ != nullptr) {
271 bundleGroupHandler_->Init(bundleGroupController_);
272 bundleGroupController_->SetHandlerAndCreateUserHistory(bundleGroupHandler_, realTimeShot_, shared_from_this());
273 BUNDLE_ACTIVE_LOGI("Init Set group controller and handler done");
274 } else {
275 return;
276 }
277 RegisterSubscriber();
278 std::vector<int32_t> activatedOsAccountIds;
279 bundleGroupController_->bundleGroupEnable_ = true;
280 GetAllActiveUser(activatedOsAccountIds);
281 if (activatedOsAccountIds.size() == 0) {
282 BUNDLE_ACTIVE_LOGI("query activated account failed, no account activated");
283 return;
284 }
285 for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) {
286 bundleGroupController_->PeriodCheckBundleState(activatedOsAccountIds[i]);
287 }
288 }
289
SetHandler(const std::shared_ptr<BundleActiveReportHandler> & reportHandler)290 void BundleActiveCore::SetHandler(const std::shared_ptr<BundleActiveReportHandler>& reportHandler)
291 {
292 handler_ = reportHandler;
293 }
294
GetUserDataAndInitializeIfNeeded(const int32_t userId,const int64_t timeStamp,const bool debug)295 std::shared_ptr<BundleActiveUserService> WEAK_FUNC BundleActiveCore::GetUserDataAndInitializeIfNeeded(
296 const int32_t userId, const int64_t timeStamp, const bool debug)
297 {
298 BUNDLE_ACTIVE_LOGD("GetUserDataAndInitializeIfNeeded called");
299 std::map<int, std::shared_ptr<BundleActiveUserService>>::iterator it = userStatServices_.find(userId);
300 if (it == userStatServices_.end()) {
301 BUNDLE_ACTIVE_LOGI("first initialize user service");
302 std::shared_ptr<BundleActiveUserService> service = std::make_shared<BundleActiveUserService>(userId, *this,
303 debug);
304 service->Init(timeStamp);
305 userStatServices_[userId] = service;
306 BUNDLE_ACTIVE_LOGI("service is not null");
307 return service;
308 }
309 return it->second;
310 }
311
OnBundleUninstalled(const int32_t userId,const std::string & bundleName,const int32_t uid,const int32_t appIndex)312 void BundleActiveCore::OnBundleUninstalled(const int32_t userId, const std::string& bundleName,
313 const int32_t uid, const int32_t appIndex)
314 {
315 BUNDLE_ACTIVE_LOGD("OnBundleUninstalled CALLED");
316 std::lock_guard<ffrt::mutex> lock(mutex_);
317 int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
318 if (timeNow == ERR_TIME_OPERATION_FAILED) {
319 return;
320 }
321 auto service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
322 if (service == nullptr) {
323 return;
324 }
325 AddbundleUninstalledUid(uid);
326 DelayRemoveBundleUninstalledUid(uid);
327 service->DeleteUninstalledBundleStats(bundleName, uid, appIndex);
328 bundleGroupController_->OnBundleUninstalled(userId, bundleName, uid, appIndex);
329 }
330
OnBundleInstalled(const int32_t userId,const std::string & bundleName,const int32_t uid,const int32_t appIndex)331 void BundleActiveCore::OnBundleInstalled(const int32_t userId, const std::string& bundleName,
332 const int32_t uid, const int32_t appIndex)
333 {
334 BUNDLE_ACTIVE_LOGD("OnBundleInstalled CALLED");
335 std::lock_guard<ffrt::mutex> lock(bundleUninstalledMutex_);
336 if (bundleUninstalledSet_.find(uid) == bundleUninstalledSet_.end()) {
337 return;
338 }
339 bundleUninstalledSet_.erase(uid);
340 if (taskMap_.find(uid) == taskMap_.end()) {
341 return;
342 }
343 ffrt::skip(taskMap_[uid]);
344 taskMap_.erase(uid);
345 }
346
AddbundleUninstalledUid(const int32_t uid)347 void BundleActiveCore::AddbundleUninstalledUid(const int32_t uid)
348 {
349 std::lock_guard<ffrt::mutex> lock(bundleUninstalledMutex_);
350 bundleUninstalledSet_.insert(uid);
351 }
352
DelayRemoveBundleUninstalledUid(const int32_t uid)353 void BundleActiveCore::DelayRemoveBundleUninstalledUid(const int32_t uid)
354 {
355 auto bundleActiveCore = shared_from_this();
356 auto task = ffrt::submit_h([bundleActiveCore, uid]() {
357 std::lock_guard<ffrt::mutex> lock(bundleActiveCore->bundleUninstalledMutex_);
358 bundleActiveCore->bundleUninstalledSet_.erase(uid);
359 if (bundleActiveCore->taskMap_.find(uid) == bundleActiveCore->taskMap_.end()) {
360 return;
361 }
362 bundleActiveCore->taskMap_.erase(uid);
363 }, {}, {}, ffrt::task_attr().delay(BUNDLE_UNINSTALL_DELAY_TIME));
364 taskMap_[uid] = std::move(task);
365 }
366
isUninstalledApp(const int32_t uid)367 bool BundleActiveCore::isUninstalledApp(const int32_t uid)
368 {
369 std::lock_guard<ffrt::mutex> lock(bundleUninstalledMutex_);
370 if (bundleUninstalledSet_.find(uid) != bundleUninstalledSet_.end()) {
371 return true;
372 }
373 return false;
374 }
375
OnStatsChanged(const int32_t userId)376 void BundleActiveCore::OnStatsChanged(const int32_t userId)
377 {
378 if (!handler_.expired()) {
379 BundleActiveReportHandlerObject tmpHandlerObject;
380 tmpHandlerObject.userId_ = userId;
381 std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
382 std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
383 if (handler_.lock()->HasEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK) == false) {
384 BUNDLE_ACTIVE_LOGI("OnStatsChanged send flush to disk event for user %{public}d", userId);
385 handler_.lock()->SendEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK, handlerobjToPtr, flushInterval_);
386 }
387 }
388 }
389
RestoreAllData()390 void BundleActiveCore::RestoreAllData()
391 {
392 for (const auto& it : userStatServices_) {
393 std::shared_ptr<BundleActiveUserService> service = it.second;
394 if (service == nullptr) {
395 BUNDLE_ACTIVE_LOGI("service in BundleActiveCore::RestoreToDatabaseLocked() is null");
396 return;
397 }
398 BUNDLE_ACTIVE_LOGI("userid is %{public}d ", service->userId_);
399 service->RestoreStats(true);
400 if (bundleGroupController_ != nullptr && bundleGroupController_->bundleUserHistory_ != nullptr) {
401 bundleGroupController_->RestoreToDatabase(it.first);
402 }
403 }
404 if (bundleGroupController_ != nullptr) {
405 bundleGroupController_->RestoreDurationToDatabase();
406 }
407 if (!handler_.expired()) {
408 BUNDLE_ACTIVE_LOGI("RestoreAllData remove flush to disk event");
409 handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK);
410 }
411 }
412
RestoreToDatabase(const int32_t userId)413 void BundleActiveCore::RestoreToDatabase(const int32_t userId)
414 {
415 BUNDLE_ACTIVE_LOGD("RestoreToDatabase called");
416 BundleActiveEvent event;
417 event.eventId_ = BundleActiveEvent::FLUSH;
418 event.timeStamp_ = GetSystemTimeMs();
419 event.abilityId_ = "";
420 auto it = userStatServices_.find(userId);
421 if (it != userStatServices_.end()) {
422 it->second->ReportEvent(event);
423 }
424 RestoreToDatabaseLocked(userId);
425 }
426
RestoreToDatabaseLocked(const int32_t userId)427 void BundleActiveCore::RestoreToDatabaseLocked(const int32_t userId)
428 {
429 BUNDLE_ACTIVE_LOGD("RestoreToDatabaseLocked called");
430 auto it = userStatServices_.find(userId);
431 if (it != userStatServices_.end()) {
432 it->second->RestoreStats(false);
433 }
434 if (bundleGroupController_ != nullptr) {
435 bundleGroupController_->RestoreDurationToDatabase();
436 }
437 if (!handler_.expired()) {
438 BUNDLE_ACTIVE_LOGI("RestoreToDatabaseLocked remove flush to disk event");
439 handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK);
440 }
441 }
442
PreservePowerStateInfo(const int32_t eventId)443 void BundleActiveCore::PreservePowerStateInfo(const int32_t eventId)
444 {
445 if (!handler_.expired()) {
446 int32_t userId = -1;
447 std::vector<int32_t> currentActiveUser;
448 BundleActiveCore::GetAllActiveUser(currentActiveUser);
449 if (currentActiveUser.size() == 1) {
450 userId = currentActiveUser.front();
451 }
452 BundleActiveReportHandlerObject tmpHandlerObject(userId, "");
453 BundleActiveEvent newEvent;
454 tmpHandlerObject.event_ = newEvent;
455 tmpHandlerObject.event_.eventId_ = eventId;
456 sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
457 tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs();
458 std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
459 std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
460 handler_.lock()->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr);
461 }
462 }
463
ShutDown()464 void BundleActiveCore::ShutDown()
465 {
466 std::lock_guard<ffrt::mutex> lock(mutex_);
467 BUNDLE_ACTIVE_LOGD("ShutDown called");
468 sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
469 int64_t timeStamp = timer->GetBootTimeMs();
470 BundleActiveEvent event(BundleActiveEvent::SHUTDOWN, timeStamp);
471 event.bundleName_ = BundleActiveEvent::DEVICE_EVENT_PACKAGE_NAME;
472 std::vector<int32_t> activatedOsAccountIds;
473 GetAllActiveUser(activatedOsAccountIds);
474 if (activatedOsAccountIds.size() == 0) {
475 BUNDLE_ACTIVE_LOGI("query activated account failed, no account activated");
476 return;
477 }
478 for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) {
479 bundleGroupController_->ShutDown(timeStamp, activatedOsAccountIds[i]);
480 }
481 ReportEventToAllUserId(event);
482 RestoreAllData();
483 }
484
OnStatsReload()485 void BundleActiveCore::OnStatsReload()
486 {
487 BUNDLE_ACTIVE_LOGD("OnStatsReload called");
488 bundleGroupController_->CheckIdleStatsOneTime();
489 }
490
OnSystemUpdate(int32_t userId)491 void BundleActiveCore::OnSystemUpdate(int32_t userId)
492 {
493 }
494
CheckTimeChangeAndGetWallTime(int32_t userId)495 int64_t WEAK_FUNC BundleActiveCore::CheckTimeChangeAndGetWallTime(int32_t userId)
496 {
497 BUNDLE_ACTIVE_LOGD("CheckTimeChangeAndGetWallTime called, userId is %{public}d", userId);
498 sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
499 int64_t actualSystemTime = GetSystemTimeMs();
500 int64_t actualRealTime = timer->GetBootTimeMs();
501 int64_t expectedSystemTime = (actualRealTime - realTimeShot_) + systemTimeShot_;
502 int64_t diffSystemTime = actualSystemTime - expectedSystemTime;
503 if (actualSystemTime == -1 || actualRealTime == -1) {
504 return ERR_TIME_OPERATION_FAILED;
505 }
506 BUNDLE_ACTIVE_LOGD("asystime is %{public}lld, artime is %{public}lld, esystime is %{public}lld, "
507 "diff is %{public}lld", (long long)actualSystemTime,
508 (long long)actualRealTime, (long long)expectedSystemTime, (long long)diffSystemTime);
509 if (std::abs(diffSystemTime) > TIME_CHANGE_THRESHOLD_MILLIS) {
510 // 时区变换逻辑
511 auto it = userStatServices_.find(userId);
512 if (it != userStatServices_.end()) {
513 BundleActiveEvent event;
514 event.eventId_ = BundleActiveEvent::FLUSH;
515 event.timeStamp_ = expectedSystemTime;
516 event.abilityId_ = "";
517 it->second->ReportEvent(event);
518 it->second->RestoreStats(true);
519 it->second->RenewTableTime(expectedSystemTime, actualSystemTime);
520 it->second->LoadActiveStats(actualSystemTime, true, true);
521 it->second->LoadModuleAndFormStats();
522 if (!handler_.expired()) {
523 BUNDLE_ACTIVE_LOGI("CheckTimeChangeAndGetWallTime remove flush to disk event");
524 handler_.lock()->RemoveEvent(BundleActiveReportHandler::MSG_FLUSH_TO_DISK);
525 }
526 }
527 realTimeShot_ = actualRealTime;
528 systemTimeShot_ = actualSystemTime;
529 }
530 return actualSystemTime;
531 }
532
ConvertToSystemTimeLocked(BundleActiveEvent & event)533 void BundleActiveCore::ConvertToSystemTimeLocked(BundleActiveEvent& event)
534 {
535 BUNDLE_ACTIVE_LOGD("ConvertToSystemTimeLocked called");
536 event.timeStamp_ = std::max((int64_t)0, event.timeStamp_ - realTimeShot_) + systemTimeShot_;
537 }
538
OnUserRemoved(const int32_t userId)539 void BundleActiveCore::OnUserRemoved(const int32_t userId)
540 {
541 BUNDLE_ACTIVE_LOGD("OnUserRemoved called");
542 std::lock_guard<ffrt::mutex> lock(mutex_);
543 auto it = userStatServices_.find(userId);
544 if (it == userStatServices_.end()) {
545 return;
546 }
547 userStatServices_[userId]->OnUserRemoved();
548 userStatServices_[userId].reset();
549 userStatServices_.erase(userId);
550 bundleGroupController_->OnUserRemoved(userId);
551 }
552
OnUserSwitched(const int32_t userId)553 void BundleActiveCore::OnUserSwitched(const int32_t userId)
554 {
555 sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
556 auto it = userStatServices_.find(currentUsedUser_);
557 if (it != userStatServices_.end()) {
558 BUNDLE_ACTIVE_LOGI("restore old user id %{public}d data when switch user", currentUsedUser_);
559 BundleActiveEvent event;
560 event.eventId_ = BundleActiveEvent::FLUSH;
561 int64_t actualRealTime = timer->GetBootTimeMs();
562 event.timeStamp_ = (actualRealTime - realTimeShot_) + systemTimeShot_;
563 event.abilityId_ = "";
564 it->second->ReportEvent(event);
565 it->second->RestoreStats(true);
566 }
567 std::vector<int32_t> activatedOsAccountIds;
568 GetAllActiveUser(activatedOsAccountIds);
569 if (activatedOsAccountIds.size() == 0) {
570 BUNDLE_ACTIVE_LOGI("query activated account failed, no account activated");
571 return;
572 }
573 for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) {
574 BUNDLE_ACTIVE_LOGI("start to period check for userId %{public}d", activatedOsAccountIds[i]);
575 bundleGroupController_->OnUserSwitched(activatedOsAccountIds[i], currentUsedUser_);
576 }
577 currentUsedUser_ = userId;
578 OnStatsChanged(userId);
579 }
580
ReportEvent(BundleActiveEvent & event,int32_t userId)581 int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, int32_t userId)
582 {
583 BUNDLE_ACTIVE_LOGD("FLUSH interval is %{public}lld, debug is %{public}d", (long long)flushInterval_, debugCore_);
584 ObtainSystemEventName(event);
585 event.PrintEvent(debugCore_);
586 std::lock_guard<ffrt::mutex> lock(mutex_);
587 if (userId == 0 || userId == -1) {
588 return -1;
589 }
590 if (currentUsedUser_ == -1) {
591 currentUsedUser_ = userId;
592 BUNDLE_ACTIVE_LOGI("last used id change to %{public}d", currentUsedUser_);
593 }
594 sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
595 int64_t bootBasedTimeStamp = timer->GetBootTimeMs();
596 if (BundleActiveBundleMgrHelper::GetInstance()->IsLauncherApp(event.bundleName_, userId)) {
597 BUNDLE_ACTIVE_LOGI("launcher event, only update app group");
598 bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId);
599 return 0;
600 }
601 BUNDLE_ACTIVE_LOGD("report event called, bundle name %{public}s time %{public}lld userId %{public}d, "
602 "eventid %{public}d, in lock range", event.bundleName_.c_str(),
603 (long long)event.timeStamp_, userId, event.eventId_);
604 int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
605 if (timeNow == ERR_TIME_OPERATION_FAILED) {
606 return -1;
607 }
608 ConvertToSystemTimeLocked(event);
609 std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
610 if (service == nullptr) {
611 BUNDLE_ACTIVE_LOGE("get user data service failed!");
612 return -1;
613 }
614 if (event.eventId_ == BundleActiveEvent::FORM_IS_CLICKED ||
615 event.eventId_ == BundleActiveEvent::FORM_IS_REMOVED) {
616 service->ReportFormEvent(event);
617 return 0;
618 }
619 service->ReportModuleEvent(event);
620 service->ReportEvent(event);
621 bundleGroupController_->ReportEvent(event, bootBasedTimeStamp, userId);
622 return 0;
623 }
624
ObtainSystemEventName(BundleActiveEvent & event)625 void BundleActiveCore::ObtainSystemEventName(BundleActiveEvent& event)
626 {
627 switch (event.eventId_) {
628 case BundleActiveEvent::SYSTEM_LOCK:
629 event.bundleName_ = OPERATION_SYSTEM_LOCK;
630 break;
631 case BundleActiveEvent::SYSTEM_UNLOCK:
632 event.bundleName_ = OPERATION_SYSTEM_UNLOCK;
633 break;
634 case BundleActiveEvent::SYSTEM_SLEEP:
635 event.bundleName_ = OPERATION_SYSTEM_SLEEP;
636 break;
637 case BundleActiveEvent::SYSTEM_WAKEUP:
638 event.bundleName_ = OPERATION_SYSTEM_WAKEUP;
639 break;
640 default:
641 break;
642 }
643 }
644
ReportEventToAllUserId(BundleActiveEvent & event)645 int32_t BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event)
646 {
647 BUNDLE_ACTIVE_LOGD("ReportEventToAllUserId called");
648 int64_t timeNow = CheckTimeChangeAndGetWallTime();
649 if (timeNow == ERR_TIME_OPERATION_FAILED) {
650 return -1;
651 }
652 if (userStatServices_.empty()) {
653 return DEFAULT_USER_ID;
654 }
655 for (const auto& it : userStatServices_) {
656 ConvertToSystemTimeLocked(event);
657 std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(it.first, timeNow,
658 debugCore_);
659 if (service == nullptr) {
660 BUNDLE_ACTIVE_LOGE("get user data service failed!");
661 return -1;
662 }
663 BUNDLE_ACTIVE_LOGI("ReportEventToAllUserId SERVICE user ID IS userId %{public}d", service->userId_);
664 service->ReportForShutdown(event);
665 return 0;
666 }
667 return 0;
668 }
669
QueryBundleStatsInfos(std::vector<BundleActivePackageStats> & packageStats,const int32_t userId,const int32_t intervalType,const int64_t beginTime,const int64_t endTime,std::string bundleName)670 ErrCode BundleActiveCore::QueryBundleStatsInfos(std::vector<BundleActivePackageStats>& packageStats,
671 const int32_t userId, const int32_t intervalType, const int64_t beginTime, const int64_t endTime,
672 std::string bundleName)
673 {
674 BUNDLE_ACTIVE_LOGD("QueryBundleStatsInfos called");
675 std::lock_guard<ffrt::mutex> lock(mutex_);
676 int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
677 if (timeNow == ERR_TIME_OPERATION_FAILED) {
678 return ERR_TIME_OPERATION_FAILED;
679 }
680
681 BUNDLE_ACTIVE_LOGD("QueryBundleStatsInfos begin time is %{public}lld, end time is %{public}lld, "
682 "intervaltype is %{public}d", (long long)beginTime, (long long)endTime, intervalType);
683 if (beginTime > timeNow || beginTime >= endTime) {
684 BUNDLE_ACTIVE_LOGI("QueryBundleStatsInfos time span illegal");
685 return ERR_QUERY_TIME_OUT_OF_RANGE;
686 }
687
688 std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
689 if (service == nullptr) {
690 BUNDLE_ACTIVE_LOGI("QueryBundleStatsInfos service is null, failed");
691 return ERR_MEMORY_OPERATION_FAILED;
692 }
693 return service->QueryBundleStatsInfos(packageStats, intervalType, beginTime, endTime, userId, bundleName);
694 }
695
QueryBundleEvents(std::vector<BundleActiveEvent> & bundleActiveEvent,const int32_t userId,const int64_t beginTime,const int64_t endTime,std::string bundleName)696 ErrCode BundleActiveCore::QueryBundleEvents(std::vector<BundleActiveEvent>& bundleActiveEvent, const int32_t userId,
697 const int64_t beginTime, const int64_t endTime, std::string bundleName)
698 {
699 BUNDLE_ACTIVE_LOGD("QueryBundleEvents called");
700 std::lock_guard<ffrt::mutex> lock(mutex_);
701 int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
702 if (timeNow == ERR_TIME_OPERATION_FAILED) {
703 return ERR_TIME_OPERATION_FAILED;
704 }
705 if (beginTime > timeNow || beginTime >= endTime) {
706 return ERR_QUERY_TIME_OUT_OF_RANGE;
707 }
708 std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
709 if (service == nullptr) {
710 return ERR_MEMORY_OPERATION_FAILED;
711 }
712 auto item = service->QueryBundleEvents(bundleActiveEvent, beginTime, endTime, userId, bundleName);
713 return item;
714 }
715
QueryModuleUsageRecords(int32_t maxNum,std::vector<BundleActiveModuleRecord> & results,int32_t userId)716 ErrCode BundleActiveCore::QueryModuleUsageRecords(int32_t maxNum, std::vector<BundleActiveModuleRecord>& results,
717 int32_t userId)
718 {
719 std::lock_guard<ffrt::mutex> lock(mutex_);
720 int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
721 if (timeNow == ERR_TIME_OPERATION_FAILED) {
722 return ERR_TIME_OPERATION_FAILED;
723 }
724 std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
725 if (!service) {
726 return ERR_MEMORY_OPERATION_FAILED;
727 }
728 return service->QueryModuleUsageRecords(maxNum, results);
729 }
730
QueryDeviceEventStats(int64_t beginTime,int64_t endTime,std::vector<BundleActiveEventStats> & eventStats,int32_t userId)731 ErrCode BundleActiveCore::QueryDeviceEventStats(int64_t beginTime, int64_t endTime,
732 std::vector<BundleActiveEventStats>& eventStats, int32_t userId)
733 {
734 std::lock_guard<ffrt::mutex> lock(mutex_);
735 int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
736 if (timeNow == ERR_TIME_OPERATION_FAILED) {
737 return ERR_TIME_OPERATION_FAILED;
738 }
739 std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
740 if (!service) {
741 return ERR_MEMORY_OPERATION_FAILED;
742 }
743 return service->QueryDeviceEventStats(beginTime, endTime, eventStats, userId);
744 }
745
QueryNotificationEventStats(int64_t beginTime,int64_t endTime,std::vector<BundleActiveEventStats> & eventStats,int32_t userId)746 ErrCode BundleActiveCore::QueryNotificationEventStats(int64_t beginTime, int64_t endTime,
747 std::vector<BundleActiveEventStats>& eventStats, int32_t userId)
748 {
749 std::lock_guard<ffrt::mutex> lock(mutex_);
750 int64_t timeNow = CheckTimeChangeAndGetWallTime(userId);
751 if (timeNow == ERR_TIME_OPERATION_FAILED) {
752 return ERR_TIME_OPERATION_FAILED;
753 }
754 std::shared_ptr<BundleActiveUserService> service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_);
755 if (!service) {
756 return ERR_MEMORY_OPERATION_FAILED;
757 }
758 return service->QueryNotificationEventStats(beginTime, endTime, eventStats, userId);
759 }
760
SetAppGroup(const std::string & bundleName,const int32_t newGroup,const int32_t userId,const bool isFlush)761 ErrCode BundleActiveCore::SetAppGroup(
762 const std::string& bundleName, const int32_t newGroup, const int32_t userId, const bool isFlush)
763 {
764 int32_t newReason = GROUP_CONTROL_REASON_FORCED;
765 sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
766 int64_t bootBasedTimeStamp = timer->GetBootTimeMs();
767 return bundleGroupController_->SetAppGroup(
768 bundleName, userId, newGroup, newReason, bootBasedTimeStamp, isFlush);
769 }
770
QueryAppGroup(int32_t & appGroup,const std::string & bundleName,const int32_t userId)771 ErrCode BundleActiveCore::QueryAppGroup(int32_t& appGroup, const std::string& bundleName, const int32_t userId)
772 {
773 return bundleGroupController_->QueryAppGroup(appGroup, bundleName, userId);
774 }
775
IsBundleIdle(const std::string & bundleName,const int32_t userId)776 int32_t BundleActiveCore::IsBundleIdle(const std::string& bundleName, const int32_t userId)
777 {
778 return bundleGroupController_->IsBundleIdle(bundleName, userId);
779 }
780
IsBundleUsePeriod(const std::string & bundleName,const int32_t userId)781 bool BundleActiveCore::IsBundleUsePeriod(const std::string& bundleName, const int32_t userId)
782 {
783 if (!bundleGroupController_->IsBundleInstalled(bundleName, userId)) {
784 BUNDLE_ACTIVE_LOGI("IsBundleUsePeriod is not bundleInstalled");
785 return false;
786 }
787 int64_t currentSystemTime = GetSystemTimeMs();
788 int64_t aWeekAgo = currentSystemTime - ONE_WEEK_TIME;
789 int64_t startTime = BundleActiveUtil::GetIntervalTypeStartTime(aWeekAgo, BundleActiveUtil::PERIOD_DAILY);
790 std::vector<BundleActivePackageStats> packageStats;
791 QueryBundleStatsInfos(packageStats, userId, BundleActivePeriodStats::PERIOD_DAILY, startTime,
792 currentSystemTime, bundleName);
793 int32_t useDayPeriod = 0;
794 for (auto& item : packageStats) {
795 if (item.startCount_ >= bundleActiveConfigReader_->GetApplicationUsePeriodicallyConfig().minUseTimes
796 && item.startCount_ <= bundleActiveConfigReader_->GetApplicationUsePeriodicallyConfig().maxUseTimes) {
797 useDayPeriod ++;
798 }
799 }
800 return useDayPeriod >= bundleActiveConfigReader_->GetApplicationUsePeriodicallyConfig().minUseDays;
801 }
802
GetAllActiveUser(std::vector<int32_t> & activatedOsAccountIds)803 void BundleActiveCore::GetAllActiveUser(std::vector<int32_t>& activatedOsAccountIds)
804 {
805 #ifdef OS_ACCOUNT_PART_ENABLED
806 if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(activatedOsAccountIds) != ERR_OK) {
807 BUNDLE_ACTIVE_LOGI("query activated account failed");
808 return;
809 }
810 #else // OS_ACCOUNT_PART_ENABLED
811 activatedOsAccountIds.clear();
812 activatedOsAccountIds.push_back(DEFAULT_OS_ACCOUNT_ID);
813 BUNDLE_ACTIVE_LOGI("os account part is not enabled, use default id.");
814 #endif // OS_ACCOUNT_PART_ENABLED
815 if (activatedOsAccountIds.size() == 0) {
816 BUNDLE_ACTIVE_LOGI("GetAllActiveUser size is 0");
817 return;
818 }
819 }
820
GetSystemTimeMs()821 int64_t BundleActiveCore::GetSystemTimeMs()
822 {
823 time_t now;
824 (void)time(&now); // unit is seconds.
825 if (static_cast<int64_t>(now) < 0) {
826 BUNDLE_ACTIVE_LOGE("Get now time error");
827 return 0;
828 }
829 auto tarEndTimePoint = std::chrono::system_clock::from_time_t(now);
830 auto tarDuration = std::chrono::duration_cast<std::chrono::milliseconds>(tarEndTimePoint.time_since_epoch());
831 int64_t tarDate = tarDuration.count();
832 if (tarDate < 0) {
833 BUNDLE_ACTIVE_LOGE("tarDuration is less than 0.");
834 return -1;
835 }
836 return static_cast<int64_t>(tarDate);
837 }
838
OnAppGroupChanged(const AppGroupCallbackInfo & callbackInfo)839 void BundleActiveCore::OnAppGroupChanged(const AppGroupCallbackInfo& callbackInfo)
840 {
841 std::shared_ptr<BundleActiveCore> bundleActiveCore = shared_from_this();
842 AccessToken::HapTokenInfo tokenInfo = AccessToken::HapTokenInfo();
843 bundleGroupHandler_->PostTask([bundleActiveCore, callbackInfo, tokenInfo]() {
844 bundleActiveCore->NotifOberserverGroupChanged(callbackInfo, tokenInfo);
845 });
846 }
847
NotifOberserverGroupChanged(const AppGroupCallbackInfo & callbackInfo,AccessToken::HapTokenInfo tokenInfo)848 void BundleActiveCore::NotifOberserverGroupChanged(const AppGroupCallbackInfo& callbackInfo,
849 AccessToken::HapTokenInfo tokenInfo)
850 {
851 std::lock_guard<ffrt::recursive_mutex> lock(callbackMutex_);
852 for (const auto &item : groupChangeObservers_) {
853 auto observer = item.second;
854 if (!observer) {
855 continue;
856 }
857 BUNDLE_ACTIVE_LOGI(
858 "RegisterAppGroupCallBack will OnAppGroupChanged!,oldGroup is %{public}d, newGroup is %{public}d",
859 callbackInfo.GetOldGroup(), callbackInfo.GetNewGroup());
860 if (AccessToken::AccessTokenKit::GetTokenType(item.first) == AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
861 observer->OnAppGroupChanged(callbackInfo);
862 } else if (AccessToken::AccessTokenKit::GetTokenType(item.first) ==
863 AccessToken::ATokenTypeEnum::TOKEN_HAP) {
864 AccessToken::AccessTokenKit::GetHapTokenInfo(item.first, tokenInfo);
865 if (tokenInfo.userID == callbackInfo.GetUserId()) {
866 observer->OnAppGroupChanged(callbackInfo);
867 }
868 }
869 }
870 }
871
RegisterAppGroupCallBack(const AccessToken::AccessTokenID & tokenId,const sptr<IAppGroupCallback> & observer)872 ErrCode BundleActiveCore::RegisterAppGroupCallBack(const AccessToken::AccessTokenID& tokenId,
873 const sptr<IAppGroupCallback> &observer)
874 {
875 std::lock_guard<ffrt::recursive_mutex> lock(callbackMutex_);
876 if (!observer) {
877 return ERR_MEMORY_OPERATION_FAILED;
878 }
879 auto item = groupChangeObservers_.find(tokenId);
880 if (item != groupChangeObservers_.end()) {
881 return ERR_REPEAT_REGISTER_OR_DEREGISTER_GROUP_CALLBACK;
882 }
883 groupChangeObservers_.emplace(tokenId, observer);
884 AddObserverDeathRecipient(observer);
885 BUNDLE_ACTIVE_LOGD("RegisterAppGroupCallBack number is %{public}d", static_cast<int>(groupChangeObservers_.size()));
886 return ERR_OK;
887 }
888
UnRegisterAppGroupCallBack(const AccessToken::AccessTokenID & tokenId,const sptr<IAppGroupCallback> & observer)889 ErrCode BundleActiveCore::UnRegisterAppGroupCallBack(const AccessToken::AccessTokenID& tokenId,
890 const sptr<IAppGroupCallback> &observer)
891 {
892 std::lock_guard<ffrt::recursive_mutex> lock(callbackMutex_);
893 auto item = groupChangeObservers_.find(tokenId);
894 if (item == groupChangeObservers_.end()) {
895 BUNDLE_ACTIVE_LOGI("UnRegisterAppGroupCallBack observer is not exist, return");
896 return ERR_REPEAT_REGISTER_OR_DEREGISTER_GROUP_CALLBACK;
897 }
898 RemoveObserverDeathRecipient(item->second);
899 groupChangeObservers_.erase(tokenId);
900 return ERR_OK;
901 }
902
AddObserverDeathRecipient(const sptr<IAppGroupCallback> & observer)903 void BundleActiveCore::AddObserverDeathRecipient(const sptr<IAppGroupCallback> &observer)
904 {
905 std::lock_guard<ffrt::recursive_mutex> lock(callbackMutex_);
906 if (!observer) {
907 BUNDLE_ACTIVE_LOGI("observer nullptr.");
908 return;
909 }
910 auto object = observer->AsObject();
911 if (!object) {
912 BUNDLE_ACTIVE_LOGI("observer->AsObject() nullptr.");
913 return;
914 }
915 auto it = recipientMap_.find(observer->AsObject());
916 if (it != recipientMap_.end()) {
917 BUNDLE_ACTIVE_LOGI("This death recipient has been added.");
918 return;
919 }
920 sptr<RemoteDeathRecipient> deathRecipient = new (std::nothrow) RemoteDeathRecipient(
921 [this](const wptr<IRemoteObject> &remote) { this->OnObserverDied(remote); });
922 if (!deathRecipient) {
923 BUNDLE_ACTIVE_LOGI("create death recipient failed");
924 return ;
925 }
926 observer->AsObject()->AddDeathRecipient(deathRecipient);
927 recipientMap_.emplace(observer->AsObject(), deathRecipient);
928 }
RemoveObserverDeathRecipient(const sptr<IAppGroupCallback> & observer)929 void BundleActiveCore::RemoveObserverDeathRecipient(const sptr<IAppGroupCallback> &observer)
930 {
931 std::lock_guard<ffrt::recursive_mutex> lock(callbackMutex_);
932 if (!observer) {
933 return;
934 }
935 auto object = observer->AsObject();
936 if (!object) {
937 return ;
938 }
939 auto iter = recipientMap_.find(observer->AsObject());
940 if (iter != recipientMap_.end()) {
941 iter->first->RemoveDeathRecipient(iter->second);
942 recipientMap_.erase(iter);
943 }
944 }
945
OnObserverDied(const wptr<IRemoteObject> & remote)946 void BundleActiveCore::OnObserverDied(const wptr<IRemoteObject> &remote)
947 {
948 if (remote == nullptr) {
949 BUNDLE_ACTIVE_LOGE("remote object is null.");
950 return;
951 }
952 std::shared_ptr<BundleActiveCore> bundleActiveCore = shared_from_this();
953 bundleGroupHandler_->PostSyncTask([bundleActiveCore, &remote]() {
954 bundleActiveCore->OnObserverDiedInner(remote);
955 });
956 }
957
OnObserverDiedInner(const wptr<IRemoteObject> & remote)958 void BundleActiveCore::OnObserverDiedInner(const wptr<IRemoteObject> &remote)
959 {
960 sptr<IRemoteObject> objectProxy = remote.promote();
961 if (remote == nullptr || !objectProxy) {
962 BUNDLE_ACTIVE_LOGE("get remote object failed");
963 return;
964 }
965 std::lock_guard<ffrt::recursive_mutex> lock(callbackMutex_);
966 for (const auto& item : groupChangeObservers_) {
967 if (!(item.second)) {
968 continue;
969 }
970 auto object = (item.second)->AsObject();
971 if (!object) {
972 continue;
973 }
974 if (object == objectProxy) {
975 groupChangeObservers_.erase(item.first);
976 break;
977 }
978 }
979 recipientMap_.erase(objectProxy);
980 }
981 } // namespace DeviceUsageStats
982 } // namespace OHOS
983
984