我在试图了解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()