When it is more advantageous to use AsyncTask, and when to use Threads.
For example:
Home
Download some file (ex: JSON).
Which would be more advantageous in this case and why ??
When it is more advantageous to use AsyncTask, and when to use Threads.
For example:
Home
Download some file (ex: JSON).
Which would be more advantageous in this case and why ??
If it is a simple¹ JSON file, use AsyncTask .
AsyncTask is most useful for asynchronous (d'oh) operations with low data demand; on the other hand, however, Java Threads are relevant when dealing with high data demand, GUI operations, and hardware-intensive applications that run in background .
As good references, you can read AsyncTask and Threads for Android.
¹: small, trivial, without much demand.
AsyncTasks
use Threads
beneath the wipes, and serve to simplify the on-screen display of the progress of the operation being performed on background (before, during or after execution) . But since AsyncTasks
are weakly linked to the Activity
lifecycle and can also cause memory leaks if they are poorly implemented, preference should be given to their use for very short operations (at most a few seconds).
For longer operations you can use Threads
or Services
(in the first case display the result on the screen involves the use of a Handler
, and in the second the use of a BroadcastReceiver
). p>
To download files therefore use Thread
or Service
. However, in order to receive the return of a request to a webservice (the JSON case you cited) in which the amount of data received is small and this data needs to be displayed on the screen, it is simpler to use AsyncTask
.