Thread
A thread is a line of code execution within an application. An application can have multiple threads running at the same time. In other words, threads allow an application to have multitasking behavior. In Java, the Thread
class is a representation of a thread of the Java Virtual Machine or JVM (which does not necessarily correspond to a thread of the host operating system, but this does not come to the case).
Handlers and Threads
For the difference between Handler
and Thread
, see this question . Note that Handlers
are not Threads
; Handlers
have this name because they are used to deliver messages (a message or Message
is basically the encapsulation of a Runnable
, that is, an executable code snippet) to threads in> loop waiting for the arrival of these code snippets to execute.
For a thread to loop, you must create a message queue for it by calling the methods Looper.prepare()
and Looper.loop()
within the thread itself. In the case of the main thread the system itself already does these steps, so we already found it in loop by default.
We use Handler
when we want a secondary thread to execute many messages, or when we want to deliver a message to the main thread. In the latter case we can avoid using Handler
through the Activity.runOnUiThread()
method (if we are in Activity
), or through AsyncTask
.
AsyncTasks
A AsyncTask
is a class that allows you to execute three code snippets in sequence: the first will be executed by the main thread of UI), the second by a secondary thread , and the third again from the main thread . Underneath the plans this is implemented using Threads
and Handlers
.
AsyncTasks
are intended to simplify the implementation of this sequence of steps, which is very common in Android (for example: triggering a "load" animation, running a background task, and then interrupting the animation ).
This sequence is thus made separate in threads and not everything in the same thread , because the main thread is reserved to refresh the screen and can not perform tasks in the background under penalty of losing responsiveness.