简体   繁体   English

android线程:工作线程如何将信号发送到主(GUI)线程?

[英]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. 我有一个gui线程启动一个新线程来做一些繁忙的事情。 The GUI thread will wait the worker thread to be completed, in the mean time the GUI need to be responsive. GUI线程将等待工作线程完成,与此同时,GUI需要响应。

Psedo code: 伪代码:

main thread: 主线程:

start_thread(); start_thread(); wait_thread_done(); wait_thread_done();

work thread: 工作线程:

doing_sth(); doing_sth(); notify_main_thread(); notify_main_thread();

What is the easiest way to do this in android? 在Android中最简单的方法是什么?

The easiest way to do this is with Android's AsyncTask. 最简单的方法是使用Android的AsyncTask。 The documentation is here http://developer.android.com/reference/android/os/AsyncTask.html 该文档位于http://developer.android.com/reference/android/os/AsyncTask.html

And you can call Activity.runOnUiThread() to update the UI from your background task. 而且,您可以调用Activity.runOnUiThread()从后台任务更新UI。

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. 调用Activity#runOnUiThread(Runnable),传递给该方法的Runnable将在GUI线程上执行。

Or use an AsyncTask - which is the proper way to do it. 或使用AsyncTask-这是正确的方法。

waiting for result will make gui thread unresponsive. 等待结果会使gui线程无响应。 you need to use AsyncTask and override onPostExecute to perform operation required when background thread is done 您需要使用AsyncTask并重写onPostExecute来执行后台线程完成后所需的操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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