我正在使用 AsyncTask 和一些非常常见的 Android 代码来获取远程网页的内容。根据返回的内容,我可以调用另一个页面。
http://developer.android.com/reference/android/os/AsyncTask.html
My debugging lines should print like this:
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()
这不可能吗?我得到了上述所有的工作......除了我在第 8 行和第 9 行之间收到一个对 EndB() 的额外调用。
我这辈子都想不通为什么。看起来没有什么应该调用 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(); }
}
}
最佳答案
您只能执行一次 AsyncTask
实例。您实际上正在创建两个实例,但无论如何您都应该这样调用它,这样它就永远不会被调用:
new DownloadWebPageTask().execute(new String[] { "http://yahoo.com" });
new DownloadWebPageTask().execute(new String[] { "http://google.com" });
而不是像这样:
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://google.com" });
我认为你在这里遇到了问题:
private void EndA()
{
Debug("EndA()");
StartB();
}
一旦 StartB 开始,您的 g_GetWhat
值就会发生变化。因此,当执行从 EndA()
返回时,下一个 if 语句的计算结果为 true,因为 g_GetWhat
的值已更改。
if(g_GetWhat == 1) { EndA(); }
if(g_GetWhat == 2) { EndB(); }
g_GetWhat
的值实际上是 2,这就是您看到当前结果的原因。调用 g_GetWhat 时应将其传递给 AsyncTask,并使其成为任务的实例变量。
关于java - 安卓应用 : Calling AsyncTask twice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9509217/