1 /*
2 * Copyright (c) 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 "cj_application_state_change_callback.h"
17
18 #include "hilog_tag_wrapper.h"
19
20 namespace OHOS {
21 namespace AbilityRuntime {
22
23 int32_t CjApplicationStateChangeCallback::serialNumber_ = 0;
24
CjApplicationStateChangeCallback()25 CjApplicationStateChangeCallback::CjApplicationStateChangeCallback()
26 {
27 }
28
NotifyApplicationForeground()29 void CjApplicationStateChangeCallback::NotifyApplicationForeground()
30 {
31 TAG_LOGD(AAFwkTag::APPKIT, "MethodName = onApplicationForeground");
32 for (auto &callback : foregroundCallbacks_) {
33 if (callback.second) {
34 callback.second();
35 }
36 }
37 }
38
NotifyApplicationBackground()39 void CjApplicationStateChangeCallback::NotifyApplicationBackground()
40 {
41 TAG_LOGD(AAFwkTag::APPKIT, "MethodName = onApplicationBackground");
42 for (auto &callback : backgroundCallbacks_) {
43 if (callback.second) {
44 callback.second();
45 }
46 }
47 }
48
Register(std::function<void (void)> foregroundCallback,std::function<void (void)> backgroundCallback)49 int32_t CjApplicationStateChangeCallback::Register(std::function<void(void)> foregroundCallback,
50 std::function<void(void)> backgroundCallback)
51 {
52 int32_t callbackId = serialNumber_;
53 if (serialNumber_ < INT32_MAX) {
54 serialNumber_++;
55 } else {
56 serialNumber_ = 0;
57 }
58 foregroundCallbacks_.emplace(callbackId, foregroundCallback);
59 backgroundCallbacks_.emplace(callbackId, backgroundCallback);
60 return callbackId;
61 }
62
UnRegister(int32_t callbackId)63 bool CjApplicationStateChangeCallback::UnRegister(int32_t callbackId)
64 {
65 if (callbackId < 0) {
66 TAG_LOGI(AAFwkTag::APPKIT, "delete all callback");
67 foregroundCallbacks_.clear();
68 backgroundCallbacks_.clear();
69 return true;
70 }
71 auto it = foregroundCallbacks_.find(callbackId);
72 if (it == foregroundCallbacks_.end()) {
73 TAG_LOGE(AAFwkTag::APPKIT, "callbackId: %{public}d is not in callbacks_", callbackId);
74 return false;
75 }
76 TAG_LOGD(AAFwkTag::APPKIT, "callbacks_.callbackId : %{public}d", it->first);
77 return foregroundCallbacks_.erase(callbackId) == 1 && backgroundCallbacks_.erase(callbackId) == 1;
78 }
79
IsEmpty() const80 bool CjApplicationStateChangeCallback::IsEmpty() const
81 {
82 return foregroundCallbacks_.empty() && backgroundCallbacks_.empty();
83 }
84 } // namespace AbilityRuntime
85 } // namespace OHOS