Handler-Looper implementation in Android
- I have Activity with Handler (UI thread)
- I start new Thread and make handler.post(new MyRunnable()) - (new work thread)
Android documentation said about post method: "Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached."
Handler attached to UI thread. How android can run runnable in the same UI thread without new thread 开发者_高级运维creation?
Is new thread will be created using Runnable from handler.post()? Or it's only run() method will be called from Runnable subclass?
Here's a rough pseudroidcode example of how to use handlers - I hope it helps :)
class MyActivity extends Activity {
private Handler mHandler = new Handler();
private Runnable updateUI = new Runnable() {
public void run() {
//Do UI changes (or anything that requires UI thread) here
}
};
Button doSomeWorkButton = findSomeView();
public void onCreate() {
doSomeWorkButton.addClickListener(new ClickListener() {
//Someone just clicked the work button!
//This is too much work for the UI thread, so we'll start a new thread.
Thread doSomeWork = new Thread( new Runnable() {
public void run() {
//Work goes here. Werk, werk.
//...
//...
//Job done! Time to update UI...but I'm not the UI thread! :(
//So, let's alert the UI thread:
mHandler.post(updateUI);
//UI thread will eventually call the run() method of the "updateUI" object.
}
});
doSomeWork.start();
});
}
}
Handler attached to UI thread.
Correct.
How android can run runnable in the same UI thread without new thread creation?
Any thread, including the main application ("UI") thread, can call post() on Handler
(or on any View
, for that matter).
精彩评论