Use AndroidExecutor for background tasks that make API calls.

This commit is contained in:
akwizgran
2016-04-29 12:18:40 +01:00
parent cb8bfeb2ce
commit c21854fbe4
10 changed files with 107 additions and 71 deletions

View File

@@ -1,46 +1,59 @@
package org.briarproject.system;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import org.briarproject.android.api.AndroidExecutor;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.inject.Inject;
class AndroidExecutorImpl implements AndroidExecutor {
private final Handler handler;
private final Runnable loop;
private final AtomicBoolean started = new AtomicBoolean(false);
private final CountDownLatch startLatch = new CountDownLatch(1);
AndroidExecutorImpl(Application app) {
Context ctx = app.getApplicationContext();
handler = new FutureTaskHandler(ctx.getMainLooper());
private volatile Handler handler = null;
@Inject
AndroidExecutorImpl() {
loop = new Runnable() {
public void run() {
Looper.prepare();
handler = new Handler();
startLatch.countDown();
Looper.loop();
}
};
}
private void startIfNecessary() {
if (started.getAndSet(true)) return;
Thread t = new Thread(loop, "AndroidExecutor");
t.setDaemon(true);
t.start();
try {
startLatch.await();
} catch (InterruptedException e) {
throw new RejectedExecutionException(e);
}
}
public <V> Future<V> submit(Callable<V> c) {
Future<V> f = new FutureTask<V>(c);
handler.sendMessage(Message.obtain(handler, 0, f));
FutureTask<V> f = new FutureTask<>(c);
execute(f);
return f;
}
public void execute(Runnable r) {
startIfNecessary();
handler.post(r);
}
private static class FutureTaskHandler extends Handler {
private FutureTaskHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message m) {
((FutureTask<?>) m.obj).run();
}
}
}