我使用AsyncTask和一些非常常見的Android代碼來獲取遠程網頁的內容。根據返回的內容,我可以再打另一個頁面。Android應用程序:調用AsyncTask兩次?
http://developer.android.com/reference/android/os/AsyncTask.html
我調試線應打印這樣的:
1> StartA()
2> onPreExecute
3> doInBackground
4> onPostExecute Note: Code here will call EndA()
5> EndA()
6>
7> StartB()
8> onPreExecute
9> doInBackground
10> onPostExecute Note: Code here will call EndB()
11> EndB()
那是不可能的呢?我得到所有上述工作......除了我得到一個附加電話呼籲EndB()出現在第8和第9行之間。
我不能爲我的生活找出原因。沒有看起來應該調用EndB()兩次。它絕對不應該被稱爲9和10之前。
private void StartA()
{
Debug("StartA()");
g_GetWhat = 1;
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://google.com" });
}
private void EndA()
{
Debug("EndA()");
StartB();
}
private void StartB()
{
Debug("StartB()");
g_GetWhat = 2;
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://yahoo.com" });
}
private void EndB()
{
Debug("EndB()");
}
////////////////////////////// /////////////////////
private class DownloadWebPageTask extends AsyncTask<String, Void, String>
{
protected void onPreExecute()
{
Debug("onPreExecute()");
}
protected String doInBackground(String... urls)
{
Debug("doInBackground()");
}
protected void onPostExecute(String result)
{
Debug("onPostExecute()");
if(g_GetWhat == 1) { EndA(); }
if(g_GetWhat == 2) { EndB(); }
}
}
正如文檔所述:「該任務只能執行一次(如果嘗試執行第二次執行,則會拋出異常)。」 – 2012-03-01 01:12:12
因此,我可以*永遠不會執行它兩次?用戶必須退出整個應用程序並稍後再運行它? 「哦,你已經使用了這個代碼,你永遠不會再使用它」?) – Carol 2012-03-01 01:14:17
我沒有看到任何「異常拋出」。 – Carol 2012-03-01 01:16:00