Stefan Dunn
Stefan Dunn

Reputation: 5513

Android doesn't terminate ASyncTask thread after onPostExecution

I have an instance of ASyncTask in my application which is used to log a user into the application, the problem is that when the ASyncTask as executed the "onPostExecution" function, the ASyncTask thread remains "running" (as shown in the Eclipse Debugger). The onPostExecution only modifies UI components and (in the case of successful login), start a new activity.

How can I terminate the thread?

Upvotes: 4

Views: 2563

Answers (3)

Hemant Shori
Hemant Shori

Reputation: 2483

just check the running threads in your application

if your project is in java application:

int active = Thread.activeCount();
System.out.println("currently active threads: "+active);
Thread all[] = new Thread[active];
Thread.enumerate(all);
for (int i = 0; i < active; i++) {
    System.out.println(i + ": " + all[i]);
}

if you r using android project application:

String run="";
int active =Thread.activeCount();
System.out.println("currently active threads: " + active);
Thread all[] = new Thread[active];
Thread.enumerate(all);

for (int i = 0; i < active; i++) {
    run+=all[i]+"\n";
}
// declare the EditText in your main thread
edittext.setText(run);

Upvotes: 0

Francesco Vadicamo
Francesco Vadicamo

Reputation: 5542

For executing the AsyncTask, Android uses a thread pool so all Thread objects are automatically recycled. So there is no need to kill manually the thread.

For this job there are two static fields in AsyncTask: SERIAL_EXECUTOR and THREAD_POOL_EXECUTOR, instances of Executor that are used when you call asyncTask.execute(Params... params).

If you need more control you can use the alternative method asyncTask.executeOnExecutor(Executor exec, Params... params) specifying another Executor instance - for example you can use Executors.newSingleThreadExecutor() that gives you an ExecutorService instance. In this way you can "shutdown" the ExecutorService, destroying definitively all threads, calling the method executor.shutdown().

Upvotes: 5

Dan S
Dan S

Reputation: 9189

Is there any particular reason you need the thread terminated? Normally you would allow the system to handle this but in my experience once you use an AsyncTask its thread stays around waiting to execute another AsyncTask.

Upvotes: 1

Related Questions