Android - Best and safe way to stop thread

Solution 1:

You should make your thread support interrupts. Basically, you can call yourThread.interrupt() to stop the thread and, in your run() method you'd need to periodically check the status of Thread.interrupted()

There is a good tutorial here.

Solution 2:

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.