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 the background 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):
Let’s see the methods in detail:
- onPreExecute() – GUI – executed just before the start of the background activity, can be used to inform the user (with an animation, message…) that the required operation has started
- doInBackground() – background – main method where to perform the background task
- publishProgress() – background – method, normally called in the doInBackground(), used to notify a “progress” during the task execution
- onProgressUpdate() – GUI – method, invoked by the publishProgress(), that can update the GUI with the “progress” of the execution
- onPostExecute() and onCancelled() – GUI – methods that are executed at the end of the task (or when it’s cancelled)
In the next page you’ll learn how to use what explained before in a real Android application…
Pages: 1 2