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:
Since no one's replying. I'm answering my own questions then.
AsyncTaskis recommended for only short tasks (around 5 seconds) is there is no method to cancel a running
AsyncTask. There exists a method called
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,
Threadcan be stopped with
Serviceprovided that you are aware of the cancellation limitation of
AsyncTaskand the possibility of memory leak can be created by
AsyncTask. Note that, there is obviously no need to use an
IntentServicewhich is already running in a worker thread.
RxJavaall 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
RxJavathat can be easily found by Googling.