Android Guts:intro to Loopers and handlers

Source: Internet
Author: User

Android Guts:intro to Loopers and handlers? Mind the Robot

One of the reasons I love Android APIs are because it contains so many useful little things. Many of them is not even specific to the platform and I really miss them in Java SE. Today I ' d like to give a short introduction to II nice classes– Looper and Handler. They is used in the Android UI internally, and available to US developers so we can do some cool things with their help.

So what can I do with Loopers and Handlers? Basically, they implement a common concurrency pattern that I call the Pipeline Thread. Here's how it works:

    • The Pipeline Thread holds a queue of tasks which is just some units of work that can be executed or processed.
    • Other threads can safely push new tasks into the Pipeline Thread's queue at any time.
    • The Pipeline Thread processes the queued tasks one after another. If There is no tasks queued, it blocks until a task appears in the queue.
    • Sometimes tasks can called messages and other names.

This architecture have some valuable traits and is widely used in frameworks and applications on different platforms.

In this post, we is going to build a simple app that emulates a queue of background downloads while showing its Status in the UI. It'll be based on a Pipeline the Thread that we'll build using Looper and Handler. As usual, the complete source was available at the bottom of the article.

?

But before we start, let's discuss the Pipeline Thread for some more time and see how Looper and Handler Implement it.

Usages of the Pipeline Thread

The most prominent usage of Pipeline Thread was found within almost any UI framework, including Swing (remember th e event-dispatching thread?), SWT, Adobe Flex and, of course, Android activities. The Pipeline Thread pattern is used to process UI events (such as button clicks, mouse movement, orientation Chan GES, screen redraw and so on). This allows a button caption without have to worry that the user would click the button at the same moment.

On the-the other hand, this forces-only does quick operations in the UI Thread–any developer knows what happens if you Try to download a file right there in a button OnClick handler. In our app we'll overcome that by adding another Pipeline Thread and pushing long-lasting operations (the D Ownloads) to it so, the UI thread can run free.

Other common usages of the Pipeline Thread pattern:

    • Executing requests to a remote service (usually you want to does them one by one and sequentially)
    • uploading images to an HTTP service
    • resizing and processing images (I once developed a picture uploader)
    • Downloading stuff, just like we ' re going

In general, using a Pipeline thread rather than launching another thread for each background operation allows you to CONTR OL the load and order (almost like law and order) of your background jobs. Also, you can have multiple Pipeline Threads and use them as a pool so you'll have both the ability to execute multiple Operations at once and keep the load under control.

In our example, we are want to allow one download at a time and we want downloads to execute in the order they were sched Uled. Exactly the case to use a Pipeline Thread.

Looping and handling

Looper is a class this turns a thread into a Pipeline thread and Handler gives you a mechanism to push tasks in it from Any other threads.

The Looper is named so because it implements the Loop–takes the next task, executes it, then takes the next one And so on. The Handler is called a Handler because someone could not invent a better name.

Here's what you should put into a thread's run () method to turn it into a Pipeline Thread and to create a Han Dler So, other threads can assign tasks to it:

@Overridepublic void Run () {try {//preparing a looper on current thread//The current thread is being detected implicitly Looper.prepare ();//Now, the handler would automatically bind to the//Looper that's attached to the current thread//you Don ' t need to specify the Looper Explicitlyhandler = new Handler ();//After the following line the thread would start//run Ning the message loop and won't normally//exit the loop unless a problem happens or you//quit () the Looper (see below ) Looper.loop ();} catch (Throwable t) {log.e (TAG, "halted due to an error", T);}}

After this, you can just pass the handler to any other thread. It has a Thread-safe interface that includes many operations and the most straightforward ones is postMessage () and its relatives.

Note: The Handler interface have many more cool operations, especially related to message passing, that I'll not cover In this example.

For example, imagine another thread have a reference to the handler , is created in our Pipeline thread. Here's how this other thread can schedule a operation to being executed in the Pipeline thread:

Handler.post (New Runnable () {@Overridepublic void Run () {//This'll be do in the Pipeline Thread}});

In our case, we'll use this idiom to schedule download tasks to being performed (on the download pipeline thread) when the User clicks a button (which is handled on the UI thread). We'll also use it the other-around–when the download thread notifies the activity that a download have completed (o n the download thread), the activity would use a Handler that's attached to the UI thread to make sure Date the UI on the UI thread only (which is a requirement of Android UI).

By the the-the-the-the-UI thread has a Looper created for it implicitly so can just create a Handler in activity ' s onCreate () and it'll work fine:

    @Override public    void OnCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.main);                Create the Handler. It'll implicitly bind to the Looper        //That's internally created for this thread (since it's the UI thread)        ha Ndler = new Handler ();    }
Implementation Details

If you understood the "idea of" Looper and Handler , the rest is details. Basically, I created a Downloadtask class that emulates a download task of a random duration. I did not want to does actual downloads because I didn ' t want to eat your data plans, but it's straightforward to change thi s into the real work. Then, the Downloadthread have an interface, a allows to enqueue Downloadtask instances and also to request it to exit gracefully. There is also the Downloadthreadlistener interface This allows the download thread to notify some other E Ntity about status updates. In our case, that interface'll be implemented by the downloadqueueactivity because we want to reflect T He download progress in the UI.

At-this-point, however, we need-another Handler , haven one that's attached to the UI thread. The Downloadthreadlistener is notified by the downloadthread from the download thread itself, but the AC tion we want to take (updating the ProgressBar and the TextView) needs to is done from the UI thread. Therefore we use the UI handler like this:

note! This might is called from another thread@overridepublic void Handledownloadthreadupdate () {//We want to modify the Progre SS Bar So we need to does it from the UI thread//How can we make sure the code runs in the UI thread? Use the Handler!handler.post (new Runnable () {@Overridepublic void Run () {//update the UI etc}});}

Note: In the case of doubt, it's also OK to call a handler from its own thread.

Of course, you should read the code and the comments to understand things clearly.

Also, it ' s better to does things like background downloads in a service, as described in my previous article.

Conclusion

LooperS and Handlers allow you to do cool things. However, they was related to concurrency which was often a slippery area. Be sure to ask your questions and give feedback in the Comments–and to stay tuned for updates!

Attachment: The complete project source

In general. You can leave a response, or trackback from your site.

5 Responses to "Android Guts:intro to Loopers and handlers"?
  1. Mark says: April at 8:59

    Isn ' t there a possibility for an NPE in RequestStop () should the handler variable has not yet been assigned? How do I deal with this? Object.wait ()?

    ?
  2. Master says: July at 6:18 am

    Perfect, very nice explation about handler and Looper

    ?
  3. Lydia says: August 3 at 11:47 am

    Nice article explanation are clean. Helped me a lot

    ?
  4. Dirk Bruere says: August 8 at 2:46 am

    You say: "After that, you can just pass the handler to any of the other thread."
    How? Can You show me a example please?

    ?
  5. Rod Jefferys says: September 4 at 6:20 pm

    I'll right away take hold of your RSS feeds as I can not in finding your email subscription hyperlink or newsletter Servi Ce. Do you have any? Kindly allow me understand on order that I may just subscribe. Thanks.

Android Guts:intro to Loopers and handlers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.