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?
A thread ends when its
runmethod finishes executing. So if you break the while loop by setting thebooleantofalseand then the control reaches the end ofrun, 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: