2015-09-04 51 views
0

我在試圖瞭解AsyncTask().get()實際工作方式時遇到問題。我知道這是一個synchronous執行,但是:我不知道​​和get()如何連接。 我從谷歌的文檔此示例代碼:Android調用AsyncTask()。get()without execute()?

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

我很困惑,​​究竟如何觸發立即doInBackground()然後如果調用get()則返回,而get()doInBackground()不起作用。

回答

0

​​計劃內部FutureTask(通常在內部Executor)並立即返回。

get()只是調用FutureTask.get()在這個內部的未來,即它等待(如有必要)的結果。

因此撥打get()而不致電​​首先等待無限期,因爲結果永遠不可用。

正如您所說,使用正常方法時,根本不需要get(),因爲結果在onPostExecute()中處理。在我嘗試瞭解你的問題之前,我甚至都不知道它的存在

+0

我不熟悉'FutureTask',所以我想這就是引起我的困惑。 – nightfixed

相關問題