I know this is the question which was asked many many times. However there is something I never found an answer for. So hopefully someone can shed me some light.
We all know that AsyncTask and Thread are options for executing background tasks to avoid ANR issue. It is recommended that asynctask should only be used for short-running tasks while thread can be used for long-running tasks. The reasons why asynctask shouldn't be used for long tasks are well-known which is about the possible leak caused by asynctask since it may continue running after an activity's destroyed. That is convincing. However, it also leads to some other questions:
Thanks
Using Handlers you have the advantage of MessagingQueues , so if you want to schedule messages or update multiple UI elements or have repeating tasks. AsyncTask are similar, in fact, they make use of Handler , but doesn't run in the UI thread, so it's good for fetching data, for instance fetching web services.
Thread can be triggered from any thread, main(UI) or background; but AsyncTask must be triggered from main thread. Also on lower API of Android(not sure, maybe API level < 11), one instance of AsyncTask can be executed only once. Long task in general.
The main difference between Handler and Thread is that a handler is a function or a method that is capable of performing a specific task while a thread is a small, lightweight execution unit within a process.
In newer Android versions, 5 threads are create by default, and the ThreadPoolExecutor will attempt to run the AsyncTask s on these 5 threads. If you create more than 5 AsyncTask s, it may either queue them or create new threads (but only up to 128).
Since no one's replying. I'm answering my own questions then.
AsyncTask
is recommended for only short tasks (around 5 seconds) is there is no method to cancel a running AsyncTask
. There exists a method called AsyncTask.cancel(true)
which invokes onCancelled(Result result)
. However, according to the docs, this method "runs on the UI thread after cancel(boolean) is invoked and doInBackground(Object[]) has finished." (https://developer.android.com/reference/android/os/AsyncTask.html). On the other hand, Thread
can be stopped with Thread.interrupt()
.AsyncTask
within a Service
provided that you are aware of the cancellation limitation of AsyncTask
and the possibility of memory leak can be created by AsyncTask
. Note that, there is obviously no need to use an AsyncTask
in an IntentService
which is already running in a worker thread.RxJava
all the time without having any issue. Note that the same memory leaking issue is also applied to RxJava
. You can perhaps find one of the specific questions here. There are also a whole bunch of discussions about handling leaking/screen rotation with RxJava
that can be easily found by Googling.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With