• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "app_state_observer_manager.h"
17 
18 #include "ability_foreground_state_observer_stub.h"
19 #include "app_foreground_state_observer_stub.h"
20 #include "application_state_observer_stub.h"
21 #include "hilog_tag_wrapper.h"
22 #include "hitrace_meter.h"
23 #include "in_process_call_wrapper.h"
24 #include "remote_client_manager.h"
25 #include "ui_extension_utils.h"
26 #include "parameters.h"
27 
28 namespace OHOS {
29 namespace AppExecFwk {
30 namespace {
31 const std::string XIAOYI_BUNDLE_NAME = "com.huawei.hmos.vassistant";
32 constexpr int BUNDLE_NAME_LIST_MAX_SIZE = 128;
33 constexpr int OBSERVER_SINGLE_COUNT_LOG = 40;
34 constexpr int OBSERVER_SINGLE_STEP_LOG = 10;
35 constexpr int OBSERVER_UID_COUNT_LOG = 3;
36 constexpr int OBSERVER_AMOUNT_COUNT_LOG = 70;
37 constexpr const char* DEVELOPER_MODE_STATE = "const.security.developermode.state";
38 } // namespace
AppStateObserverManager()39 AppStateObserverManager::AppStateObserverManager()
40 {
41     TAG_LOGD(AAFwkTag::APPMGR, "AppStateObserverManager instance is created");
42 }
43 
~AppStateObserverManager()44 AppStateObserverManager::~AppStateObserverManager()
45 {
46     TAG_LOGD(AAFwkTag::APPMGR, "AppStateObserverManager instance is destroyed");
47 }
48 
Init()49 void AppStateObserverManager::Init()
50 {
51     if (!handler_) {
52         handler_ = AAFwk::TaskHandlerWrap::CreateQueueHandler("app_state_task_queue");
53     }
54 }
55 
RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer,const std::vector<std::string> & bundleNameList)56 int32_t AppStateObserverManager::RegisterApplicationStateObserver(
57     const sptr<IApplicationStateObserver> &observer, const std::vector<std::string> &bundleNameList)
58 {
59     TAG_LOGD(AAFwkTag::APPMGR, "called");
60     if (bundleNameList.size() > BUNDLE_NAME_LIST_MAX_SIZE) {
61         TAG_LOGE(AAFwkTag::APPMGR, "bundleNameList passed in is too long");
62         return ERR_INVALID_VALUE;
63     }
64     if (AAFwk::PermissionVerification::GetInstance()->VerifyAppStateObserverPermission() == ERR_PERMISSION_DENIED) {
65         TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
66         return ERR_PERMISSION_DENIED;
67     }
68     if (observer == nullptr) {
69         TAG_LOGE(AAFwkTag::APPMGR, "null observer");
70         return ERR_INVALID_VALUE;
71     }
72     if (ObserverExist(observer)) {
73         TAG_LOGE(AAFwkTag::APPMGR, "observer exist");
74         return ERR_INVALID_VALUE;
75     }
76     std::lock_guard lockRegister(observerLock_);
77     appStateObserverMap_.emplace(observer, AppStateObserverInfo{IPCSkeleton::GetCallingUid(), bundleNameList});
78     if (appStateObserverMap_.size() >= OBSERVER_SINGLE_COUNT_LOG &&
79         appStateObserverMap_.size() % OBSERVER_SINGLE_STEP_LOG == 0) {
80         TAG_LOGW(AAFwkTag::APPMGR, "appStateObserverMap_ size:%{public}zu", appStateObserverMap_.size());
81     }
82     AddObserverCount(IPCSkeleton::GetCallingUid());
83     AddObserverDeathRecipient(observer, ObserverType::APPLICATION_STATE_OBSERVER);
84     return ERR_OK;
85 }
86 
UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer)87 int32_t AppStateObserverManager::UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
88 {
89     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
90     TAG_LOGD(AAFwkTag::APPMGR, "called");
91     if (AAFwk::PermissionVerification::GetInstance()->VerifyAppStateObserverPermission() == ERR_PERMISSION_DENIED) {
92         TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
93         return ERR_PERMISSION_DENIED;
94     }
95     std::lock_guard lockUnregister(observerLock_);
96     if (observer == nullptr) {
97         TAG_LOGE(AAFwkTag::APPMGR, "null observer");
98         return ERR_INVALID_VALUE;
99     }
100 
101     for (auto it = appStateObserverMap_.begin(); it != appStateObserverMap_.end(); ++it) {
102         if (it->first->AsObject() == observer->AsObject()) {
103             DecreaseObserverCount(it->second.uid);
104             appStateObserverMap_.erase(it);
105             TAG_LOGD(AAFwkTag::APPMGR, "appStateObserverMap_ size:%{public}zu", appStateObserverMap_.size());
106             RemoveObserverDeathRecipient(observer);
107             return ERR_OK;
108         }
109     }
110     TAG_LOGE(AAFwkTag::APPMGR, "observer not exist");
111     return ERR_INVALID_VALUE;
112 }
113 
RegisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> & observer)114 int32_t AppStateObserverManager::RegisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> &observer)
115 {
116     TAG_LOGD(AAFwkTag::APPMGR, "called");
117     if (observer == nullptr) {
118         TAG_LOGE(AAFwkTag::APPMGR, "null observer");
119         return ERR_INVALID_VALUE;
120     }
121     if (AAFwk::PermissionVerification::GetInstance()->VerifyAppStateObserverPermission() == ERR_PERMISSION_DENIED) {
122         TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
123         return ERR_PERMISSION_DENIED;
124     }
125     if (IsAppForegroundObserverExist(observer)) {
126         TAG_LOGE(AAFwkTag::APPMGR, "observer exist");
127         return ERR_INVALID_VALUE;
128     }
129 
130     std::lock_guard lockRegister(appForegroundObserverLock_);
131     appForegroundStateObserverMap_.emplace(observer, IPCSkeleton::GetCallingUid());
132     AddObserverDeathRecipient(observer, ObserverType::APP_FOREGROUND_STATE_OBSERVER);
133     AddObserverCount(IPCSkeleton::GetCallingUid());
134     if (appForegroundStateObserverMap_.size() >= OBSERVER_SINGLE_COUNT_LOG &&
135         appForegroundStateObserverMap_.size() % OBSERVER_SINGLE_STEP_LOG == 0) {
136         TAG_LOGW(AAFwkTag::APPMGR, "appForegroundObserver size:%{public}zu", appForegroundStateObserverMap_.size());
137     }
138     return ERR_OK;
139 }
140 
UnregisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> & observer)141 int32_t AppStateObserverManager::UnregisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> &observer)
142 {
143     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
144     TAG_LOGD(AAFwkTag::APPMGR, "called");
145     if (observer == nullptr) {
146         TAG_LOGE(AAFwkTag::APPMGR, "null observer");
147         return ERR_INVALID_VALUE;
148     }
149     if (AAFwk::PermissionVerification::GetInstance()->VerifyAppStateObserverPermission() == ERR_PERMISSION_DENIED) {
150         TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
151         return ERR_PERMISSION_DENIED;
152     }
153     std::lock_guard lockUnregister(appForegroundObserverLock_);
154     for (const auto &[it, uid] : appForegroundStateObserverMap_) {
155         if (it != nullptr && it->AsObject() == observer->AsObject()) {
156             DecreaseObserverCount(uid);
157             appForegroundStateObserverMap_.erase(it);
158             RemoveObserverDeathRecipient(observer);
159             return ERR_OK;
160         }
161     }
162     return ERR_INVALID_VALUE;
163 }
164 
RegisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> & observer)165 int32_t AppStateObserverManager::RegisterAbilityForegroundStateObserver(
166     const sptr<IAbilityForegroundStateObserver> &observer)
167 {
168     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
169     TAG_LOGD(AAFwkTag::APPMGR, "called");
170     if (observer == nullptr) {
171         TAG_LOGE(AAFwkTag::APPMGR, "null observer");
172         return ERR_INVALID_VALUE;
173     }
174     if (AAFwk::PermissionVerification::GetInstance()->VerifyAppStateObserverPermission() == ERR_PERMISSION_DENIED) {
175         TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
176         return ERR_PERMISSION_DENIED;
177     }
178     if (IsAbilityForegroundObserverExist(observer)) {
179         TAG_LOGW(AAFwkTag::APPMGR, "Observer exist.");
180         return ERR_OK;
181     }
182 
183     std::lock_guard lockRegister(abilityForegroundObserverLock_);
184     abilityForegroundObserverMap_.emplace(observer, IPCSkeleton::GetCallingUid());
185     AddObserverDeathRecipient(observer, ObserverType::ABILITY_FOREGROUND_STATE_OBSERVER);
186     AddObserverCount(IPCSkeleton::GetCallingUid());
187     if (abilityForegroundObserverMap_.size() >= OBSERVER_SINGLE_COUNT_LOG &&
188         abilityForegroundObserverMap_.size() % OBSERVER_SINGLE_STEP_LOG == 0) {
189         TAG_LOGW(AAFwkTag::APPMGR, "abilityForegroundObserver size:%{public}zu", abilityForegroundObserverMap_.size());
190     }
191     return ERR_OK;
192 }
193 
UnregisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> & observer)194 int32_t AppStateObserverManager::UnregisterAbilityForegroundStateObserver(
195     const sptr<IAbilityForegroundStateObserver> &observer)
196 {
197     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
198     TAG_LOGD(AAFwkTag::APPMGR, "called");
199     if (observer == nullptr) {
200         TAG_LOGE(AAFwkTag::APPMGR, "null observer");
201         return ERR_INVALID_VALUE;
202     }
203     if (AAFwk::PermissionVerification::GetInstance()->VerifyAppStateObserverPermission() == ERR_PERMISSION_DENIED) {
204         TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
205         return ERR_PERMISSION_DENIED;
206     }
207     std::lock_guard lockUnregister(abilityForegroundObserverLock_);
208     for (const auto &[it, uid] : abilityForegroundObserverMap_) {
209         if (it != nullptr && it->AsObject() == observer->AsObject()) {
210             DecreaseObserverCount(uid);
211             abilityForegroundObserverMap_.erase(it);
212             RemoveObserverDeathRecipient(observer);
213             return ERR_OK;
214         }
215     }
216     return ERR_INVALID_VALUE;
217 }
218 
OnAppStarted(const std::shared_ptr<AppRunningRecord> & appRecord)219 void AppStateObserverManager::OnAppStarted(const std::shared_ptr<AppRunningRecord> &appRecord)
220 {
221     if (handler_ == nullptr) {
222         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
223         return;
224     }
225 
226     auto task = [weak = weak_from_this(), appRecord]() {
227         auto self = weak.lock();
228         if (self == nullptr) {
229             TAG_LOGE(AAFwkTag::APPMGR, "null self");
230             return;
231         }
232         TAG_LOGD(AAFwkTag::APPMGR, "OnAppStarted come.");
233         self->HandleOnAppStarted(appRecord);
234     };
235     handler_->SubmitTask(task);
236 }
237 
OnAppStopped(const std::shared_ptr<AppRunningRecord> & appRecord)238 void AppStateObserverManager::OnAppStopped(const std::shared_ptr<AppRunningRecord> &appRecord)
239 {
240     if (handler_ == nullptr) {
241         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
242         return;
243     }
244 
245     auto task = [weak = weak_from_this(), appRecord]() {
246         auto self = weak.lock();
247         if (self == nullptr) {
248             TAG_LOGE(AAFwkTag::APPMGR, "null self");
249             return;
250         }
251         TAG_LOGD(AAFwkTag::APPMGR, "OnAppStopped come.");
252         self->HandleOnAppStopped(appRecord);
253     };
254     handler_->SubmitTask(task);
255 }
256 
257 
OnAppStateChanged(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state,bool needNotifyApp,bool isFromWindowFocusChanged)258 void AppStateObserverManager::OnAppStateChanged(
259     const std::shared_ptr<AppRunningRecord> &appRecord,
260     const ApplicationState state,
261     bool needNotifyApp,
262     bool isFromWindowFocusChanged)
263 {
264     if (handler_ == nullptr) {
265         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
266         return;
267     }
268 
269     auto task = [weak = weak_from_this(), appRecord, state, needNotifyApp, isFromWindowFocusChanged]() {
270         auto self = weak.lock();
271         if (self == nullptr) {
272             TAG_LOGE(AAFwkTag::APPMGR, "null self");
273             return;
274         }
275         TAG_LOGD(AAFwkTag::APPMGR, "OnAppStateChanged come.");
276         self->HandleAppStateChanged(appRecord, state, needNotifyApp, isFromWindowFocusChanged);
277     };
278     handler_->SubmitTask(task);
279 }
280 
OnProcessDied(const std::shared_ptr<AppRunningRecord> & appRecord)281 void AppStateObserverManager::OnProcessDied(const std::shared_ptr<AppRunningRecord> &appRecord)
282 {
283     if (handler_ == nullptr) {
284         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
285         return;
286     }
287 
288     auto task = [weak = weak_from_this(), appRecord]() {
289         auto self = weak.lock();
290         if (self == nullptr) {
291             TAG_LOGE(AAFwkTag::APPMGR, "null self");
292             return;
293         }
294         TAG_LOGD(AAFwkTag::APPMGR, "OnProcessDied come.");
295     self->HandleOnAppProcessDied(appRecord);
296     };
297     handler_->SubmitTask(task);
298 }
299 
OnRenderProcessDied(const std::shared_ptr<RenderRecord> & renderRecord)300 void AppStateObserverManager::OnRenderProcessDied(const std::shared_ptr<RenderRecord> &renderRecord)
301 {
302     if (handler_ == nullptr) {
303         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
304         return;
305     }
306 
307     auto task = [weak = weak_from_this(), renderRecord]() {
308         auto self = weak.lock();
309         if (self == nullptr) {
310             TAG_LOGE(AAFwkTag::APPMGR, "null self");
311             return;
312         }
313         TAG_LOGD(AAFwkTag::APPMGR, "OnRenderProcessDied come.");
314         self->HandleOnRenderProcessDied(renderRecord);
315     };
316     handler_->SubmitTask(task);
317 }
318 
319 #ifdef SUPPORT_CHILD_PROCESS
OnChildProcessDied(std::shared_ptr<ChildProcessRecord> childRecord)320 void AppStateObserverManager::OnChildProcessDied(std::shared_ptr<ChildProcessRecord> childRecord)
321 {
322     if (handler_ == nullptr) {
323         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
324         return;
325     }
326 
327     auto task = [weak = weak_from_this(), childRecord]() {
328         auto self = weak.lock();
329         if (self == nullptr) {
330             TAG_LOGE(AAFwkTag::APPMGR, "null self");
331             return;
332         }
333         TAG_LOGD(AAFwkTag::APPMGR, "OnChildProcessDied come.");
334         self->HandleOnChildProcessDied(childRecord);
335     };
336     handler_->SubmitTask(task);
337 }
338 #endif // SUPPORT_CHILD_PROCESS
339 
OnProcessStateChanged(const std::shared_ptr<AppRunningRecord> & appRecord)340 void AppStateObserverManager::OnProcessStateChanged(const std::shared_ptr<AppRunningRecord> &appRecord)
341 {
342     if (handler_ == nullptr) {
343         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
344         return;
345     }
346 
347     auto task = [weak = weak_from_this(), appRecord]() {
348         auto self = weak.lock();
349         if (self == nullptr) {
350             TAG_LOGE(AAFwkTag::APPMGR, "null self");
351             return;
352         }
353         TAG_LOGD(AAFwkTag::APPMGR, "OnProcessStateChanged come.");
354         self->HandleOnProcessStateChanged(appRecord);
355     };
356     handler_->SubmitTask(task);
357 }
358 
OnWindowShow(const std::shared_ptr<AppRunningRecord> & appRecord)359 void AppStateObserverManager::OnWindowShow(const std::shared_ptr<AppRunningRecord> &appRecord)
360 {
361     if (handler_ == nullptr) {
362         TAG_LOGE(AAFwkTag::APPMGR, "handler is nullptr, OnWindowShow failed.");
363         return;
364     }
365 
366     auto task = [weak = weak_from_this(), appRecord]() {
367         auto self = weak.lock();
368         if (self == nullptr) {
369             TAG_LOGE(AAFwkTag::APPMGR, "self is nullptr, OnWindowShow failed.");
370             return;
371         }
372         TAG_LOGD(AAFwkTag::APPMGR, "OnWindowShow come.");
373         self->HandleOnWindowShow(appRecord);
374     };
375     handler_->SubmitTask(task);
376 }
377 
OnWindowHidden(const std::shared_ptr<AppRunningRecord> & appRecord)378 void AppStateObserverManager::OnWindowHidden(const std::shared_ptr<AppRunningRecord> &appRecord)
379 {
380     if (handler_ == nullptr) {
381         TAG_LOGE(AAFwkTag::APPMGR, "handler is nullptr, OnWindowHidden failed.");
382         return;
383     }
384 
385     auto task = [weak = weak_from_this(), appRecord]() {
386         auto self = weak.lock();
387         if (self == nullptr) {
388             TAG_LOGE(AAFwkTag::APPMGR, "self is nullptr, OnWindowHidden failed.");
389             return;
390         }
391         TAG_LOGD(AAFwkTag::APPMGR, "OnWindowHidden come.");
392         self->HandleOnWindowHidden(appRecord);
393     };
394     handler_->SubmitTask(task);
395 }
396 
OnProcessCreated(const std::shared_ptr<AppRunningRecord> & appRecord,bool isPreload)397 void AppStateObserverManager::OnProcessCreated(const std::shared_ptr<AppRunningRecord> &appRecord, bool isPreload)
398 {
399     if (handler_ == nullptr) {
400         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
401         return;
402     }
403 
404     auto task = [weak = weak_from_this(), appRecord, isPreload]() {
405         auto self = weak.lock();
406         if (self == nullptr) {
407             TAG_LOGE(AAFwkTag::APPMGR, "null self");
408             return;
409         }
410         self->HandleOnAppProcessCreated(appRecord, isPreload);
411     };
412     handler_->SubmitTask(task);
413 }
414 
OnProcessReused(const std::shared_ptr<AppRunningRecord> & appRecord)415 void AppStateObserverManager::OnProcessReused(const std::shared_ptr<AppRunningRecord> &appRecord)
416 {
417     if (handler_ == nullptr) {
418         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
419         return;
420     }
421 
422     auto task = [weak = weak_from_this(), appRecord]() {
423         auto self = weak.lock();
424         if (self == nullptr) {
425             TAG_LOGE(AAFwkTag::APPMGR, "null self");
426             return;
427         }
428         TAG_LOGD(AAFwkTag::APPMGR, "OnProcessReused come.");
429         self->HandleOnProcessResued(appRecord);
430     };
431     handler_->SubmitTask(task);
432 }
433 
OnRenderProcessCreated(const std::shared_ptr<RenderRecord> & renderRecord,const bool isPreload)434 void AppStateObserverManager::OnRenderProcessCreated(const std::shared_ptr<RenderRecord> &renderRecord,
435     const bool isPreload)
436 {
437     if (handler_ == nullptr) {
438         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
439         return;
440     }
441 
442     auto task = [weak = weak_from_this(), renderRecord, isPreload]() {
443         auto self = weak.lock();
444         if (self == nullptr) {
445             TAG_LOGE(AAFwkTag::APPMGR, "null self");
446             return;
447         }
448         TAG_LOGD(AAFwkTag::APPMGR, "OnRenderProcessCreated come.");
449         self->HandleOnRenderProcessCreated(renderRecord, isPreload);
450     };
451     handler_->SubmitTask(task);
452 }
453 
454 #ifdef SUPPORT_CHILD_PROCESS
OnChildProcessCreated(std::shared_ptr<ChildProcessRecord> childRecord)455 void AppStateObserverManager::OnChildProcessCreated(std::shared_ptr<ChildProcessRecord> childRecord)
456 {
457     if (handler_ == nullptr) {
458         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
459         return;
460     }
461 
462     auto task = [weak = weak_from_this(), childRecord]() {
463         auto self = weak.lock();
464         if (self == nullptr) {
465             TAG_LOGE(AAFwkTag::APPMGR, "null self");
466             return;
467         }
468         TAG_LOGD(AAFwkTag::APPMGR, "OnChildProcessCreated come.");
469         self->HandleOnChildProcessCreated(childRecord);
470     };
471     handler_->SubmitTask(task);
472 }
473 #endif // SUPPORT_CHILD_PROCESS
474 
StateChangedNotifyObserver(const AbilityStateData abilityStateData,bool isAbility,bool isFromWindowFocusChanged)475 void AppStateObserverManager::StateChangedNotifyObserver(
476     const AbilityStateData abilityStateData, bool isAbility, bool isFromWindowFocusChanged)
477 {
478     if (handler_ == nullptr) {
479         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
480         return;
481     }
482 
483     auto task = [weak = weak_from_this(), abilityStateData, isAbility, isFromWindowFocusChanged]() {
484         auto self = weak.lock();
485         if (self == nullptr) {
486             TAG_LOGE(AAFwkTag::APPMGR, "null self");
487             return;
488         }
489         TAG_LOGD(AAFwkTag::APPMGR, "StateChangedNotifyObserver come.");
490         self->HandleStateChangedNotifyObserver(abilityStateData, isAbility, isFromWindowFocusChanged);
491     };
492     handler_->SubmitTask(task);
493 }
494 
HandleOnAppStarted(const std::shared_ptr<AppRunningRecord> & appRecord)495 void AppStateObserverManager::HandleOnAppStarted(const std::shared_ptr<AppRunningRecord> &appRecord)
496 {
497     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
498     if (appRecord == nullptr) {
499         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
500         return;
501     }
502 
503     AppStateData data = WrapAppStateData(appRecord, ApplicationState::APP_STATE_CREATE);
504     data.isSpecifyTokenId = appRecord->GetAssignTokenId() > 0 ? true : false;
505     TAG_LOGD(AAFwkTag::APPMGR, "HandleOnAppStarted, bundle:%{public}s, uid:%{public}d, state:%{public}d",
506         data.bundleName.c_str(), data.uid, data.state);
507     auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
508     for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
509         const auto &bundleNames = it->second.bundleNames;
510         auto iter = std::find(bundleNames.begin(), bundleNames.end(), data.bundleName);
511         if ((bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr) {
512             it->first->OnAppStarted(data);
513         }
514     }
515 }
516 
HandleOnAppStopped(const std::shared_ptr<AppRunningRecord> & appRecord)517 void AppStateObserverManager::HandleOnAppStopped(const std::shared_ptr<AppRunningRecord> &appRecord)
518 {
519     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
520     if (appRecord == nullptr) {
521         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
522         return;
523     }
524 
525     AppStateData data = WrapAppStateData(appRecord, ApplicationState::APP_STATE_TERMINATED);
526     TAG_LOGD(AAFwkTag::APPMGR, "HandleOnAppStopped, bundle:%{public}s, uid:%{public}d, state:%{public}d",
527         data.bundleName.c_str(), data.uid, data.state);
528     auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
529     for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
530         const auto &bundleNames = it->second.bundleNames;
531         auto iter = std::find(bundleNames.begin(), bundleNames.end(), data.bundleName);
532         if ((bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr) {
533             it->first->OnAppStopped(data);
534         }
535     }
536 }
537 
HandleAppStateChanged(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state,bool needNotifyApp,bool isFromWindowFocusChanged)538 void AppStateObserverManager::HandleAppStateChanged(const std::shared_ptr<AppRunningRecord> &appRecord,
539     const ApplicationState state, bool needNotifyApp, bool isFromWindowFocusChanged)
540 {
541     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
542     if (appRecord == nullptr) {
543         return;
544     }
545     if (state == ApplicationState::APP_STATE_FOREGROUND || state == ApplicationState::APP_STATE_BACKGROUND) {
546         if (needNotifyApp && !isFromWindowFocusChanged) {
547             AppStateData data = WrapAppStateData(appRecord, state);
548             appRecord->GetSplitModeAndFloatingMode(data.isSplitScreenMode, data.isFloatingWindowMode);
549             auto appForegroundStateObserverMap = GetAppForegroundStateObserverMapCopy();
550             for (const auto &[observer, uid] : appForegroundStateObserverMap) {
551                 if (observer != nullptr) {
552                     observer->OnAppStateChanged(data);
553                 }
554             }
555         }
556         if (!AAFwk::UIExtensionUtils::IsUIExtension(appRecord->GetExtensionType()) &&
557             !AAFwk::UIExtensionUtils::IsWindowExtension(appRecord->GetExtensionType())) {
558             AppStateData data = WrapAppStateData(appRecord, state);
559             TAG_LOGD(AAFwkTag::APPMGR, "name:%{public}s, uid:%{public}d, state:%{public}d, notify:%{public}d",
560                 data.bundleName.c_str(), data.uid, data.state, needNotifyApp);
561             auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
562             for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
563                 const auto &bundleNames = it->second.bundleNames;
564                 auto iter = std::find(bundleNames.begin(), bundleNames.end(), data.bundleName);
565                 bool valid = (bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr;
566                 if (valid) {
567                     it->first->OnForegroundApplicationChanged(data);
568                 }
569                 if (valid && needNotifyApp) {
570                     it->first->OnAppStateChanged(data);
571                 }
572             }
573         }
574     }
575     if (state == ApplicationState::APP_STATE_CREATE || state == ApplicationState::APP_STATE_TERMINATED) {
576         AppStateData data = WrapAppStateData(appRecord, state);
577         TAG_LOGD(AAFwkTag::APPMGR, "OnApplicationStateChanged, name:%{public}s, uid:%{public}d, state:%{public}d",
578             data.bundleName.c_str(), data.uid, data.state);
579         auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
580         for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
581             const auto &bundleNames = it->second.bundleNames;
582             auto iter = std::find(bundleNames.begin(), bundleNames.end(), data.bundleName);
583             if ((bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr) {
584                 it->first->OnApplicationStateChanged(data);
585             }
586         }
587     }
588 }
589 
HandleStateChangedNotifyObserver(const AbilityStateData abilityStateData,bool isAbility,bool isFromWindowFocusChanged)590 void AppStateObserverManager::HandleStateChangedNotifyObserver(
591     const AbilityStateData abilityStateData, bool isAbility, bool isFromWindowFocusChanged)
592 {
593     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
594     TAG_LOGD(AAFwkTag::APPMGR,
595         "Handle state change, module:%{public}s, bundle:%{public}s, ability:%{public}s, state:%{public}d,"
596         "pid:%{public}d ,uid:%{public}d, abilityType:%{public}d, isAbility:%{public}d, callerBundleName:%{public}s,"
597         "callerAbilityName:%{public}s, isAtomicService:%{public}d, callerUid:%{public}d",
598         abilityStateData.moduleName.c_str(), abilityStateData.bundleName.c_str(),
599         abilityStateData.abilityName.c_str(), abilityStateData.abilityState,
600         abilityStateData.pid, abilityStateData.uid, abilityStateData.abilityType, isAbility,
601         abilityStateData.callerBundleName.c_str(), abilityStateData.callerAbilityName.c_str(),
602         abilityStateData.isAtomicService, abilityStateData.callerUid);
603     auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
604     for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
605         const auto &bundleNames = it->second.bundleNames;
606         auto iter = std::find(bundleNames.begin(), bundleNames.end(), abilityStateData.bundleName);
607         if ((bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr) {
608             if (isAbility) {
609                 it->first->OnAbilityStateChanged(abilityStateData);
610             } else {
611                 it->first->OnExtensionStateChanged(abilityStateData);
612             }
613         }
614     }
615 
616     if ((abilityStateData.abilityState == static_cast<int32_t>(AbilityState::ABILITY_STATE_FOREGROUND) ||
617             abilityStateData.abilityState == static_cast<int32_t>(AbilityState::ABILITY_STATE_BACKGROUND)) &&
618         isAbility && !isFromWindowFocusChanged) {
619         auto abilityForegroundObserverMap = GetAbilityForegroundObserverMapCopy();
620         for (auto &[observer, uid] : abilityForegroundObserverMap) {
621             if (observer != nullptr) {
622                 observer->OnAbilityStateChanged(abilityStateData);
623             }
624         }
625     }
626 }
627 
HandleOnAppProcessCreated(const std::shared_ptr<AppRunningRecord> & appRecord,bool isPreload)628 void AppStateObserverManager::HandleOnAppProcessCreated(const std::shared_ptr<AppRunningRecord> &appRecord,
629     bool isPreload)
630 {
631     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
632     if (!appRecord) {
633         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
634         return;
635     }
636     ProcessData data = WrapProcessData(appRecord);
637     data.isPreload = isPreload;
638     data.isPreloadModule = appRecord->GetNeedPreloadModule();
639     if (data.bundleName == XIAOYI_BUNDLE_NAME && data.extensionType == ExtensionAbilityType::SERVICE) {
640         TAG_LOGI(AAFwkTag::APPMGR, "change processType to NORMAL");
641         data.processType = ProcessType::NORMAL;
642     }
643     TAG_LOGI(AAFwkTag::APPMGR,
644         "bundle:%{public}s, pid:%{public}d, uid:%{public}d, processType:%{public}d, "
645         "extensionType:%{public}d, processName:%{public}s, renderUid:%{public}d, isTestMode:%{public}d, "
646         "callerPid:%{public}d, callerUid:%{public}d",
647         data.bundleName.c_str(), data.pid, data.uid, data.processType, data.extensionType, data.processName.c_str(),
648         data.renderUid, data.isTestMode, data.callerPid, data.callerUid);
649     HandleOnProcessCreated(data);
650 }
651 
HandleOnProcessResued(const std::shared_ptr<AppRunningRecord> & appRecord)652 void AppStateObserverManager::HandleOnProcessResued(const std::shared_ptr<AppRunningRecord> &appRecord)
653 {
654     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
655     if (!appRecord) {
656         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
657         return;
658     }
659     ProcessData data = WrapProcessData(appRecord);
660     TAG_LOGD(AAFwkTag::APPMGR, "Process Resued, bundle:%{public}s, pid:%{public}d, uid:%{public}d",
661         data.bundleName.c_str(), data.pid, data.uid);
662 
663     auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
664     for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
665         const auto &bundleNames = it->second.bundleNames;
666         auto iter = std::find(bundleNames.begin(), bundleNames.end(), data.bundleName);
667         if ((bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr) {
668             it->first->OnProcessReused(data);
669         }
670     }
671 }
672 
HandleOnRenderProcessCreated(const std::shared_ptr<RenderRecord> & renderRecord,const bool isPreload)673 void AppStateObserverManager::HandleOnRenderProcessCreated(const std::shared_ptr<RenderRecord> &renderRecord,
674     const bool isPreload)
675 {
676     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
677     if (!renderRecord) {
678         TAG_LOGE(AAFwkTag::APPMGR, "null renderRecord");
679         return;
680     }
681     ProcessData data = WrapRenderProcessData(renderRecord);
682     data.isPreload = isPreload;
683     TAG_LOGD(AAFwkTag::APPMGR,
684         "RenderProcess Create, bundle:%{public}s, pid:%{public}d, uid:%{public}d, processType:%{public}d, "
685         "processName:%{public}s, renderUid:%{public}d",
686         data.bundleName.c_str(), data.pid, data.uid, data.processType, data.processName.c_str(), data.renderUid);
687     HandleOnProcessCreated(data);
688 }
689 
690 #ifdef SUPPORT_CHILD_PROCESS
HandleOnChildProcessCreated(std::shared_ptr<ChildProcessRecord> childRecord)691 void AppStateObserverManager::HandleOnChildProcessCreated(std::shared_ptr<ChildProcessRecord> childRecord)
692 {
693     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
694     if (!childRecord) {
695         TAG_LOGE(AAFwkTag::APPMGR, "null childRecord");
696         return;
697     }
698     ProcessData data;
699     if (WrapChildProcessData(data, childRecord) != ERR_OK) {
700         TAG_LOGE(AAFwkTag::APPMGR, "WrapChildProcessData failed");
701         return;
702     }
703     TAG_LOGD(AAFwkTag::APPMGR,
704         "ChildProcess Create, bundleName:%{public}s, pid:%{public}d, uid:%{public}d, "
705         "processType:%{public}d, processName:%{public}s",
706         data.bundleName.c_str(), data.pid, data.uid, data.processType, data.processName.c_str());
707     HandleOnProcessCreated(data);
708 }
709 #endif // SUPPORT_CHILD_PROCESS
710 
HandleOnProcessCreated(const ProcessData & data)711 void AppStateObserverManager::HandleOnProcessCreated(const ProcessData &data)
712 {
713     auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
714     for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
715         const auto &bundleNames = it->second.bundleNames;
716         auto iter = std::find(bundleNames.begin(), bundleNames.end(), data.bundleName);
717         if ((bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr) {
718             it->first->OnProcessCreated(data);
719         }
720     }
721 }
722 
HandleOnProcessStateChanged(const std::shared_ptr<AppRunningRecord> & appRecord)723 void AppStateObserverManager::HandleOnProcessStateChanged(const std::shared_ptr<AppRunningRecord> &appRecord)
724 {
725     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
726     if (!appRecord) {
727         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
728         return;
729     }
730     ProcessData data = WrapProcessData(appRecord);
731     if (data.bundleName == XIAOYI_BUNDLE_NAME && data.extensionType == ExtensionAbilityType::SERVICE) {
732         TAG_LOGI(AAFwkTag::APPMGR, "change processType to NORMAL");
733         data.processType = ProcessType::NORMAL;
734     }
735     TAG_LOGD(AAFwkTag::APPMGR,
736         "bundle:%{public}s, pid:%{public}d, uid:%{public}d, state:%{public}d, "
737         "isContinuousTask:%{public}d, gpuPid:%{public}d",
738         data.bundleName.c_str(), data.pid, data.uid, data.state, data.isContinuousTask, data.gpuPid);
739     auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
740     for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
741         const auto &bundleNames = it->second.bundleNames;
742         auto iter = std::find(bundleNames.begin(), bundleNames.end(), data.bundleName);
743         if ((bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr) {
744             it->first->OnProcessStateChanged(data);
745         }
746     }
747 }
748 
HandleOnWindowShow(const std::shared_ptr<AppRunningRecord> & appRecord)749 void AppStateObserverManager::HandleOnWindowShow(const std::shared_ptr<AppRunningRecord> &appRecord)
750 {
751     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
752     if (!appRecord) {
753         TAG_LOGE(AAFwkTag::APPMGR, "app record is null");
754         return;
755     }
756     ProcessData data = WrapProcessData(appRecord);
757     TAG_LOGD(AAFwkTag::APPMGR,
758         "bundle:%{public}s, pid:%{public}d, uid:%{public}d, state:%{public}d, "
759         "isContinuousTask:%{public}d, gpuPid:%{public}d",
760         data.bundleName.c_str(), data.pid, data.uid, data.state, data.isContinuousTask, data.gpuPid);
761     auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
762     for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
763         const auto &bundleNames = it->second.bundleNames;
764         auto iter = std::find(bundleNames.begin(), bundleNames.end(), data.bundleName);
765         if ((bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr) {
766             it->first->OnWindowShow(data);
767         }
768     }
769 }
770 
HandleOnWindowHidden(const std::shared_ptr<AppRunningRecord> & appRecord)771 void AppStateObserverManager::HandleOnWindowHidden(const std::shared_ptr<AppRunningRecord> &appRecord)
772 {
773     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
774     if (!appRecord) {
775         TAG_LOGE(AAFwkTag::APPMGR, "app record is null");
776         return;
777     }
778     ProcessData data = WrapProcessData(appRecord);
779     TAG_LOGD(AAFwkTag::APPMGR,
780         "bundle:%{public}s, pid:%{public}d, uid:%{public}d, state:%{public}d, "
781         "isContinuousTask:%{public}d, gpuPid:%{public}d",
782         data.bundleName.c_str(), data.pid, data.uid, data.state, data.isContinuousTask, data.gpuPid);
783     auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
784     for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
785         const auto &bundleNames = it->second.bundleNames;
786         auto iter = std::find(bundleNames.begin(), bundleNames.end(), data.bundleName);
787         if ((bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr) {
788             it->first->OnWindowHidden(data);
789         }
790     }
791 }
792 
HandleOnAppProcessDied(const std::shared_ptr<AppRunningRecord> & appRecord)793 void AppStateObserverManager::HandleOnAppProcessDied(const std::shared_ptr<AppRunningRecord> &appRecord)
794 {
795     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
796     if (!appRecord) {
797         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
798         return;
799     }
800     ProcessData data = WrapProcessData(appRecord);
801     TAG_LOGD(AAFwkTag::APPMGR, "Process died, bundle:%{public}s, pid:%{public}d, uid:%{public}d, renderUid:%{public}d,"
802         " exitReason:%{public}d, exitMsg:%{public}s",
803         data.bundleName.c_str(), data.pid, data.uid, data.renderUid, data.exitReason, data.exitMsg.c_str());
804     HandleOnProcessDied(data);
805 }
806 
HandleOnRenderProcessDied(const std::shared_ptr<RenderRecord> & renderRecord)807 void AppStateObserverManager::HandleOnRenderProcessDied(const std::shared_ptr<RenderRecord> &renderRecord)
808 {
809     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
810     if (!renderRecord) {
811         TAG_LOGE(AAFwkTag::APPMGR, "null renderRecord");
812         return;
813     }
814     ProcessData data = WrapRenderProcessData(renderRecord);
815     TAG_LOGD(AAFwkTag::APPMGR,
816         "Render Process died, bundle:%{public}s, pid:%{public}d, uid:%{public}d, renderUid:%{public}d",
817         data.bundleName.c_str(), data.pid, data.uid, data.renderUid);
818     HandleOnProcessDied(data);
819 }
820 
821 #ifdef SUPPORT_CHILD_PROCESS
HandleOnChildProcessDied(std::shared_ptr<ChildProcessRecord> childRecord)822 void AppStateObserverManager::HandleOnChildProcessDied(std::shared_ptr<ChildProcessRecord> childRecord)
823 {
824     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
825     if (!childRecord) {
826         TAG_LOGE(AAFwkTag::APPMGR, "null childRecord");
827         return;
828     }
829     ProcessData data;
830     if (WrapChildProcessData(data, childRecord) != ERR_OK) {
831         TAG_LOGE(AAFwkTag::APPMGR, "WrapChildProcessData failed");
832         return;
833     }
834     TAG_LOGD(AAFwkTag::APPMGR,
835         "ChildProcess died, bundleName:%{public}s, pid:%{public}d, uid:%{public}d, "
836         "processType:%{public}d, processName:%{public}s",
837         data.bundleName.c_str(), data.pid, data.uid, data.processType, data.processName.c_str());
838     HandleOnProcessDied(data);
839 }
840 #endif // SUPPORT_CHILD_PROCESS
841 
HandleOnProcessDied(const ProcessData & data)842 void AppStateObserverManager::HandleOnProcessDied(const ProcessData &data)
843 {
844     auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
845     for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
846         const auto &bundleNames = it->second.bundleNames;
847         auto iter = std::find(bundleNames.begin(), bundleNames.end(), data.bundleName);
848         if ((bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr) {
849             it->first->OnProcessDied(data);
850         }
851     }
852 }
853 
WrapProcessData(const std::shared_ptr<AppRunningRecord> & appRecord)854 ProcessData AppStateObserverManager::WrapProcessData(const std::shared_ptr<AppRunningRecord> &appRecord)
855 {
856     ProcessData processData;
857     processData.bundleName = appRecord->GetBundleName();
858     processData.pid = appRecord->GetPid();
859     processData.uid = appRecord->GetUid();
860     auto applicationInfo = appRecord->GetApplicationInfo();
861     if (applicationInfo) {
862         processData.accessTokenId = applicationInfo->accessTokenId;
863     }
864     processData.state = static_cast<AppProcessState>(appRecord->GetState());
865     processData.isContinuousTask = appRecord->IsContinuousTask();
866     processData.isKeepAlive = appRecord->IsKeepAliveApp();
867     processData.isFocused = appRecord->GetFocusFlag();
868     processData.requestProcCode = appRecord->GetRequestProcCode();
869     processData.processChangeReason = static_cast<int32_t>(appRecord->GetProcessChangeReason());
870     processData.processName = appRecord->GetProcessName();
871     processData.extensionType = appRecord->GetExtensionType();
872     processData.processType = appRecord->GetProcessType();
873     if (appRecord->GetUserTestInfo() != nullptr && system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
874         processData.isTestMode = true;
875     }
876     processData.exitReason = appRecord->GetExitReason();
877     processData.exitMsg = appRecord->GetExitMsg();
878     processData.gpuPid = appRecord->GetGPUPid();
879     processData.callerPid = appRecord->GetCallerPid();
880     processData.callerUid = appRecord->GetCallerUid();
881     return processData;
882 }
883 
WrapRenderProcessData(const std::shared_ptr<RenderRecord> & renderRecord)884 ProcessData AppStateObserverManager::WrapRenderProcessData(const std::shared_ptr<RenderRecord> &renderRecord)
885 {
886     ProcessData processData;
887     processData.bundleName = renderRecord->GetHostBundleName();
888     processData.pid = renderRecord->GetPid();
889     processData.uid = renderRecord->GetHostUid();
890     processData.renderUid = renderRecord->GetUid();
891     processData.processName = renderRecord->GetProcessName();
892     processData.processType = renderRecord->GetProcessType();
893     processData.hostPid = renderRecord->GetHostPid();
894     return processData;
895 }
896 
897 #ifdef SUPPORT_CHILD_PROCESS
WrapChildProcessData(ProcessData & processData,std::shared_ptr<ChildProcessRecord> childRecord)898 int32_t AppStateObserverManager::WrapChildProcessData(ProcessData &processData,
899     std::shared_ptr<ChildProcessRecord> childRecord)
900 {
901     if (!childRecord) {
902         TAG_LOGE(AAFwkTag::APPMGR, "null childRecord");
903         return ERR_INVALID_VALUE;
904     }
905     auto hostRecord = childRecord->GetHostRecord();
906     if (!hostRecord) {
907         TAG_LOGE(AAFwkTag::APPMGR, "null hostRecord");
908         return ERR_INVALID_VALUE;
909     }
910     processData.bundleName = hostRecord->GetBundleName();
911     processData.uid = hostRecord->GetUid();
912     processData.hostPid = childRecord->GetHostPid();
913     processData.pid = childRecord->GetPid();
914     processData.childUid = childRecord->GetUid();
915     processData.processName = childRecord->GetProcessName();
916     processData.processType = childRecord->GetProcessType();
917     return ERR_OK;
918 }
919 #endif // SUPPORT_CHILD_PROCESS
920 
ObserverExist(const sptr<IRemoteBroker> & observer)921 bool AppStateObserverManager::ObserverExist(const sptr<IRemoteBroker> &observer)
922 {
923     if (observer == nullptr) {
924         TAG_LOGE(AAFwkTag::APPMGR, "null observer");
925         return false;
926     }
927     std::lock_guard lockRegister(observerLock_);
928     for (auto it = appStateObserverMap_.begin(); it != appStateObserverMap_.end(); ++it) {
929         if (it->first->AsObject() == observer->AsObject()) {
930             return true;
931         }
932     }
933     return false;
934 }
935 
IsAbilityForegroundObserverExist(const sptr<IRemoteBroker> & observer)936 bool AppStateObserverManager::IsAbilityForegroundObserverExist(const sptr<IRemoteBroker> &observer)
937 {
938     if (observer == nullptr) {
939         TAG_LOGE(AAFwkTag::APPMGR, "null observer");
940         return false;
941     }
942     std::lock_guard lockRegister(abilityForegroundObserverLock_);
943     for (const auto &[it, uid] : abilityForegroundObserverMap_) {
944         if (it != nullptr && it->AsObject() == observer->AsObject()) {
945             return true;
946         }
947     }
948     return false;
949 }
950 
IsAppForegroundObserverExist(const sptr<IRemoteBroker> & observer)951 bool AppStateObserverManager::IsAppForegroundObserverExist(const sptr<IRemoteBroker> &observer)
952 {
953     if (observer == nullptr) {
954         TAG_LOGE(AAFwkTag::APPMGR, "null observer");
955         return false;
956     }
957     std::lock_guard lockRegister(appForegroundObserverLock_);
958     for (const auto &[it, uid] : appForegroundStateObserverMap_) {
959         if (it != nullptr && it->AsObject() == observer->AsObject()) {
960             return true;
961         }
962     }
963     return false;
964 }
965 
AddObserverDeathRecipient(const sptr<IRemoteBroker> & observer,const ObserverType & type)966 void AppStateObserverManager::AddObserverDeathRecipient(const sptr<IRemoteBroker> &observer, const ObserverType &type)
967 {
968     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
969     TAG_LOGD(AAFwkTag::APPMGR, "Add observer death recipient begin.");
970     if (observer == nullptr || observer->AsObject() == nullptr) {
971         TAG_LOGE(AAFwkTag::APPMGR, "null observer");
972         return;
973     }
974     std::lock_guard lock(recipientMapMutex_);
975     auto it = recipientMap_.find(observer->AsObject());
976     if (it != recipientMap_.end()) {
977         TAG_LOGE(AAFwkTag::APPMGR, "Death recipient added");
978         return;
979     } else {
980         std::weak_ptr<AppStateObserverManager> thisWeakPtr(shared_from_this());
981         sptr<IRemoteObject::DeathRecipient> deathRecipient = nullptr;
982         auto deathRecipientFunc = [thisWeakPtr, type](const wptr<IRemoteObject> &remote) {
983             auto appStateObserverManager = thisWeakPtr.lock();
984             if (appStateObserverManager) {
985                 appStateObserverManager->OnObserverDied(remote, type);
986             }
987         };
988         if (type == ObserverType::APPLICATION_STATE_OBSERVER) {
989             deathRecipient = new (std::nothrow) ApplicationStateObserverRecipient(deathRecipientFunc);
990         } else if (type == ObserverType::APP_FOREGROUND_STATE_OBSERVER) {
991             deathRecipient = new (std::nothrow) AppForegroundStateObserverRecipient(deathRecipientFunc);
992         } else if (type == ObserverType::ABILITY_FOREGROUND_STATE_OBSERVER) {
993             deathRecipient = new (std::nothrow) AbilityForegroundStateObserverRecipient(deathRecipientFunc);
994         } else {
995             TAG_LOGW(AAFwkTag::APPMGR, "null ObserverType");
996             return;
997         }
998         if (deathRecipient == nullptr) {
999             TAG_LOGE(AAFwkTag::APPMGR, "null deathRecipient");
1000             return;
1001         }
1002         if (!observer->AsObject()->AddDeathRecipient(deathRecipient)) {
1003             TAG_LOGE(AAFwkTag::APPMGR, "AddDeathRecipient failed");
1004         }
1005         recipientMap_.emplace(observer->AsObject(), deathRecipient);
1006     }
1007 }
1008 
RemoveObserverDeathRecipient(const sptr<IRemoteBroker> & observer)1009 void AppStateObserverManager::RemoveObserverDeathRecipient(const sptr<IRemoteBroker> &observer)
1010 {
1011     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1012     TAG_LOGD(AAFwkTag::APPMGR, "Remove observer death recipient begin.");
1013     if (observer == nullptr || observer->AsObject() == nullptr) {
1014         TAG_LOGE(AAFwkTag::APPMGR, "null observer");
1015         return;
1016     }
1017     std::lock_guard lock(recipientMapMutex_);
1018     auto it = recipientMap_.find(observer->AsObject());
1019     if (it != recipientMap_.end()) {
1020         it->first->RemoveDeathRecipient(it->second);
1021         recipientMap_.erase(it);
1022         return;
1023     }
1024 }
1025 
AddObserverCount(int32_t uid)1026 void AppStateObserverManager::AddObserverCount(int32_t uid)
1027 {
1028     std::lock_guard lock(observerCountMapMutex_);
1029     auto it = observerCountMap_.find(uid);
1030     if (it == observerCountMap_.end()) {
1031         observerCountMap_.emplace(uid, 1);
1032     } else {
1033         it->second++;
1034         if (it->second > OBSERVER_UID_COUNT_LOG) {
1035             TAG_LOGW(AAFwkTag::APPMGR, "too many observer uid: %{public}d, count: %{public}d", uid, it->second);
1036         }
1037         observerAmount_++;
1038         if (observerAmount_ % OBSERVER_AMOUNT_COUNT_LOG == 0) {
1039             for (const auto &[uid, count] : observerCountMap_) {
1040                 TAG_LOGW(AAFwkTag::APPMGR, "observer overview uid: %{public}d, count: %{public}d", uid, count);
1041             }
1042         }
1043     }
1044 }
1045 
DecreaseObserverCount(int32_t uid)1046 void AppStateObserverManager::DecreaseObserverCount(int32_t uid)
1047 {
1048     std::lock_guard lock(observerCountMapMutex_);
1049     auto it = observerCountMap_.find(uid);
1050     if (it == observerCountMap_.end()) {
1051         return;
1052     }
1053     it->second--;
1054     if (it->second <= 0) {
1055         observerCountMap_.erase(it);
1056     }
1057     observerAmount_--;
1058 }
1059 
GetAppStateObserverMapCopy()1060 AppStateObserverMap AppStateObserverManager::GetAppStateObserverMapCopy()
1061 {
1062     std::lock_guard lock(observerLock_);
1063     return appStateObserverMap_;
1064 }
1065 
GetAppForegroundStateObserverMapCopy()1066 AppForegroundStateObserverMap AppStateObserverManager::GetAppForegroundStateObserverMapCopy()
1067 {
1068     std::lock_guard lock(appForegroundObserverLock_);
1069     return appForegroundStateObserverMap_;
1070 }
1071 
GetAbilityForegroundObserverMapCopy()1072 AbilityForegroundObserverMap AppStateObserverManager::GetAbilityForegroundObserverMapCopy()
1073 {
1074     std::lock_guard lock(abilityForegroundObserverLock_);
1075     return abilityForegroundObserverMap_;
1076 }
1077 
OnObserverDied(const wptr<IRemoteObject> & remote,const ObserverType & type)1078 void AppStateObserverManager::OnObserverDied(const wptr<IRemoteObject> &remote, const ObserverType &type)
1079 {
1080     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1081     TAG_LOGD(AAFwkTag::APPMGR, "OnObserverDied");
1082     auto object = remote.promote();
1083     if (object == nullptr) {
1084         TAG_LOGE(AAFwkTag::APPMGR, "null observer");
1085         return;
1086     }
1087 
1088     if (type == ObserverType::APPLICATION_STATE_OBSERVER) {
1089         sptr<IApplicationStateObserver> observer = iface_cast<IApplicationStateObserver>(object);
1090         UnregisterApplicationStateObserver(observer);
1091     } else if (type == ObserverType::ABILITY_FOREGROUND_STATE_OBSERVER) {
1092         sptr<IAbilityForegroundStateObserver> observer = iface_cast<IAbilityForegroundStateObserver>(object);
1093         UnregisterAbilityForegroundStateObserver(observer);
1094     } else if (type == ObserverType::APP_FOREGROUND_STATE_OBSERVER) {
1095         sptr<IAppForegroundStateObserver> observer = iface_cast<IAppForegroundStateObserver>(object);
1096         UnregisterAppForegroundStateObserver(observer);
1097     } else {
1098         TAG_LOGW(AAFwkTag::APPMGR, "null ObserverType");
1099         return;
1100     }
1101 }
1102 
WrapAppStateData(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state)1103 AppStateData AppStateObserverManager::WrapAppStateData(const std::shared_ptr<AppRunningRecord> &appRecord,
1104     const ApplicationState state)
1105 {
1106     AppStateData appStateData;
1107     appStateData.pid = appRecord->GetPid();
1108     appStateData.bundleName = appRecord->GetBundleName();
1109     appStateData.state = static_cast<int32_t>(state);
1110     appStateData.uid = appRecord->GetUid();
1111     appStateData.extensionType = appRecord->GetExtensionType();
1112     appStateData.isPreloadModule = appRecord->GetNeedPreloadModule();
1113     if (appRecord->GetApplicationInfo() != nullptr) {
1114         appStateData.accessTokenId = static_cast<uint32_t>(appRecord->GetApplicationInfo()->accessTokenId);
1115     }
1116     appStateData.isFocused = appRecord->GetFocusFlag();
1117     auto renderRecordMap = appRecord->GetRenderRecordMap();
1118     if (!renderRecordMap.empty()) {
1119         for (auto iter : renderRecordMap) {
1120             auto renderRecord = iter.second;
1121             if (renderRecord != nullptr) {
1122                 appStateData.renderPids.emplace_back(renderRecord->GetPid());
1123             }
1124         }
1125     }
1126     std::shared_ptr<RemoteClientManager> remoteClientManager = std::make_shared<RemoteClientManager>();
1127     auto bundleMgr = remoteClientManager->GetBundleManagerHelper();
1128     std::string callerBundleName;
1129     if (bundleMgr != nullptr &&
1130         IN_PROCESS_CALL(bundleMgr->GetNameForUid(appRecord->GetCallerUid(), callerBundleName)) == ERR_OK) {
1131         appStateData.callerBundleName = callerBundleName;
1132     } else {
1133         appStateData.callerBundleName = "";
1134     }
1135     appStateData.appIndex = appRecord->GetAppIndex();
1136     TAG_LOGD(AAFwkTag::APPMGR, "Handle state change, bundle:%{public}s, state:%{public}d,"
1137         "pid:%{public}d ,uid:%{public}d, isFocused:%{public}d, callerBUndleName: %{public}s, appIndex:%{public}d",
1138         appStateData.bundleName.c_str(), appStateData.state, appStateData.pid, appStateData.uid,
1139         appStateData.isFocused, appStateData.callerBundleName.c_str(), appStateData.appIndex);
1140     return appStateData;
1141 }
1142 
OnPageShow(const PageStateData pageStateData)1143 void AppStateObserverManager::OnPageShow(const PageStateData pageStateData)
1144 {
1145     TAG_LOGD(AAFwkTag::APPMGR, "call");
1146     if (handler_ == nullptr) {
1147         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
1148         return;
1149     }
1150 
1151     auto task = [weak = weak_from_this(), pageStateData]() {
1152         auto self = weak.lock();
1153         if (self == nullptr) {
1154             TAG_LOGE(AAFwkTag::APPMGR, "null self");
1155             return;
1156         }
1157         TAG_LOGD(AAFwkTag::APPMGR, "OnProcessCreated come.");
1158         self->HandleOnPageShow(pageStateData);
1159     };
1160     handler_->SubmitTask(task);
1161 }
1162 
OnPageHide(const PageStateData pageStateData)1163 void AppStateObserverManager::OnPageHide(const PageStateData pageStateData)
1164 {
1165     TAG_LOGD(AAFwkTag::APPMGR, "call");
1166     if (handler_ == nullptr) {
1167         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
1168         return;
1169     }
1170 
1171     auto task = [weak = weak_from_this(), pageStateData]() {
1172         auto self = weak.lock();
1173         if (self == nullptr) {
1174             TAG_LOGE(AAFwkTag::APPMGR, "null self");
1175             return;
1176         }
1177         TAG_LOGD(AAFwkTag::APPMGR, "OnProcessCreated come.");
1178         self->HandleOnPageHide(pageStateData);
1179     };
1180     handler_->SubmitTask(task);
1181 }
1182 
HandleOnPageShow(const PageStateData pageStateData)1183 void AppStateObserverManager::HandleOnPageShow(const PageStateData pageStateData)
1184 {
1185     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1186     auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
1187     for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
1188         const auto &bundleNames = it->second.bundleNames;
1189         auto iter = std::find(bundleNames.begin(), bundleNames.end(), pageStateData.bundleName);
1190         if ((bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr) {
1191             it->first->OnPageShow(pageStateData);
1192         }
1193     }
1194 }
1195 
HandleOnPageHide(const PageStateData pageStateData)1196 void AppStateObserverManager::HandleOnPageHide(const PageStateData pageStateData)
1197 {
1198     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1199     auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
1200     for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
1201         const auto &bundleNames = it->second.bundleNames;
1202         auto iter = std::find(bundleNames.begin(), bundleNames.end(), pageStateData.bundleName);
1203         if ((bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr) {
1204             it->first->OnPageHide(pageStateData);
1205         }
1206     }
1207 }
1208 
OnAppCacheStateChanged(const std::shared_ptr<AppRunningRecord> & appRecord,ApplicationState state)1209 void AppStateObserverManager::OnAppCacheStateChanged(const std::shared_ptr<AppRunningRecord> &appRecord,
1210     ApplicationState state)
1211 {
1212     if (handler_ == nullptr) {
1213         TAG_LOGE(AAFwkTag::APPMGR, "null handler");
1214         return;
1215     }
1216 
1217     auto task = [weak = weak_from_this(), appRecord, state]() {
1218         auto self = weak.lock();
1219         if (self == nullptr) {
1220             TAG_LOGE(AAFwkTag::APPMGR, "null self");
1221             return;
1222         }
1223         TAG_LOGD(AAFwkTag::APPMGR, "OnAppCacheStateChanged come.");
1224         self->HandleOnAppCacheStateChanged(appRecord, state);
1225     };
1226     handler_->SubmitTask(task);
1227 }
1228 
HandleOnAppCacheStateChanged(const std::shared_ptr<AppRunningRecord> & appRecord,ApplicationState state)1229 void AppStateObserverManager::HandleOnAppCacheStateChanged(const std::shared_ptr<AppRunningRecord> &appRecord,
1230     ApplicationState state)
1231 {
1232     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1233     if (appRecord == nullptr) {
1234         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
1235         return;
1236     }
1237 
1238     AppStateData data = WrapAppStateData(appRecord, state);
1239     data.isSpecifyTokenId = appRecord->GetAssignTokenId() > 0 ? true : false;
1240     TAG_LOGD(AAFwkTag::APPMGR, "HandleOnAppCacheStateChanged, bundle:%{public}s, uid:%{public}d, state:%{public}d",
1241         data.bundleName.c_str(), data.uid, data.state);
1242     auto appStateObserverMapCopy = GetAppStateObserverMapCopy();
1243     for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) {
1244         const auto &bundleNames = it->second.bundleNames;
1245         auto iter = std::find(bundleNames.begin(), bundleNames.end(), data.bundleName);
1246         if ((bundleNames.empty() || iter != bundleNames.end()) && it->first != nullptr) {
1247             it->first->OnAppCacheStateChanged(data);
1248         }
1249     }
1250 }
1251 }  // namespace AppExecFwk
1252 }  // namespace OHOS
1253