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