【问题标题】:Android AsyncTask: what is difference between execute() and get()?Android AsyncTask:execute() 和 get() 有什么区别?
【发布时间】:2013-09-03 21:16:17
【问题描述】:

我应该这样写吗

return task.exec(session, state).get(json_timeout, TimeUnit.MILLISECONDS);

或者我可以这样做

task.exec(session, state, result);
return result;

A 已经阅读了我找到的所有文档,但未能找到答案。我的坏...

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:

    不要使用get()。它将阻塞 ui 线程,直到 asynctask 完成执行,不再使其异步。

    使用执行和调用异步任务

    new task().exec(session, state, result);
    

    您也可以将参数传递给asynctaskdoInbackground() 的构造函数

    http://developer.android.com/reference/android/os/AsyncTask.html

    public final Result get ()

    Added in API level 3
    Waits if necessary for the computation to complete, and then retrieves its result.
    

    您可以将您的 asynctask 设置为您的活动类的内部类,并在onPostExecute 中更新 ui。

    如果 asynctask 在不同的文件中,那么你可以使用 interface.

    How do I return a boolean from AsyncTask?

    【讨论】:

      【解决方案2】:

      AsyncTask#get() 会阻塞调用线程。

      AsyncTask#execute() 将在单独的线程中运行并在onPostExecute(...) 中传递Result

      我建议不要使用get() 方法,除非在测试等特殊情况下。 AsyncTask 的全部目的是在doInBackground() 中执行一些长时间运行的操作,然后在完成后处理结果。

      正常 AsyncTask 执行的一个示例如下所示:

      Task task = new Task(){
          @Override
          protected void onPostExecute(Result result) {
              super.onPostExecute(result);
              //handle your result here
          }
      };
      task.execute();
      

      【讨论】:

        猜你喜欢
        • 2021-05-10
        • 2014-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-10
        • 1970-01-01
        • 2011-02-01
        • 2015-08-03
        相关资源
        最近更新 更多