X-Git-Url: http://git.osdn.net/view?a=blobdiff_plain;f=looper_backed_event_loop.cpp;h=b4f5c44ee4d7ad6068bfe42d2a54d15d37fc1992;hb=HEAD;hp=db7197ac84e08e9598cc2e2c5c0e3d0d55f4ad90;hpb=696a49e12ef63c815440de8564a5802da5e0ba9b;p=android-x86%2Fsystem-connectivity-wificond.git diff --git a/looper_backed_event_loop.cpp b/looper_backed_event_loop.cpp index db7197a..b4f5c44 100644 --- a/looper_backed_event_loop.cpp +++ b/looper_backed_event_loop.cpp @@ -14,8 +14,9 @@ * limitations under the License. */ -#include +#include "wificond/looper_backed_event_loop.h" +#include #include #include @@ -39,6 +40,28 @@ class EventLoopCallback : public android::MessageHandler { DISALLOW_COPY_AND_ASSIGN(EventLoopCallback); }; +class WatchFdCallback : public android::LooperCallback { + public: + explicit WatchFdCallback(const std::function& callback) + : callback_(callback) { + } + + ~WatchFdCallback() override = default; + + virtual int handleEvent(int fd, int events, void* data) { + callback_(fd); + // Returning 1 means Looper keeps watching this file descriptor after + // callback is called. + // See Looper.h for details. + return 1; + } + + private: + const std::function callback_; + + DISALLOW_COPY_AND_ASSIGN(WatchFdCallback); +}; + } // namespace namespace android { @@ -66,12 +89,48 @@ void LooperBackedEventLoop::PostDelayedTask( looper_->sendMessageDelayed(ms2ns(delay_ms), looper_callback, NULL); } +bool LooperBackedEventLoop::WatchFileDescriptor( + int fd, + ReadyMode mode, + const std::function& callback) { + sp watch_fd_callback = new WatchFdCallback(callback); + int event; + if (mode == kModeInput) { + event = Looper::EVENT_INPUT; + } else if (mode == kModeOutput) { + event = Looper::EVENT_OUTPUT; + } else { + LOG(ERROR) << "Invalid mode for WatchFileDescriptor()."; + return false; + } + // addFd() returns 1 if descriptor was added, 0 if arguments were invalid. + // Since we are using non-NULL callback, the second parameter 'ident' will + // always be ignored. It is OK to use 0 for 'ident'. + // See Looper.h for more details. + if (looper_->addFd(fd, 0, event, watch_fd_callback, NULL) == 0) { + LOG(ERROR) << "Invalid arguments for Looper::addFd()."; + return false; + } + return true; +} + +bool LooperBackedEventLoop::StopWatchFileDescriptor(int fd) { + if (looper_->removeFd(fd) == 1) { + return true; + } + return false; +} + void LooperBackedEventLoop::Poll() { while (should_continue_) { looper_->pollOnce(-1); } } +void LooperBackedEventLoop::PollForOne(int timeout_millis) { + looper_->pollOnce(timeout_millis); +} + void LooperBackedEventLoop::TriggerExit() { PostTask([this](){ should_continue_ = false; }); }