简体   繁体   中英

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:

main 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM