android thread: how worker thread send signal to main(GUI) thread?
I have a gui thread starting a new thread to do some busy things. The GUI thread will wait the worker thread to be completed, in the mean time the GUI need to be responsive.
Psedo code:
ma开发者_如何学Goin thread:
start_thread(); wait_thread_done();
work thread:
doing_sth(); notify_main_thread();
What is the easiest way to do this in android?
The easiest way to do this is with Android's AsyncTask. The documentation is here http://developer.android.com/reference/android/os/AsyncTask.html
And you can call Activity.runOnUiThread() to update the UI from your background task.
A small working snippet :
new Thread() {
public void run() {
handler.post(new Runnable() {
public void run() {
try{
// **Do the GUI work here**
} catch (Exception e) { }
}});
};
}.start();
Call Activity#runOnUiThread(Runnable), the Runnable you pass to that method will execute on the GUI thread.
Or use an AsyncTask - which is the proper way to do it.
waiting for result will make gui thread unresponsive. you need to use AsyncTask and override onPostExecute to perform operation required when background thread is done
精彩评论