Building responsive apps with Handler
The
Handler
class is fundamental to the infrastructure of Android apps—together with Looper
. It underpins everything that the main thread does—including the invocation of the Activity
lifecycle methods.
While Looper
takes care of dispatching work on its message-loop thread, Handler
provides the means to add work to the message queue belonging to a Looper
.
We can create a Handler
to submit work to be processed on the main thread simply by creating a new instance of Handler
from an Activity
lifecycle method such as onCreate
, shown as follows:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Handler handler = new Handler(); // … }
We could also be explicit that we want to submit work to the main thread by passing a reference to the main Looper
instance into the Handler
constructor.
Handler handler = new Handler(Looper.getMainLooper());
Exactly what we mean by "work" can be described by subclasses of java.lang...