This situation isn't in any way different from the standard Java. You can use the standard way to stop a thread:
class WorkerThread extends Thread {
volatile boolean running = true;
public void run() {
// Do work...
if (!running) return;
//Continue doing the work
}
}
The main idea is to check the value of the field from time to time. When you need to stop your thread, you set running
to false. Also, as Chris has pointed out, you can use the interruption mechanism.
By the way, when you use AsyncTask, your apporach won't differ much. The only difference is that you will have to call isCancel()
method from your task instead of having a special field. If you call cancel(true)
, but don't implement this mechanism, the thread still won't stop by itself, it will run to the end.