1 /*
2  * Copyright (c) 2022 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 "config_change_observer.h"
17 
18 #include "bg_continuous_task_mgr.h"
19 #include "continuous_task_log.h"
20 
21 namespace OHOS {
22 namespace BackgroundTaskMgr {
ConfigChangeObserver(const std::shared_ptr<AppExecFwk::EventHandler> handler,const std::shared_ptr<BgContinuousTaskMgr> taskMgr)23 ConfigChangeObserver::ConfigChangeObserver(const std::shared_ptr<AppExecFwk::EventHandler> handler,
24     const std::shared_ptr<BgContinuousTaskMgr> taskMgr)
25 {
26     handler_ = handler;
27     taskMgr_ = taskMgr;
28 }
29 
CheckExpired()30 bool ConfigChangeObserver::CheckExpired()
31 {
32     if (handler_.expired()) {
33         BGTASK_LOGE("ConfigChangeObserver handler expired");
34         return false;
35     }
36     if (taskMgr_.expired()) {
37         BGTASK_LOGE("ConfigChangeObserver taskMgr expired");
38         return false;
39     }
40     return true;
41 }
42 
OnConfigurationUpdated(const AppExecFwk::Configuration & configuration)43 void ConfigChangeObserver::OnConfigurationUpdated(const AppExecFwk::Configuration &configuration)
44 {
45     if (!CheckExpired()) {
46         return;
47     }
48 
49     auto task = [wp = weak_from_this(), configuration]() {
50         auto sp = wp.lock();
51         if (sp) {
52             auto taskMgr = sp->taskMgr_.lock();
53             if (taskMgr) {
54                 taskMgr->OnConfigurationChanged(configuration);
55             }
56         }
57     };
58 
59     auto handler = handler_.lock();
60     if (handler == nullptr) {
61         return;
62     }
63     handler->PostTask(task);
64 }
65 }
66 }