[android] Introduce RunLoop based on Looper

Also implement a Timer and AsyncTask based on Android's Looper.
This commit is contained in:
Thiago Marcos P. Santos
2016-03-08 13:32:40 -03:00
parent 08d12f860e
commit 74a1d3c164
5 changed files with 325 additions and 1 deletions

View File

@@ -0,0 +1,60 @@
#include "run_loop_impl.hpp"
#include <mbgl/util/async_task.hpp>
#include <mbgl/util/run_loop.hpp>
#include <atomic>
#include <functional>
namespace mbgl {
namespace util {
class AsyncTask::Impl : public RunLoop::Impl::Runnable {
public:
Impl(std::function<void()>&& fn)
: task(std::move(fn)) {
loop->initRunnable(this);
}
~Impl() {
loop->removeRunnable(this);
}
void maySend() {
if (!queued.test_and_set()) {
loop->addRunnable(this);
}
}
TimePoint dueTime() const override {
return due;
}
void runTask() override {
loop->removeRunnable(this);
queued.clear();
task();
}
private:
// Always expired, run immediately.
const TimePoint due = Clock::now();
RunLoop::Impl* loop = reinterpret_cast<RunLoop::Impl*>(RunLoop::getLoopHandle());
std::atomic_flag queued = ATOMIC_FLAG_INIT;
std::function<void()> task;
};
AsyncTask::AsyncTask(std::function<void()>&& fn)
: impl(std::make_unique<Impl>(std::move(fn))) {
}
AsyncTask::~AsyncTask() = default;
void AsyncTask::send() {
impl->maySend();
}
} // namespace util
} // namespace mbgl