From 80307e6836dd2d3380bc54e24f69a1274bc16e34 Mon Sep 17 00:00:00 2001 From: M66B Date: Wed, 15 Aug 2018 12:34:52 +0000 Subject: [PATCH] Replace AsyncTask by HandlerThread Saving accounts and identities take too long on the foreground --- .../java/eu/faircode/email/SimpleTask.java | 34 +++++++++++++------ 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/eu/faircode/email/SimpleTask.java b/app/src/main/java/eu/faircode/email/SimpleTask.java index 3e7c40568f..f0c919e679 100644 --- a/app/src/main/java/eu/faircode/email/SimpleTask.java +++ b/app/src/main/java/eu/faircode/email/SimpleTask.java @@ -20,8 +20,9 @@ package eu.faircode.email; */ import android.content.Context; -import android.os.AsyncTask; import android.os.Bundle; +import android.os.Handler; +import android.os.HandlerThread; import android.util.Log; import androidx.appcompat.app.AppCompatActivity; @@ -42,6 +43,15 @@ public abstract class SimpleTask implements LifecycleObserver { private Bundle args = null; private Result stored = null; + static HandlerThread handlerThread; + static Handler handler; + + static { + handlerThread = new HandlerThread("SimpleTask"); + handlerThread.start(); + handler = new Handler(handlerThread.getLooper()); + } + public void load(Context context, LifecycleOwner owner, Bundle args) { run(context, owner, args); } @@ -82,24 +92,28 @@ public abstract class SimpleTask implements LifecycleObserver { private void run(final Context context, LifecycleOwner owner, final Bundle args) { owner.getLifecycle().addObserver(this); - new AsyncTask() { + // Run in background thread + handler.post(new Runnable() { @Override - protected Result doInBackground(Object... params) { - Result result = new Result(); + public void run() { + final Result result = new Result(); + try { result.data = onLoad(context, args); } catch (Throwable ex) { Log.e(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex)); result.ex = ex; } - return result; - } - @Override - protected void onPostExecute(Result result) { - deliver(args, result); + // Run on main thread + new Handler(context.getMainLooper()).post(new Runnable() { + @Override + public void run() { + deliver(args, result); + } + }); } - }.execute(args); + }); } private void deliver(Bundle args, Result result) {