Applications of Handler and HandlerThread
The Handler
class is incredibly versatile, which makes its range of applications very broad.
So far we looked at Handler
and HandlerThread
in the context of the Activity
lifecycle, which constrains the sort of applications that make sense—ideally we do not want to perform long-running operations (more than a second or so) at all in this context.
With that constraint in mind, good candidate uses include performing calculations, string processing, reading and writing small files on the filesystem, and reading or writing to local databases using a background HandlerThread
.
We might consider AsyncTask
instead for one-off's, or if we want to display progress or cancel a task part way through. The Android platform also uses Handler
extensively as a mechanism for abstracting the work that needs doing from the thread that will do it. A nice example of this can be found in android.hardware.SensorManager
, which allows listeners to be registered along with a Handler...