1 /*
2  * Copyright (c) 2023 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 #ifndef LOG_TAG
16 #define LOG_TAG "CallbackHandlerInner"
17 #endif
18 
19 #include "callback_handler.h"
20 #include "event_handler.h"
21 #include "event_runner.h"
22 #include "audio_service_log.h"
23 
24 namespace OHOS {
25 namespace AudioStandard {
26 using namespace std;
27 class CallbackHandlerInner : public CallbackHandler, public AppExecFwk::EventHandler {
28 public:
29     explicit CallbackHandlerInner(std::shared_ptr<IHandler> iHandler);
30     ~CallbackHandlerInner();
31 
32     void SendCallbackEvent(uint32_t eventCode, int64_t data) override;
33 
34     void ReleaseEventRunner() override;
35 
36 protected:
37     void ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) override;
38 
39 private:
40     std::weak_ptr<IHandler> iHandler_;
41 };
42 
GetInstance(std::shared_ptr<IHandler> iHandler)43 std::shared_ptr<CallbackHandler> CallbackHandler::GetInstance(std::shared_ptr<IHandler> iHandler)
44 {
45     return std::make_shared<CallbackHandlerInner>(iHandler);
46 }
47 
CallbackHandlerInner(std::shared_ptr<IHandler> iHandler)48 CallbackHandlerInner::CallbackHandlerInner(std::shared_ptr<IHandler> iHandler)
49     : AppExecFwk::EventHandler(AppExecFwk::EventRunner::Create("OS_AudioStateCB"))
50 {
51     iHandler_ = iHandler;
52 }
53 
~CallbackHandlerInner()54 CallbackHandlerInner::~CallbackHandlerInner()
55 {
56     AUDIO_WARNING_LOG("Destructor callback handler inner");
57 }
58 
SendCallbackEvent(uint32_t eventCode, int64_t data)59 void CallbackHandlerInner::SendCallbackEvent(uint32_t eventCode, int64_t data)
60 {
61     SendEvent(AppExecFwk::InnerEvent::Get(eventCode, data));
62 }
63 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event)64 void CallbackHandlerInner::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event)
65 {
66     uint32_t eventCode = event->GetInnerEventId();
67     int64_t data = event->GetParam();
68     std::shared_ptr<IHandler> handler = iHandler_.lock();
69     if (handler == nullptr) {
70         AUDIO_ERR_LOG("iHandler is nullptr");
71         return;
72     }
73     handler->OnHandle(eventCode, data);
74 }
75 
ReleaseEventRunner()76 void CallbackHandlerInner::ReleaseEventRunner()
77 {
78     SetEventRunner(nullptr);
79 }
80 } // namespace AudioStandard
81 } // namespace OHOS
82