If you tested the application I wrote for the previous tutorial, you could have noticed a small problem: while the connection is established and the “Hello World!” message is sent, the GUI of the application does not respond. The reason is simple: most of the methods used are blocking, i.e. they stop the execution of the process until they get a result (or a timeout).
If, for example, you call the read() method to get some data from a socket, that method stops the execution until the data is available!
To solve the problem, you must learn how to write a multitasking application, that is an application with different processes, each one independent from the other.
Threads and GUI
To simplify, an application may be composed by one or more processes (thread), executed in parallel by the Android O.S. Simple applications, like the ones from the previous examples, have a single thread, called main thread. This thread manages, among the other tasks, the components (text boxes, images, buttons…) that forms the graphical interface (GUI) of your application.
The first rule you must consider when writing multithread application is that only the main thread can update the graphical interface:
This rule often causes headaches to programmers: consider when a dedicated thread receives data from a Bluetooth socket: it’s common that, when you get a command, you should update the GUI accordingly…
Normally, a suggested solution is to ask to the main thread to update the GUI for you… today I’d like to show you a different approach, that leverages the use of the AsyncTask object.
The AsyncTask object was included in Android to easily manage tasks that have to be executed in thebackground and have to interact with the application’s GUI.
The advantage is that – transparently for the developer – some of its methods are executed in the GUI (main) thread and others are executed in a different, dedicated thread.
Developers can therefore use the methods executed in the GUI thread to update the interface and the ones executed in the second thread for the background operations that should not block the main thread (for example send/receive data through a socket):