Android中的Handler-Looper实现

mob*_*lex 3 implementation android handler looper

  1. 我有Activity with Handler(UI线程)
  2. 我启动新的Thread并生成handler.post(new MyRunnable()) - (新工作线程)

关于post方法的Android文档说:"导致Runnable r被添加到消息队列中.sunnable将在这个处理程序所附加的线程上运行."

处理程序附加到UI线程.android如何在没有新线程创建的情况下在同一个UI线程中运行runnable?

是否将使用来自handler.post()的Runnable创建新线程?或者只有run()方法将从Runnable子类调用?

Cep*_*ron 5

这是一个粗略的伪代码示例,说明如何使用处理程序 - 我希望它有帮助:)

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();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)