A Handler can be easily used to execute code after a delayed amount of time. It is also useful for executing code repeatedly after a specified amount of time by calling the Handler.postDelayed() method again from within the Runnable's run() method.
HandlerThreads and communication between Threads
As Handlers are used to send Messages and Runnables to a Thread's message queue it's easy to implement event based communication between multiple Threads. Every Thread that has a Looper is able to receive and process messages. A HandlerThread is a Thread that implements such a Looper, for example the main Thread (UI Thread) implements the features of a HandlerThread.
Creating a Handler for the current Thread
Creating a Handler for the main Thread (UI Thread)
Send a Runnable from another Thread to the main Thread
Creating a Handler for another HandlerThread and sending events to it
Stop handler from execution
To stop the Handler from execution remove the callback attached to it using the runnable running inside it:
Use Handler to create a Timer (similar to javax.swing.Timer)
This can be useful if you're writing a game or something that needs to execute a piece of code every a few seconds.
This code will print "Hello" every second.
Using a Handler to execute code after a delayed amount of time
Executing code after 1.5 seconds:
Executing code repeatedly every 1 second:
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0