Android authoritative Programming Guide-notes (24th Looper Handler and Handlerthread)

Source: Internet
Author: User

Asynctask is the simplest way to perform a background thread, but it does not apply to repetitive and long-running tasks.

1. Looper

In Android, a thread has a message queue, and a thread that uses Message Queuing is called a message loop. The message loop loops through the queue to check for new messages.

The message loop consists of threads and Looper, and the Looper object manages the thread's message queue.

The main thread is a message loop, so also has looper, the main thread of all the work is done by its looper, Looper constantly grabbed the message from the message queue, and then complete the task specified by the message.

2. Message

A message is an instance of the message class that has several instance variables, three of which need to be defined at implementation time.

1.What: User-defined int message code to describe the message.

2.obj: User-specified object that is sent with the message.

3.target: Handles the handler of the message.

3. Handler

The target of the message is an instance of the handler class, handler can be thought of as the short name of the message handler, and when a message is created it is automatically associated with a handler, and when the message is processed, The handler object is responsible for triggering message processing events,

Handler is not just a target for handling message, but also an interface for creating and publishing a message.

4. Relationship

Looper has a message inbox, so the message must be published or processed on Looper. To work with Looper, Handler always cites it.

A handler is associated with only one looper, and a message is associated with only one target handler (also known as the message destination). Looper has an entire message queue, and multiple message references can refer to the same target handler.

Multiple handler can also be associated with a looper, which means that a handler message may be stored in the same message queue as another handler.

5. Using handler

You typically do not need to manually set the target handler for a message. When creating information, call the Handler.obtainmessage () method. When the other message field is passed to him, the method automatically sets the target to the handler object.

To avoid creating a new Message object, the Handler.obtainmessage () method fetches the message from the public loop.

Once you get the message, you can call the Sendtotarget () method to send it to its handler, and handler will place the message at the end of the Looper message queue.

When Looper obtains a specific message in the message queue, it is sent to the message destination for processing. Messages are typically handled in the handler.handlemessage () implementation method of the target.

6. Handlerthread

The Handlerthread class helped us complete the process of building the looper, so long as it was inherited, it would save some work.

 Public classThumbnaildownloader<t>extendsHandlerthread {Private Static FinalString TAG = "Thumbnaildownloader"; Private Static Final intmessage_download = 0;//Identify download Requests    PrivateBoolean Mhasquit =false; PrivateHandler Mrequesthandler;//stores a reference to handler, which is responsible for managing the download request message queue on a thumbnaildownloader background thread.    This handler is also responsible for extracting and processing download request messages from the message queue. //onlooperprepared () is called before Looper checks the message queue for the first time. @Overrideprotected voidonlooperprepared () {Mrequesthandler=NewHandler () {@Override Public voidHandlemessage (Message msg) {//the call to the Handler.handlemessage () method is triggered when the download message in the queue is taken out and can be processed. //Processing Operations            }        }; }     Public voidQueuethumbnail (T target, String URL) {//when the other message field is passed to it, the method automatically sets the target to the handler object (Obtainmessage)//The Sendtotarget () method sends a message to its handler, and handler places the message at the end of the Looper message queue. mrequesthandler.obtainmessage (message_download,target). Sendtotarget (); } Public voidClearqueue () {mrequesthandler.removemessages (message_download); }}

This is called in the main thread:

New thumbnaildownloader<>// calling the Getlooper () method after the start () method is a way to ensure thread-ready processing. Potential competition can be avoided.  // call Mthumbnaildownloader.queuethumbnail (holder, URL) when needed ;

7. Thread Interaction

The main thread will now be able to invoke the method of the threads in a timely manner for downloading pictures. But there is one problem, that is, how do the download threads update the view after downloading a task? We know that the UI can only be updated in the main thread, so we use the main thread to declare a Handler, pass it to the download thread, and let the download thread perform the update operation on the main thread after the download is complete. The callback is used here because the method of the main thread cannot be directly referenced.

7.1 In the download thread:

//Thumbnaildownloader, which is the download thread//member DeclarationPrivateHandler Mresponsehandler;PrivateThumbnaildowloadlistener<t>Mthumbnaildownloadlistener;//Callback Interface Public InterfaceThumbnaildowloadlistener<t> {/** When the picture is downloaded, it can be given to the UI to be displayed, and the method in the interface is called.         * This method is used to delegate the task of processing downloaded images to another class (photogalleryfragment) so that the Thumbnaildownloader can pass the download results to other view objects. */    voidonthumbnaildownloaded (T target, Bitmap thumbnail);} Public voidSetthumbnaildownloaderlistener (thumbnaildowloadlistener<t>listener) {Mthumbnaildownloadlistener=Listener;}//passing the Handler of the main thread through the constructor function PublicThumbnaildowloader (Handler responsehandler) {Super(TAG); Mresponsehandler=ResponseHandler;}

This way, the main thread can get the download thread to the Handler and callback interface instances of the main thread by invoking these methods.

7.2 In the main thread

//member DeclarationPrivateThumbnaildowloader<photoholder>Mthumbnaildownloader;//passing instances to the download thread//This Handler is established in the main thread, so it is associated with the main thread LooperHandler ResponseHandler =NewHandler (); Mthumbnaildownloader=NewThumbnaildowloader<>(ResponseHandler); Mthumbnaildownloader.setthumbnaildownloaderlistener (NewThumbnaildowloader.thumbnaildowloadlistener<photoholder>() {@Override Public voidonthumbnaildownloaded (photoholder target, Bitmap thumbnail) {drawable drawable=Newbitmapdrawable (getresources (), thumbnail);        Target.binddrawable (drawable); }    });

8. Thread Interaction

Now, with Mresponsehandler, the download thread has access to the Handler bound to the main thread Looper. Also, Thumbnaildownloadlistener uses the returned BITMAP to perform UI update operations. Specifically, this is achieved by onthumbnaildownloaded, using the newly downloaded Bitmap to set the drawable of the Photoholder.
Similar to the request to download pictures on the download thread, we can also return a custom message to the main thread and ask to display the downloaded picture. However, this requires another Handler subclass, and a handlemessage (...) override method. For convenience, we turned to another convenient Handler method--post (Runnable).

Mresponsehandler.post (new  Runnable () {    @Override    publicvoid  run () {        if (Mrequestmap.get (target)! = URL | |                 mhasquit) {            return;        }        Mrequestmap.remove (target);        mthumbnaildownloadlistener.onthumbnaildownloaded (target, bitmap);}    );

In this case, the newly created Runnable object is treated as a callback method of the message and executes the run () method directly, so it is equivalent to sending a message stating what to do instead of giving the object and message type to Handler, so Handler decides what to do.

Android authoritative Programming Guide-notes (24th Looper Handler and Handlerthread)

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.