Android Thread interupt when activity destroy does not work

1.4k Views Asked by At

I'm new to android developing. I have an activity where I create a thread to load an image and refresh it on imageView. The thread runs an "infinite loop". I want to also stop the thread when the activity is stopped. Below you can see in sample what I have implemented but it throws exception and the thread continues to work or the app crashes. Any suggestions?

public class myActivity extends Activity{

   Thread tr;


   .... onCreate(){
        bla bla bla

        tr = new Thread();
        tr.start();
   }

   .....onDestroy(){
        tr.interupt();
   }

   bla bla bla
}

Sorry for not writing the full code but I'm not home right now where I have the code. What should I change to make it stop ok?

I have also tried another trick, where I set a public static boolean and onDestroy I set it false.

In the thread the "infinite loop" wokrs as :

public static Boolean is = true;

in thread:

while (is == true)....

onDestroy:

is = false; 

So, with this trick, since the loop will end, will the thread be killed when it has ended it's operations?

2

There are 2 best solutions below

0
On BEST ANSWER

A thread ends when its run method finishes executing. So if you break the while loop by setting the boolean to false and then the control reaches the end of run, the thread will surely finish. This is in fact the recommended way to stop a thread in java.

One important point you should remember is to always set variables that are modified by one thread and read by another one as volatile, to prevent optimizations like variable caching from breaking your code:

public static volatile boolean is = true;
2
On

Don't solve your problem using the first approach ,This approach is not recommended in java threads documentation. Your second approach is the best way of doing this job. Now in the second approach when u make your "is" variable as false in onDestroy method, this will immediately break the while loop inside your thread. Now after this while loop If you have written any code then it will continue executing and once it reaches the end of your thread code the thread will stop by itself.