Android does not interrupt ASyncTask stream after onPostExecution

I have an ASyncTask instance in my application that is used to register the user in the application, the problem is that when ASyncTask executes the onPostExecution function, the ASyncTask thread remains "running" (as shown in Eclipse Debugger). OnPostExecution only changes the user interface components and (in case of a successful login) starts a new action.

How can I complete the thread?

+4
source share
3 answers

AsyncTask Android uses a thread pool to execute, so all Thread objects are automatically recycled. Therefore, there is no need to manually kill the stream.

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

If you need more control, you can use the alternative asyncTask.executeOnExecutor(Executor exec, Params... params) method with another Executor instance, for example, you can use Executors.newSingleThreadExecutor() , which gives you an ExecutorService instance. This way you can turn off the ExecutorService , permanently destroy all threads by calling the executor.shutdown() method.

+5
source

Is there any specific reason why you need a thread? Usually you let the system handle this, but in my experience, when you use AsyncTask , its thread remains on hold to execute another AsyncTask .

+1
source

just check the running threads in the application

if your project is in a 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 are using the android app app:

 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); 
0
source

Source: https://habr.com/ru/post/1390095/


All Articles