我有一个创建 android 应用程序的程序。
该程序的主类使用Async Tasks进行连接,然后请求数据。连接和请求数据都是通过一个按钮启动的,并且在这两种情况下都会显示一个进度条。
当我为connect启动异步任务时,程序会按照预期运行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();
}