blob: 1886e4d0c4b6e7c6ae805c6878c451ff0d7edb78 (
plain)
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
79
80
81
82
83
84
85
86
87
|
/*
This file is part of Subsonic.
Subsonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Subsonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2009 (C) Sindre Mehus
*/
package github.daneren2005.subphonic.util;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import android.util.Log;
/**
* @author Sindre Mehus
* @version $Id$
*/
public abstract class CancellableTask {
private static final String TAG = CancellableTask.class.getSimpleName();
private final AtomicBoolean running = new AtomicBoolean(false);
private final AtomicBoolean cancelled = new AtomicBoolean(false);
private final AtomicReference<Thread> thread = new AtomicReference<Thread>();
private final AtomicReference<OnCancelListener> cancelListener = new AtomicReference<OnCancelListener>();
public void cancel() {
Log.d(TAG, "Cancelling " + CancellableTask.this);
cancelled.set(true);
OnCancelListener listener = cancelListener.get();
if (listener != null) {
try {
listener.onCancel();
} catch (Throwable x) {
Log.w(TAG, "Error when invoking OnCancelListener.", x);
}
}
}
public boolean isCancelled() {
return cancelled.get();
}
public void setOnCancelListener(OnCancelListener listener) {
cancelListener.set(listener);
}
public boolean isRunning() {
return running.get();
}
public abstract void execute();
public void start() {
thread.set(new Thread() {
@Override
public void run() {
running.set(true);
Log.d(TAG, "Starting thread for " + CancellableTask.this);
try {
execute();
} finally {
running.set(false);
Log.d(TAG, "Stopping thread for " + CancellableTask.this);
}
}
});
thread.get().start();
}
public static interface OnCancelListener {
void onCancel();
}
}
|