【发布时间】:2012-08-09 12:20:08
【问题描述】:
我有一个创建安卓应用程序的程序。
这个程序的主类使用Async Tasks进行连接,然后请求数据。连接和请求数据都是通过一个按钮启动的,并且在这两种情况下都会显示一个进度条。
当我为 connect 启动 Async Task 时,程序会通过 onPreExecute()、doInBackground()、onProgressUpdate() 和 onPostExecute(),符合预期。
但是在 onPostExecute() 之后,当我查看调试器窗口时,AsyncTask 仍在运行并继续运行。然后当我请求数据时,会创建一个新的 AsyncTask 并且我有两个正在运行。
如何终止第一个 AsyncTask(实际上是第二个完成后),因为在使用该程序一段时间后,我最终得到了大约 20 个 AsyncTask 线程还在运行!
我在下面包含了我的代码:
private ProgressDialog connectionDialog;
private ProgressDialog requestDataDialog;
private ProgressDialog usingDialog;
private int currentDialog;
public void connectClick(View view) //When the connect button is clicked
{
currentDialog = 1;
new PerformTask().execute();
}
private class PerformTask extends AsyncTask<Void, Integer, Integer>
{
protected void onPreExecute()
{
showDialog(currentDialog);
}
protected Integer doInBackground(Void... voi)
{
int total = 0;
//Perform the task required
publishProgress(total);
return total;
}
protected void onProgressUpdate(Integer... progress)
{
usingDialog.setProgress(progress[0]);
}
protected void onPostExecute(Integer result)
{
removeDialog(currentDialog);
}
}
protected Dialog onCreateDialog(int id)
{
//Setup the dialogs
}
public void requestDownloadClick(View view)
{
currentDialog = 2;
new PerformTask().execute();
}
【问题讨论】:
-
你用的是什么安卓版本?从 Honeycomb 开始,所有异步任务都在单个线程上运行。您也可以使用 threadpoolExecutor,然后使用 Asynctasks.executeonExecutor developer.android.com/reference/android/os/AsyncTask.html
-
好吧,基本上 - 没关系,反正我也无能为力。谢谢。我确实尝试搜索类似的问题,但没有找到。
标签: java android android-asynctask terminate