2015-09-04 60 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