Handler in Android
While working on SUSI.AI app (a smart assistant app), I found the necessity of handling UI components along with background data queue. While initializing a text to speech(TTS) engine inside a fragment that already had a speech to text (stt) engine implemented, there was a necessity to run the TTS engine to run using handler and later make it interact with the main UI thread. Let’s see how I handled this situation in the SUSI.AI app.
Android usually handles all the UI operations and input events from one single thread which is known as the Main or UI thread. Android collects all events in this thread in a queue and processes this queue. If one needs to perform some tasks in parallel with the main thread, then the main thread needs to be synchronized. Each handler is associated with a thread. A handler is a way to solve the asynchronous problem in Android.
A handler is widely used for:
- Managing and inserting messages in the queue
- Performing a task at a scheduled time in a different thread
- Implementing runnable
How Handlers work?
A handler is used to send and process Message and Runnable objects associated with a thread. Each handler is associated with a different single thread. This helps to perform the task asynchronously. The task, messages or runnable associated with that handlers are executed when it comes out of the message queue.
In Android, Handler is mainly used to update the main thread from background thread or other than the main thread. There are two methods in the handler:
- Post() − it posts a message from background thread to the main thread using looper.
- sendmessage() − if we want to organize what we have sent to UI (message from background thread) or UI functions. we should use sendMessage().
Construction of Handler:
First of all, we need to create and reference to Handler. After Handler is being created, we create some runnable objects. These runnable objects get executed inside the Handler.
Construction of Runnables that can be used in the handler:
Here, in this example, I have used the Post method to update the main thread.
Clearly, the post method is used in the handler object to execute the task mentioned in the runnable, by using its reference. Also, we can see the use of postDelayed function. This function executes the runnable after a specific span of time(mentioned in milliseconds in the parameter along with the runnable reference).
Lastly, it is very important to note that we should clear all the references to the handlers during the destruction of the view or the activity else there might be memory leaks.
Reference: Handler in Android
SUSI.AI Android App: PlayStore GitHub
Tags:SUSI.AI Android App, Kotlin, SUSI.AI, FOSSASIA, GSoC, Android, Handler
You must be logged in to post a comment.