首页 文章

Android中的Handler-Looper实现

提问于
浏览
3
  • 我有Activity with Handler(UI线程)

  • 我启动新的Thread并生成handler.post(new MyRunnable()) - (新工作线程)

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

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

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

2 回答

  • 3

    附加到UI线程的处理程序 .

    正确 .

    android如何在没有新线程创建的情况下在同一个UI线程中运行runnable?

    任何线程,包括主应用程序("UI")线程,都可以在 Handler (或任何 View ,就此而言)上调用post() .

  • 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();
            });
        }
    }
    

相关问题