The code is fully commented and illutrates how to post/send Runnable and Message objects between Threads and how to prepare a Thread using HandlerThread.
If you want to learn more, check this tutorial about the HaMeR framework.- Two Activities, one for Runnable e other for Message calls
- Two HandlerThread objects
- WorkerThread to receive and process calls from the UI
- CounterThread to receive Message calls from the WorkerThread
- And some utility classes and layout resources
- The app has a simple UI with buttons to download some images and start a counter
Posting and receiving Runnables with RunnableActivity
- The RunnableActivity instantiate a background Thread called WorkerThread passing a Handler and a WorkerThread.Callback as parameters
- The activity makes a call on WorkerThread asking it to download a image.
- The download is done asynchronously on the background thread
- The WorkerThread sends the image to the RunnableActivity posting a Runnable to it using a Handler that it received as parameter earlier.
Sending and Receiving Messages with MessageActivity
- The MessageActivity instantiate a background Thread calledWorkerThread passing a Handler as parameters
- The activity makes a call on WorkerThread asking it to download a specific image or download a random one.
- The download is done asynchronously on the background thread
- The WorkerThread create a Message using the 'key' defined on the MessageActivity and passing the image downloaded as a parameter object.
- The Message in sent to the MessageActivity using a Handler that WorkerThread received as parameter earlier.
- The Handler on MessageActivity processes the Message, get the object from it and exhibits on the UI