Search code examples
androidmultithreadingandroid-asynctaskandroid-service

Asynctask vs Thread vs Services vs Loader


I got slightly confused about the differences between Asynctask, Thread, Service, Loader in Android.

I know how it works. But i still don't understand what and when should i use.

I work with Android for 3 years, and generally still use AsyncTask for all background tasks (and sometimes Thread). But many people say that "Asynctask is outdated", and don't recommend to use them. Also they recommend to use robospice or Volley.

So, is AsyncTask really so bad and i should use framework for networking tasks? And what should i use for background (not networking) task?


Solution

  • AysncTasks are not 'outdated' as much as they are incomplete. Among other things async tasks do not bother if their parent activity is currently running or not. For the same reason why you include checks for verify the context to be null or not. Besides, unless you are using your own Thread Pool Executor these tasks execute serially.

    Volley tries to fill in those gaps, mainly concerning syncing up with the main thread and thread pooling. It behaves optimal if you wish to do stuff that requires average network requests; like some meta data list and images(picture the youtube app requests and facebook app requests for posts).

    Typically few advantages of Volley are as follows

    1. It keeps the worker thread informed about the activity(Main thread)
    2. Easier resource prioritization you could provide priority to your download requests. A typical scenario would involve you giving priority to text over image.
    3. Effective request cache and memory management.
    4. Extensible
    5. It provides you an option to discard your request in-case your activity was shutdown or restarted.
    6. Simpler patterns for data retrieval as opposed to AsyncTasks.

    Volley fares badly when it comes to streaming requests/video as mentioned at Google I/O.

    I'm not exactly aware of robospice. Ps: If you have time on your hand see https://www.youtube.com/watch?v=yhv8l9F44qo

    Here's a further read if you wish to go into other libraries with benchmarks for the same. Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley