2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <looper_backed_event_loop.h>
19 #include <utils/Looper.h>
20 #include <utils/Timers.h>
24 class EventLoopCallback : public android::MessageHandler {
26 explicit EventLoopCallback(const std::function<void()>& callback)
27 : callback_(callback) {
30 ~EventLoopCallback() override = default;
32 virtual void handleMessage(const android::Message& message) {
37 const std::function<void()> callback_;
39 DISALLOW_COPY_AND_ASSIGN(EventLoopCallback);
48 LooperBackedEventLoop::LooperBackedEventLoop()
49 : should_continue_(true) {
50 looper_ = android::Looper::prepare(Looper::PREPARE_ALLOW_NON_CALLBACKS);
53 LooperBackedEventLoop::~LooperBackedEventLoop() {
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);
62 void LooperBackedEventLoop::PostDelayedTask(
63 const std::function<void()>& callback,
65 sp<android::MessageHandler> looper_callback = new EventLoopCallback(callback);
66 looper_->sendMessageDelayed(ms2ns(delay_ms), looper_callback, NULL);
69 void LooperBackedEventLoop::Poll() {
70 while (should_continue_) {
71 looper_->pollOnce(-1);
75 void LooperBackedEventLoop::TriggerExit() {
76 PostTask([this](){ should_continue_ = false; });
79 } // namespace wificond
80 } // namespace android