Andy Zhai
Andy Zhai

Reputation: 65

What's the main uses for an Android Handler?

I read the Android SDK API about Handler. "There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own."

I know the meaning of the first point. But what's the meaning of the second point? Could you give me an example? Much appreciated!

Upvotes: 0

Views: 86

Answers (4)

Jim
Jim

Reputation: 10288

This might help: you want to download an image from a website - use a handler to process the download while your user sees a spinner and can still read text on the page. Or if you wanted to convert an image (like resize a photo to MMS send it), the resizing process might take a while, so your user can enter the message text on the UI while the handler processes resizing of the image in the background.

The handler will only use CPU cycles that are available, so the UI thread can be a processor "hog" and the device remains responsive the user. On mutli-processor devices this is still an issue because of Android architecture.

Upvotes: 0

marcinj
marcinj

Reputation: 50046

You can use it to send messages between threads in a safe way. And its not only between GUI thread and worker thread, but also between two worker threads. Many operating systems implement such mechanism, ie. Windows have its messaging system.

One example of using this feature is when you have producer thread that sends jobs to some consumer thread for processing, but consumer thread can process only one job at once, handler allows to put jobs in queue.

Upvotes: 0

laalto
laalto

Reputation: 152927

runOnUiThread() is implemented with a Handler. If the current thread is not the UI thread, the Runnable is posted to the UI thread's Handler and executed as the UI thread's message queue is processed.

Upvotes: 1

Martin Cazares
Martin Cazares

Reputation: 13705

A good example would be using a thread running in the background to perform a long task, so, by the end of the execution if you want to modify a View, you cannot do it from the worker thread, and in this case a Handler could help you out with that issue, Handlers by default attach to the Thread-Loop that created them, so if you make sure that your handler is created in the main-thread, from the worker thread you can send a message to the handler and it will be handled in the main thread, giving you the chance to modify the View, AsyncTask is actually a combination of Threads and Handlers, so a good understanding of them could become in a powerful tool for you as developer to leverage your background/main thread sync...

Hope it helps!

Regards!

Upvotes: 2

Related Questions