Android Message Delivery handler message mechanism (i)

Source: Internet
Author: User

Objective:

Whether it is the current project or the previous project, will meet the communication between the threads, communication between components, the current unified use Eventbus to do processing, in summing up learning eventbus before, think or need to learn to summarize the initial implementation of the way, also is not forget beginner's mind it, This is also a reason to learn to summarize the handler message mechanism today.

Handler mechanism to produce background

When an Android application is created, a UI main thread is created, but sometimes we have some time-consuming operations, in order to prevent blocking of the UI main thread, we will put the time-consuming operation into the child thread to process, after processing the UI, but Android does not allow the child threads to manipulate the UI , it violates the principle of the Android single-threaded model (that is, Android UI operations are not thread-safe and these operations must be performed in the UI thread), so Android uses the handler messaging mechanism to communicate between threads.

Main roles of the handler mechanism

Message: Messages that contain the message ID, the message Processing object, and the processed data are queued by MessageQueue and processed by handler.

Handler: Handler, responsible for sending and processing the message. When using handler, you need to implement the Handlemessage (Message msg) method to process a specific message, such as updating the UI.

MessageQueue: Message Queuing, which holds messages sent by handler and executes according to FIFO rules. Of course, storing a message is not a meaningful preservation, but rather a concatenation of the message in the form of a linked list, waiting for the looper to be extracted.

Looper: The message pump continuously extracts message execution from the MessageQueue. Therefore, a MessageQueue needs a looper.

Thread: Threads that are responsible for dispatching the entire message loop, that is, the execution site of the message loop.

Handler mechanism mainly uses 1.)send messages, send messages between different threads, using the method of Sendxxx ();
Sendemptymessage (int); // send an empty message sendMessage (msg); // send message, can carry parameter in message long); // send a message at a future point in time long); // delay NMS Send Message

Example:

Main thread Definition Handler

Handler Mhandler =NewHandler () {@Override Public voidhandlemessage (Message msg) {Super. Handlemessage (msg); Switch(msg.what) { Case0:                    //finish the main interface update, get the dataString data =(String) msg.obj;                    Textview.settext (data);  Break; default:                     Break; }        }    };

A child thread sends a message informing handler that the UI update is complete

    Private voidgetdatafromnet () {NewThread (NewRunnable () {@Override Public voidrun () {//time consuming operation, send message to handler after completion, complete UI update;Mhandler.sendemptymessage (0); //need data transfer, using the following method;Message msg =NewMessage (); Msg.obj= "Network data";//can be the basic type, can be an object, can be a list, map, etc.;mhandler.sendmessage (msg);    }}). Start (); }
2.)To schedule a task to perform a task in the future, using the method postxxx ();
Post (Runnable); // Submit Scheduled Tasks to execute immediately long); // submit a scheduled task to be executed at a future point in time long); // Submit scheduled Task delay NMS execution

Example:

Main thread Definition Handler

  Private Handler mhandler=New Handler ();

Child thread submission Task Update UI

    Private voidgetdatafromnet () {NewThread (NewRunnable () {@Override Public voidrun () {//time consuming operation, submitting task update UI after completion                FinalString data = "Network Information"; Mhandler.post (NewRunnable () {@Override Public voidrun () {textview.settext (data);            }                });    }}). Start (); }
Handler mechanism extension

To make it easier to use the handler messaging mechanism, Android also offers several ways to expand, and internal implementations are based on the handler message mechanism

1.)Activity.runonuithread (Runnable)
    Private voidgetdatafromnet () {NewThread (NewRunnable () {@Override Public voidrun () {//time consuming operation, submitting task update UI after completion                FinalString data = "Network Information"; Runonuithread (NewRunnable () {@Override Public voidrun () {textview.settext (data);            }                });    }}). Start (); }
2.) view.post (Runnable)
   Private voidgetdatafromnet () {NewThread (NewRunnable () {@Override Public voidrun () {//time consuming operation, submitting task update UI after completion                FinalString data = "Network Information"; Textview.post (NewRunnable () {@Override Public voidrun () {textview.settext (data);            }                });    }}). Start (); }

5.) Use asynctask instead of thread

    Private voidgetdatafromnet () {mytask task=NewMyTask ();    Task.execute (); }    Private classMyTaskextendsAsynctask {//when a background thread executes@Overrideprotectedobject Doinbackground (Object ... params) {////time-consuming operation,String data = "Network Information"; returndata; }        //The background thread executes the end of the operation, where the parameter result is returned by Doinbackground@Overrideprotected voidOnPostExecute (Object result) {Super. OnPostExecute (Result);        Textview.settext ((String) result); }    }

Summary:

At this point handler message simple summary to this end, more internal specific implementation can refer to

1.http://www.cnblogs.com/angeldevil/p/3340644.html

2.http://blog.csdn.net/fei0724/article/details/8664462

Android Message Delivery handler message mechanism (i)

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.