Combine the source code to explain the Android message model

Source: Internet
Author: User

Handler is the core of the entire message system, is handler sent to MessageQueue message, and finally Looper is to inform handler, so from the handler.

First, Handler

There are many handler constructors, but they are essentially the same:

Public Handler () {This          (null, FALSE);      }  

  

Public Handler (Callback Callback, Boolean async) {          //Auto bind when the Looper          mlooper = Looper.mylooper () of the front thread;          if (Mlooper = = null) {              throw new RuntimeException (                  "Can ' t ' create handler inside thread that have not called Looper. Prepare () ");//From this we can see that the creation of handler must have Looper          }          mqueue = Mlooper.mqueue;  Looper MessageQueue          Mcallback = callback;     A back-off interface          masynchronous = async;        }  

This is the handler that creates the given Looper:

Public Handler (Looper Looper, Callback Callback, Boolean async) {mlooper = Looper;         Mqueue = Looper.mqueue;         Mcallback = callback;     masynchronous = async; }

Second, the source code of Looper:

public static Looper Mylooper () {         return sthreadlocal.get ();     }  

General steps to create a looper in a child thread: (This is my own writing, not the source code)

Class MyThread extends thread{public          Handler Handler;          Public Looper Looper;          public void Run () {              looper.prepare ();//Create a Looper              Looper = Looper.mylooper ();              Handler = new Handler () {                 @Override public              void Handlemessage (Message msg) {                    System.out.println (" Currentthread-> "+thread.currentthread ());                 }             ;             Looper.loop ();//Let the message loop up          }      

Here's a look at the Looper.prepare,looper.loop method:

public static void Prepare () {          prepare (true);      }        private static void Prepare (Boolean quitallowed) {          if (sthreadlocal.get () = null) {//sthreadlocal allows the thread to maintain its own independent object.              throw new RuntimeException ("Only one Looper could be created per thread");          }          Sthreadlocal.set (New Looper (quitallowed));      }  

Looper.prepare ():

public static void Loop () {final Looper me = Mylooper (); if (me = = null) {//If Looper is empty throw new RuntimeException ("No Looper;          Looper.prepare () wasn ' t called on this thread. ");            Final MessageQueue queue = Me.mqueue;          。。。。 for (;;) {Message msg = Queue.next ();//Loop next if (msg = = NULL) {//No Message Indicat                  ES the message queue is quitting.              Return                } 。。。。  Msg.target.dispatchMessage (msg); Distributing the message, Msg.target is handler if (logging! = null) {logging.println ("<<<<< Fi              nished to "+ Msg.target +" "+ msg.callback);                } 。。。。  Msg.recycle (); Recycle msg to Msgpool}} 

From this code can be seen looper constantly check messagepool whether there is ==message, some words through the handler of DispatchMessage (msg) sent out, using handler to interact with the outside world.

Source code for 3.Message:

public static message obtain () {   //Get Message Object         synchronized (spoolsync) {             if (sPool! = null) {                 message M = SPool;                 SPool = M.next;                 M.next = null;                 spoolsize--;                 return m;             }         }         return new Message ();  No, the new     

Handler.obtainmessage () Method:

Public final Message Obtainmessage ()     {         return message.obtain (this);  Through the obtain method of message     }  

  

public static message obtain (Handler h) {  //Is this method        message m = obtain ();  The final call is the Obtain method        M.target = h;      Target is handler          return m;    

Read the above source code, I believe you must have a certain understanding of handler,message,looper, programming often encountered in the method, know how to use it. In fact, learn Android must often read the source code is very useful.

4. Below is the code, example analysis:

<pre name= "code" class= "Java" >package com.example.handler_01; Import Android.  Manifest.permission;  Import android.app.Activity;  Import Android.os.Bundle;  Import Android.os.Handler;  Import Android.os.Handler.Callback;  Import Android.os.Message;  Import Android.view.Menu;  Import Android.view.MenuItem;  Import Android.view.View;  Import Android.view.View.OnClickListener;  Import Android.widget.Button;  Import Android.widget.ImageView;  Import Android.widget.TextView;    Import Android.widget.Toast;      public class Mainactivity extends Activity implements onclicklistener{private TextView TextView;                  Private button button; Private Handler Handler = new Handler (new Callback () {//Intercept message public boolean handlemessage (Message msg)              {//Intercept handler sent message Toast.maketext (Getapplicationcontext (), "" "+1, 1). Show ();              return false;          Return false;//If True, then proof intercept, the following handlemessage will not execute! }      }{public void Handlemessage (Message msg) {Toast.maketext (Getapplicationcontext (), "" "+2, 1). Show ();              Person person = (person) msg.obj;          System.out.println (Person.tostring ());            }      };            Private myrunnable myrunnable=new myrunnable ();            Private ImageView ImageView;      private int images[]={r.drawable.a1,r.drawable.a2,r.drawable.a3};            private int index; Class Myrunnable implements runnable{//constantly updated images, 3 rotations @Override public void run () {index++            ;  index=index%3;            Continuous circulation Imageview.setimageresource (Images[index]);  Handler.postdelayed (myrunnable, 1000);          Execute myrunnable System.out.println ("Threads in Myrunnable:" +thread.currentthread ()) every once in a while, and//run on the current main thread! }} @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (Savedi          Nstancestate); Setcontentview (r.layout.acTivity_main);          TextView = (TextView) Findviewbyid (R.id.textview);          ImageView = (ImageView) Findviewbyid (R.ID.IMAGEVIEW1);          Button = (button) Findviewbyid (R.id.button1);          Button.setonclicklistener (this); New Thread () {@Override public void run () {try {Thread.s                      Leep (2000);                    /*message message = new Message ();                                           message.arg1=88;*/Message message = Handler.obtainmessage ();                     person person = new person ();                     person.age=20;                     Person.name= "Chaochao";                     Message.obj=person;                  Handler.sendmessage (message);//sends a message to the main thread in a child thread. } catch (Interruptedexception e) {//TODO auto-generated catch block E.printsta                  Cktrace ();        }                                }  }.start ();      Handler.postdelayed (myrunnable, 1000);              } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.button1:              Handler.removecallbacks (myrunnable);              Handler.sendemptymessage (1);            Break          Default:break;          }} class person{public int age;                    public String name;          Public String toString () {return "name=" +name+ "age=" +age;   }      }  }

The layout is simple, not the code.

Operation Result:

You can have a picture of yourself ....

The use of handler is analyzed in detail at the rear.

Forwarding Please specify the source: http://www.cnblogs.com/jycboy/p/handlerjx.html

Combine the source code to explain the Android message model

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.