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
so that we can easily handle sensor data in a separate HandlerThread
.
In the download section available from the Packt Publishing website you'll find an example of processing sensor data in the background, using the magnetic field sensor and the accelerometer in combination to create a simple compass.
18.223.203.175