0

我在试图了解AsyncTask().get()实际工作方式时遇到问题。我知道这是一次执行,synchronous但是:我不知道如何连接。我有来自 Google 文档的示例代码:execute()get()

// Async Task Class
class DownloadMusicfromInternet extends AsyncTask<String, String, String> {

    // Show Progress bar before downloading Music
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Log.d("Task: ", "onPreExecute()");
    }

    // Download Music File from Internet
    @Override
    protected String doInBackground(String... f_url) {
       for (int i = 0; i < 100; i++){
           try {
               Thread.sleep(100);
               Log.d("Task: ", String.valueOf(i));
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
        return null;
    }

    // While Downloading Music File
    protected void onProgressUpdate(String... progress) {
        // Set progress percentage
        Log.d("Task: ", "onProgressUpdate()");
    }

    // Once Music File is downloaded
    @Override
    protected void onPostExecute(String file_url) {
        Log.d("Task: ", "onPostExecute()");
    }
}

现在,button.onClick()我以 3 种方式称之为:

new DownloadMusicfromInternet().execute("");//works as expected, the "normal" way


//works the normal way, but it's synchronous
try {
   new DownloadMusicfromInternet().execute("").get();
} catch (InterruptedException e) {
   e.printStackTrace();
} catch (ExecutionException e) {
   e.printStackTrace();
}

//does not work
try {
  new DownloadMusicfromInternet().get();
} catch (InterruptedException e) {
  e.printStackTrace();
} catch (ExecutionException e) {
  e.printStackTrace();
}

我很困惑到底是如何execute()触发的,然后如果被调用doInBackground()则立即返回,而对任何东西都没有影响。get()get()doInBackground()

4

1 回答 1

1

execute()安排 internal FutureTask(通常在 internal 上Executor)并立即返回。

get()只需在这个内部未来调用FutureTask.get(),即它等待(如果需要)结果。

所以调用get()而不execute()先调用会无限期地等待,因为结果永远不会可用。

正如您所提到的,当以正常方式使用时,get()根本不需要,因为结果是在onPostExecute(). 在我试图理解你的问题之前,我什至不知道它的存在

于 2015-09-04T11:19:07.687 回答