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 #ifndef AV_SESSION_APP_MANAGER_ADAPTER_H
17 #define AV_SESSION_APP_MANAGER_ADAPTER_H
18 
19 #include <functional>
20 #include <mutex>
21 #include <set>
22 #include "app_mgr_client.h"
23 #include "app_state_callback_host.h"
24 
25 namespace OHOS::AVSession {
26 class AppManagerAdapter {
27 public:
28     static AppManagerAdapter& GetInstance();
29 
30     ~AppManagerAdapter();
31 
32     void Init();
33 
34     bool IsAppBackground(int32_t uid, int32_t pid);
35 
36     void SetAppBackgroundStateObserver(const std::function<void(int32_t, int32_t)>& observer);
37 
38     void AddObservedApp(int32_t uid);
39 
40     void RemoveObservedApp(int32_t uid);
41 
42     void HandleAppStateChanged(const AppExecFwk::AppProcessData& appProcessData);
43 
44     void SetServiceCallbackForAppStateChange(const std::function<void(int uid, int state)>& callback);
45 
46 private:
47     AppManagerAdapter();
48 
49     AppExecFwk::AppMgrClient appManager_;
50     sptr<AppExecFwk::IAppStateCallback> appStateCallback_;
51     std::function<void(int32_t, int32_t)> backgroundObserver_;
52     std::recursive_mutex uidLock_;
53     std::set<int32_t> observedAppUIDs_;
54     std::function<void(int uid, int state)> serviceCallbackForAppStateChange_;
55 
56     static constexpr int RETRY_COUNT_MAX = 5;
57     static constexpr int RETRY_INTERVAL_TIME = 500;
58 };
59 
60 class AVSessionAppStateCallback : public AppExecFwk::AppStateCallbackHost {
61 public:
62     void OnAppStateChanged(const AppExecFwk::AppProcessData&) override;
63 };
64 }
65 #endif // AV_SESSION_APP_MANAGER_ADAPTER_H