【问题标题】:AsyncTask vs Activity.runOnUiThread() vs Handler.post()AsyncTask vs Activity.runOnUiThread() vs Handler.post()
【发布时间】:2015-11-04 20:24:56
【问题描述】:

我正在研究一个大型应用程序的代码。 UI 中使用了 3 种异步模式,它们看起来都一样:

模式 1,异步任务

new AsyncTask<X, Void, Z>() {  
    protected Boolean doInBackground(X... params) {  
        //background task  
    }  

    protected void onPostExecute(Z res) {  
        //UI callback  
    }  
}.execute();

模式 2,Activity.runOnUiThread(Runnable)

new Thread() {  
    public void run() {  
        //background task  

        runOnUiThread(new Runnable() {  
            public void run() {  
                //UI callback  
            }  
        });  
    }  
}.start();

模式 3,Handler.post(Runnable)

new Thread() {  
    public void run() {  
        //background task  

        handler.post(new Runnable() {  
            public void run() {  
                //UI callback  
            }  
        });  
    }  
}.start();

问题:

  • 我缺少的 3 种模式之间有什么区别吗? (除了 AsyncTask 在具有后台优先级的预先存在的线程池上运行。)
  • 在任何情况下都会首选特定模式?

【问题讨论】:

    标签: android asynchronous android-asynctask


    【解决方案1】:

    无论是外表还是内部,他们都是真正的Handler

    调用onPostExecute()AsyncTask#finish()是从Handler消息循环中调用的。

    runOnUiThread() 如果当前线程不是 UI 线程,则将 Runnable 发布到 Handler。如果是 UI 线程,runnable 会同步执行 - 这并不总是可取的。

    直接使用Handler 可以为您提供低级控制,仅此而已。

    使用什么取决于您的具体要求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-18
      • 2017-02-13
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多