[android] Android - Best and safe way to stop thread

As we know that the Thread.stop() is deprecated in JAVA, under the hood the Thread.stop calls the interrupt() method on the thread to stop it, Interrupt is meant to be thrown from the methods which keep the thread waiting for some other thread to notify after the execution completes. Interrupt will cause nothing to the thread if it is not handled in the execution of a thread, like, if(Thread.interrupted())return; So, all in all we need to basically manage the start and stop of the thread like calling the start() method like Thread.start() starts a while(true) inside the run() method of the thread and checks for interrupted status in each iteration and returns from the thread.

Please note that a thread will not die in the following situations:

  1. The thread has not yet returned from the run().
  2. Any of the objects owned by the thread is accessible. (This hints to null/dispose of the references for GC to do the rest)