I have a program that creates an android application.
The main class of this program uses Async Tasks to connect, then request data. Both connect and request data are started via a button and a progress bar is displayed in both cases.
When I start the Async Task for connect, the program runs through the methods onPreExecute(), doInBackground(), onProgressUpdate() and onPostExecute(), which is as expected.
However after onPostExecute(), when I look in the debugger window, AsyncTask is still running and continues to run. When I then request data, a new AsyncTask is created and I have two running.
How do I terminate the first AsyncTask (and indeed the second once it has finished) as after using the program for a while I end up with around 20 AsyncTask threads still running!
I've included my code below:
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();
}
Just for completeness and so I can accept the question, here is the answer, given by grv_9098, found at stackoverflow.com/a/3077508/1514187 :
AsyncTask manages a thread pool, created with ThreadPoolExecutor. It will have from 5 to 128 threads. If there are more than 5 threads, those extra threads will stick around for at most 10 seconds before being removed. (note: these figures are for the presently-visible open source code and vary by Android release).
Leave the AsyncTask threads alone, please.