From c7cf17bac2f904c58d7f9f97766a0d57c6f2416d Mon Sep 17 00:00:00 2001 From: M66B Date: Sun, 26 Jan 2020 16:25:34 +0100 Subject: [PATCH] Allow cancelling simple task --- .../main/java/eu/faircode/email/SimpleTask.java | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/eu/faircode/email/SimpleTask.java b/app/src/main/java/eu/faircode/email/SimpleTask.java index 67ea083572..d9ca00abd2 100644 --- a/app/src/main/java/eu/faircode/email/SimpleTask.java +++ b/app/src/main/java/eu/faircode/email/SimpleTask.java @@ -39,6 +39,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; // This simple task is simple to use, but it is also simple to cause bugs that can easily lead to crashes // Make sure to not access any member in any outer scope from onExecute @@ -49,6 +50,9 @@ public abstract class SimpleTask implements LifecycleObserver { private boolean count = true; private int executing = 0; + private String name; + private Future future; + private static final List tasks = new ArrayList<>(); private static final ExecutorService executor = @@ -89,6 +93,8 @@ public abstract class SimpleTask implements LifecycleObserver { private void run(final Context context, final LifecycleOwner owner, final Bundle args, final String name) { final Handler handler = new Handler(); + this.name = name; + if (owner instanceof TwoStateOwner) Log.e(new Throwable("SimpleTask/TwoStateOwner")); @@ -109,7 +115,7 @@ public abstract class SimpleTask implements LifecycleObserver { onException(args, ex); } - executor.submit(new Runnable() { + future = executor.submit(new Runnable() { private Object data; private Throwable ex; @@ -187,7 +193,16 @@ public abstract class SimpleTask implements LifecycleObserver { }); } + void cancel(Context context) { + if (future != null) + if (future.cancel(false)) { + Log.i("Cancelled task=" + name); + cleanup(context); + } + } + private void cleanup(Context context) { + future = null; synchronized (tasks) { tasks.remove(this); if (count)