Handlers in Android Programming
I have got to know that the Handlers are basically used to Run the Small Section of Code and etc...
But I didn't g开发者_JAVA百科ot the exact scenerio about when particularly It is Ideal to use the Handlers!
Any Help???
Thanks, david
Handlers are used for updating the UI from other (non-UI) threads.
For example, you can declare a Handler on your Activity class:
Handler h = new Handler();
Then you have some other tasks on different thread that wants to update some UI (progress bar, status message, etc). This will crash:
progressBar.setProgress(50);
Instead, call this:
h.post(new Runnable() {
public void run() {
progressBar.setProgress(50);
}
});
I'm a newbie myself but I'll give a newbie example since I recently learned this, I'm sure there are many more.
You have to use a Handler
when you want to update the main UI when you are doing something in another thread. For example in my case I used it in image slideshow code that runs in a TimerTask
. You cannot update the main UI ImageView
with the next image from within the TimerTask
because it's in a different thread. So you have to use a Handler
or you get an error.
This is just one example. I hope this helps.
精彩评论