Android - Best and safe way to stop thread

Android-Droid picture Android-Droid · Dec 14, 2011 · Viewed 176.9k times · Source

I want to know which is the best way to stop a thread in Android. I know I can use AsyncTask instead of it and that there is a cancel() method. I have to use Threads in my situation. Here is how I'm using Thread:

Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //doing some work
        }
    };
new Thread(runnable).start();

So, does anyone have any idea of which is the best way to stop a thread?

Answer

Chris picture Chris · Dec 14, 2011

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.