Threading Problem with Java and Android
I'm designing an app, which flicks through a series of pictures, like flicking through a photo album. Pretty standard stuff I'm sure. Since the picture must be viewed for a few seconds before it automatically changes ot the next pic, I decided to ake a thread that shows the pic, waits couple of second and then moves on.
Picthread(ImageView Image1) {
this.image = Image1;
}
public void run(){
showPicture(image);
animal_array = new String[7];
while (counter < 7){
try{
int timer = 0;
while (timer < 2000){
sleep(500);
timer+=500;
}
image.post(new Runnable(){
public void run() {
showPicture(image);
}
});
}
catch (InterruptedException e) {
}
}
}
This actualy worked. showPictures is a very simple method that just chooses a picture and puts it on an ImageView. It isn't necessary to know about it for my problem. At first itdidn't work, the logcat said I couldn't touch a view on a view heirarchy that wasnt created in this thread. I wasn't sure what that meant so I did the
image.post(...)
code. Which worked. My main question is: Why was this necesary? If you look at my above code, the first showPicture() method is not inside the image.post() code. But no exception is registered. I don't understand this, why isn't a post needed? But also why do I need to post, since Image is a class variable, and I thought could be viewed by all threads. I was happy it worked, but puzzled.
开发者_运维问答Please bare in mind, this is my first attempt at threading in Java on anything more than trivial textbook examples. SO I'm still pretty confused.
By the way, in the end I ditched the whole thread, and just did
new Thread(new Runnable() {
public void run() {...}
When doing "things" with the GUI you should always be on the GUI thread. That is what View.post(Runnable)
does, ensuring that the gui thread does the work of the runnable.
Even though your showImage
works once does not mean that it always works...
精彩评论