Android

Looper, MessageQueue & Handler Explained – Android Studio Tutorial

In this tutorial, I will explain what Android’s Looper, MessageQueue, and Handler classes are, how they are used to keep the UI...



In this tutorial, I will explain what Android’s Looper, MessageQueue, and Handler classes are, how they are used to keep the UI thread alive, and how we can add them to a normal Java thread. This is the concept behind the HandlerThread class, but in this video we will set up everything manually to understand the underlying concepts.
To create a looper thread, we have to call Looper.prepare in a Thread’s run method to attach a Looper and a MessageQueue to it. When we call Looper.loop, the Looper loops through this MessageQueue in an infinite for-loop until we call quit on it. In each round, the Looper takes the next message with the current timestamp from the MessageQueue and dispatches it to the Handler that originally added it to the queue, where it will then be executed on the thread this Handler is attached to.
A Handler can send a message with arbitrary data fields (what, arg1, arg2, obj etc.) or post a runnable, which will then be added as a callback to an empty message internally. Optionally, a delay or time can be specified, for example with postDelayed or sendMessageDelayed. Messages without a callback (data messages) have to be handled by overriding the handleMessage method in a Handler subclass or callback.
We will also take a quick look at ways to avoid memory leaks from non-static inner classes.

Watch the whole playlist:

Example code:

Looper Thread

____________________
❗ Subscribe to the channel:
https://www.youtube.com/c/codinginflow?sub_confirmation=1

⏯ Watch more tutorials:
https://www.youtube.com/c/codinginflow/playlists

⭐ Become a channel member for exclusive tutorials and other perks:
https://www.youtube.com/channel/UC_Fh8kvtkVPkeihBs42jGcA/join

㊙ Help translating the videos:
http://www.youtube.com/timedtext_cs_panel?c=UC_Fh8kvtkVPkeihBs42jGcA&tab=2

💚 Support the content:

Support the Content

💬 Join the Discord chat:
https://discord.gg/TSnMvmc

🎧 Audiobooks and podcasts for programmers:

5 Audiobooks and Podcasts That Help You Become a Better Programmer While Washing the Dishes

👶 How to get started with Android development:

How to Learn Android Development as a Complete Beginner

📣 Follow Coding in Flow on social media:

Facebook:
https://www.facebook.com/codinginflow

Instagram:
https://www.instagram.com/codinginflow

Twitter:

Blog:

Tutorials



source

20 Replies to “Looper, MessageQueue & Handler Explained – Android Studio Tutorial”

  1. Hi, If i post messages/runnables in code (not with UI buttons) after the creation of looperThread, it find that handler is still null and an exception is generated. So from start of the thread to first messages posted, must exist a delay, or bad things can happen.

  2. I know this is a bit late, but I recently had to work on an app at work that uses Java and raw threads and Handlers. Previously I was using Kotlin/Coroutines. Since I wasn't too familiar about the inner workings of Handler/Threads within the Android context, these videos help A LOT! Thank you so much! <3

  3. The guys tutorials are nicely created, very detailed, in depth. I really appriciate your work and have learnt so many things.
    Especially that dagger tutorial was amazing.

  4. Hi thanks your videos are great! I have a problem on understanding a sentence in 23:05 to 23:12 you say "this works in witch case the message will always be executed in the handler that ???? Sended" I lessened multiple times but still i couldn't understand that word, Can you explain this? Sorry

  5. Hast mir wieder mal geholfen! 😃Wie man Thread braucht habe ich auch von Dir gelernt mit Einpacken in
    'new Thread().start' aber da wird jedesmal ein neuer Thread erzeugt. Nicht gut für eine Aufgabe die jede Sekunde Aufgerufen wird… ☹ Bis jetzt hab ich einfach nicht Verstanden wie man im gleichen nicht UI Thread bleiben kann!? 🤔 Das händling mit Handler, Looper war bis jetzt für mich nicht zu durchschauen… 🥴😵☹ Jetzt kann ich es und habe es schon in meine App eingebaut! 🤗 Ich überprüfe zwar ob ich Internet Verbindung habe aber wenn keine Daten kommen friert der ganze Bildschirm ein. In seltenen Fällen gabs das. Jetzt ist das endlich Geschichte!!! 🤗😊

  6. Hi Florian, I have one doubt about the working of the Handler class. We are storing our ExampleHandler object in the reference of the super class Handler. I am assuming that the looper gets the reference 'handler' which is associated with our background thread. Now rule of inheritance states that we cannot calls the child's public method(s) as well as the overridden method(s) on a reference of the super class. Then how come we are invoking @overridden handleMessage() of ExampleHandler class by calling the handleMessage() of the Handler class.

    Thanks a lot for reading this. Your videos has helped me a lot understanding the core topics. Appreciate it man !!!!!!

  7. Interesting enough, when I try to use Message msg = new Message.obtain(), it shows me to autocomplete the obtain, but when I do it tells me it cannot resolve the symbol "obtain".
    Like what the heck?
    And btw, is it possible that this tutorial is already outdated?
    If I try to extend the handlerclass it needs to be either abstact or needs to implement the methods publish(), flush() and close().
    And I cant seem to overwrite handleMessage, not finding that method.

  8. I just wish you made more tutorials. You are by far one of the best tutor I've ever seen. Tutorials are well edited and you do a good job at explaining stuff. Thank you sir very much.

  9. Honestly this video is a good example of what is wrong with pure OO programming, and Java/JVM In particular. Threading is just straightforward and logical using procedural languages like C, I developed multithreaded Windows apps using Win32 API in the past by just reading official Microsoft documents. All was crystal clear. But here all is fuzzy, and bloated, abstraction over abstraction over abstraction… and in the end you still leak memory. Like a never ending nightmare.

  10. Thank you very very much… just pick right stuff and mix them to make an app, I told you before, you can have both things in hand, your focused tutorials, and whole apps, just break them in segments.
    Take care 🙂

Beri komentar...