HandlerThread – Android Studio Tutorial
In this tutorial, we will learn how to use the HandlerThread class on Android, which is a subclass of the normal Java Thread that initiates a MessageQueue and a Looper in it’s run method. This way, it keeps running until we call quit on it and accepts new work packages in form of Messages and Runnables.
To get work into a HandlerThread, we need a Handler, which we can initialize either in the onLooperPrepared callback in a HandlerThread subclass, or by passing the HandlerThread’s Looper explicitly with getLooper.
The Handler has different methods available to send and create Messages and Runnables, like post, postDelayed, postAtTime, postAtFrontOfQueue, send, sendDelayed, sendAtTime, sendAtFrontOfQueue, sendEmptyMessage, sendEmptyMessageDelayed, sendEmptyMessageAtTime and different obtain variations that take different combinations of arguments. With setTarget, we can specify the Handler that a Message should be dispatched to, and with sendToTarget send it to the corresponding MessageQueue.
Messages can hold data in their what, arg1, arg2, and obj fields, and we can attach an additional data Bundle with setData. To read this data, we have to override the Handler’s handleMessage method.
When we instantiate a HandlerThread, we should specify a thread priority with the Process.THREAD_PRIORITY constants, either over the constructor or by calling Process.setThreadPriority.
With quit and quitSafely we can leave the MessageQueue of a HandlerThread. But we can also remove Messages and Runnables from its MessageQueue without quitting the Looper, by calling removeMessages, removeCallbacks or removeCallbacksAndMessages, which can also take an object token argument to identify the Message more specifically.
Watch this playlist to learn more about the underlying concepts (Thread, MessageQueue, Looper, etc.):
Example code:
https://gist.github.com/codinginflow/64e927623aea6557031afb74e4a47f12
____________________
💻 Find the BEST programming tutorials on TutHub:
https://tuthub.io
⭐ Get my MVVM Caching Course now:
https://codinginflow.com/caching
❗ Subscribe to the channel:
https://www.youtube.com/c/codinginflo…
📨 Subscribe to the Coding in Flow newsletter:
https://codinginflow.com/newsletter
❓ Join our free developer community:
https://discord.gg/TSnMvmc
📣 Follow Coding in Flow on other sites:
Facebook: https://www.facebook.com/codinginflow
Instagram: https://www.instagram.com/codinginflow
TikTok: https://www.tiktok.com/@codinginflow
Twitter: https://twitter.com/codinginflow
Github: https://github.com/codinginflow
💰 Business requests, sponsoring, etc.: info@codinginflow.com
Views :32113
android studio