-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncTaskExecutor.java
More file actions
78 lines (60 loc) · 2.07 KB
/
Copy pathAsyncTaskExecutor.java
File metadata and controls
78 lines (60 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.app.yourrestaurantapp.utilities;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public abstract class AsyncTaskExecutor<Params, Progress, Result> {
ExecutorService executor;
private Handler handler;
protected AsyncTaskExecutor() {
executor = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
});
}
public ExecutorService getExecutor() {
return executor;
}
public Handler getHandler() {
if (handler == null) {
synchronized (AsyncTaskExecutor.class) {
handler = new Handler(Looper.getMainLooper());
}
}
return handler;
}
protected void onPreExecute() {
// Override this method wherever you want to perform task before background execution get started
}
protected abstract Result doInBackground(Params params);
protected abstract void onPostExecute(Result result);
protected void onProgressUpdate(@NonNull Progress value) {
// Override this method wherever you want update a progress result
}
// used for push progress report to UI
public void publishProgress(@NonNull Progress value) {
getHandler().post(() -> onProgressUpdate(value));
}
public void execute() {
execute(null);
}
public void execute(Params params) {
getHandler().post(() -> {
onPreExecute();
executor.execute(() -> {
Result result = doInBackground(params);
getHandler().post(() -> onPostExecute(result));
});
});
}
public void shutDown() {
if (executor != null) {
executor.shutdownNow();
}
}
public boolean isCancelled() {
return executor == null || executor.isTerminated() || executor.isShutdown();
}
}