Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
7859 views
1
package com.artifex.mupdfdemo;
2
3
import java.util.concurrent.CancellationException;
4
import java.util.concurrent.ExecutionException;
5
6
// Ideally this would be a subclass of AsyncTask, however the cancel() method is final, and cannot
7
// be overridden. I felt that having two different, but similar cancel methods was a bad idea.
8
public class CancellableAsyncTask<Params, Result>
9
{
10
private final AsyncTask<Params, Void, Result> asyncTask;
11
private final CancellableTaskDefinition<Params, Result> ourTask;
12
13
public void onPreExecute()
14
{
15
16
}
17
18
public void onPostExecute(Result result)
19
{
20
21
}
22
23
public CancellableAsyncTask(final CancellableTaskDefinition<Params, Result> task)
24
{
25
if (task == null)
26
throw new IllegalArgumentException();
27
28
this.ourTask = task;
29
asyncTask = new AsyncTask<Params, Void, Result>()
30
{
31
@Override
32
protected Result doInBackground(Params... params)
33
{
34
return task.doInBackground(params);
35
}
36
37
@Override
38
protected void onPreExecute()
39
{
40
CancellableAsyncTask.this.onPreExecute();
41
}
42
43
@Override
44
protected void onPostExecute(Result result)
45
{
46
CancellableAsyncTask.this.onPostExecute(result);
47
task.doCleanup();
48
}
49
};
50
}
51
52
public void cancelAndWait()
53
{
54
this.asyncTask.cancel(true);
55
ourTask.doCancel();
56
57
try
58
{
59
this.asyncTask.get();
60
}
61
catch (InterruptedException e)
62
{
63
}
64
catch (ExecutionException e)
65
{
66
}
67
catch (CancellationException e)
68
{
69
}
70
71
ourTask.doCleanup();
72
}
73
74
public void execute(Params ... params)
75
{
76
asyncTask.execute(params);
77
}
78
79
}
80
81