OSDN Git Service

db7197ac84e08e9598cc2e2c5c0e3d0d55f4ad90
[android-x86/system-connectivity-wificond.git] / looper_backed_event_loop.cpp
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <looper_backed_event_loop.h>
18
19 #include <utils/Looper.h>
20 #include <utils/Timers.h>
21
22 namespace {
23
24 class EventLoopCallback : public android::MessageHandler {
25  public:
26   explicit EventLoopCallback(const std::function<void()>& callback)
27       : callback_(callback) {
28   }
29
30   ~EventLoopCallback() override = default;
31
32   virtual void handleMessage(const android::Message& message) {
33     callback_();
34   }
35
36  private:
37   const std::function<void()> callback_;
38
39   DISALLOW_COPY_AND_ASSIGN(EventLoopCallback);
40 };
41
42 }  // namespace
43
44 namespace android {
45 namespace wificond {
46
47
48 LooperBackedEventLoop::LooperBackedEventLoop()
49     : should_continue_(true) {
50   looper_ = android::Looper::prepare(Looper::PREPARE_ALLOW_NON_CALLBACKS);
51 }
52
53 LooperBackedEventLoop::~LooperBackedEventLoop() {
54 }
55
56 void LooperBackedEventLoop::PostTask(const std::function<void()>& callback) {
57   sp<android::MessageHandler> event_loop_callback =
58       new EventLoopCallback(callback);
59   looper_->sendMessage(event_loop_callback, NULL);
60 }
61
62 void LooperBackedEventLoop::PostDelayedTask(
63     const std::function<void()>& callback,
64     int64_t delay_ms) {
65   sp<android::MessageHandler> looper_callback = new EventLoopCallback(callback);
66   looper_->sendMessageDelayed(ms2ns(delay_ms), looper_callback, NULL);
67 }
68
69 void LooperBackedEventLoop::Poll() {
70   while (should_continue_) {
71     looper_->pollOnce(-1);
72   }
73 }
74
75 void LooperBackedEventLoop::TriggerExit() {
76   PostTask([this](){ should_continue_ = false; });
77 }
78
79 }  // namespace wificond
80 }  // namespace android