Handler机制

来源:互联网 发布:淘宝买银饰可靠吗 编辑:程序博客网 时间:2024/05/19 07:42

   虽然已经有那么多人写了,多个角度说不定哪句说到你点上了。

   首先这是我理解的handler工作流程:


   我分为四步:1,创建handler关联looper,2,获取消息,3,发送消息,4,处理消息


一,创建Handler并关联Looper

    好的演讲总有个故事样的开头,例如有的演讲家会说,我先给大家讲个故事,或者今天早上我遇到了这样一件事什么什么的,我也给大家举个栗子吧:

<span style="font-family:FangSong_GB2312;font-size:14px;">public class MainActivity extends Activity {    private Handler handler1;    private Handler handler2;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    handler1 = new Handler();    new Thread(new Runnable() {      @Override      public void run() {        handler2 = new Handler();      }    }).start();  }}</span>

   如果现在运行一下程序,崩溃了,提示的错误信息为 Can't create handler inside thread that has not called Looper.prepare() 。说是不能在没有调用Looper.prepare() 的线程中创建Handler,那我们尝试在子线程中先调用一下Looper.prepare()呢,代码如下所示:

<span style="font-family:FangSong_GB2312;font-size:14px;">new Thread(new Runnable() {  @Override  public void run() {    Looper.prepare();    handler2 = new Handler();  }}).start();</span>
   这时就不会出错了。希望以上废话没有消耗你太多精力。

   我们创建Handler时通常会调用Handler()方法,没有参数,它不干非要调用下面这个方法:

<span style="font-family:FangSong_GB2312;font-size:14px;">public Handler(Callback callback, boolean async) {        if (FIND_POTENTIAL_LEAKS) {            final Class<? extends Handler> klass = getClass();            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&                    (klass.getModifiers() & Modifier.STATIC) == 0) {                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +                    klass.getCanonicalName());            }        }        mLooper = Looper.myLooper();        if (mLooper == null) {            throw new RuntimeException(                "Can't create handler inside thread that has not called Looper.prepare()");        }        mQueue = mLooper.mQueue;        mCallback = callback;        mAsynchronous = async;    }</span>
    if不用看,接下来mLooper=Looper.myLooper很显然是要给Handler关联Looper, 点进去,看Loop是怎么来的。

<span style="font-family:FangSong_GB2312;font-size:14px;"> public static @Nullable Looper myLooper() {        return sThreadLocal.get();    }</span>
    这个sThreadLocal是个ThreadLocal类的对象,别看名字是这样,其实它没有继承任何类,包括Thread类,我把它理解成一个保险箱,放它所在的类的变量,很安全(线程安全),所以它里面的东西,都是它所在的类的东西。它现在要返回当前类的Looper,它得有啊。Ctrl+F搜索"sThreadLocal.set"就找到它是怎么有了Looper了。

<span style="font-family:FangSong_GB2312;font-size:14px;">    private static void prepare(boolean quitAllowed) {        if (sThreadLocal.get() != null) {            throw new RuntimeException("Only one Looper may be created per thread");        }        sThreadLocal.set(new Looper(quitAllowed));    }</span>
    最后一行代码就是这个set方法了,在这里new了个Looper,并且给了当前类,它所在的方法叫prepare,这就是为什么要调用prepare了。而且而且呀,这个if要看的,它说如果保险箱里有Looper就抛错呢,这就是为什么一个thread只有一个looper了。进去看下Looper的构造方法:

<span style="font-family:FangSong_GB2312;font-size:14px;">  private Looper(boolean quitAllowed) {        mQueue = new MessageQueue(quitAllowed);        mThread = Thread.currentThread();    }</span>
   哎呀呀,自带MessageQueue,还要关联当前Thread呢。上段代码的set方法也把looper关联到线程了,这样它们就互相关联了,一个thread一个looper,一夫一妻。

   但是有UI线程我们没有调用prepare方法,为什么呢。我们写java程序的时候熟悉的main入口方法还记得伐,就是public static void main(String[] args),它也是android程序的入口,你在ActivityThread类里,这个方法里调用了Looper.prepareMainLooper()方法。

<span style="font-family:FangSong_GB2312;font-size:14px;">public static void main(String[] args) {               Looper.prepareMainLooper();        ActivityThread thread = new ActivityThread();        thread.attach(false);        if (sMainThreadHandler == null) {            sMainThreadHandler = thread.getHandler();        }        if (false) {            Looper.myLooper().setMessageLogging(new                    LogPrinter(Log.DEBUG, "ActivityThread"));        }        // End of event ActivityThreadMain.        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);        Looper.loop();        throw new RuntimeException("Main thread loop unexpectedly exited");    }</span>

   而Looper.prepareMainLooper()方法调用了prepare方法new Looper去了,这样主线程就有了looper了,看下面。

<span style="font-family:FangSong_GB2312;font-size:14px;">    public static void prepareMainLooper() {        prepare(false);        synchronized (Looper.class) {            if (sMainLooper != null) {                throw new IllegalStateException("The main Looper has already been prepared.");            }            sMainLooper = myLooper();        }    }</span>

    而且上面的上面那段代码倒数第二句Looper.loop()就开始处理消息了。

<span style="font-family:FangSong_GB2312;font-size:14px;">    public static void loop() {        final Looper me = myLooper();        if (me == null) {            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");        }        final MessageQueue queue = me.mQueue;        // Make sure the identity of this thread is that of the local process,        // and keep track of what that identity token actually is.        Binder.clearCallingIdentity();        final long ident = Binder.clearCallingIdentity();        for (;;) {            Message msg = queue.next(); // might block            if (msg == null) {                // No message indicates that the message queue is quitting.                return;            }            // This must be in a local variable, in case a UI event sets the logger            Printer logging = me.mLogging;            if (logging != null) {                logging.println(">>>>> Dispatching to " + msg.target + " " +                        msg.callback + ": " + msg.what);            }            msg.target.dispatchMessage(msg);            if (logging != null) {                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);            }            // Make sure that during the course of dispatching the            // identity of the thread wasn't corrupted.            final long newIdent = Binder.clearCallingIdentity();            if (ident != newIdent) {                Log.wtf(TAG, "Thread identity changed from 0x"                        + Long.toHexString(ident) + " to 0x"                        + Long.toHexString(newIdent) + " while dispatching to "                        + msg.target.getClass().getName() + " "                        + msg.callback + " what=" + msg.what);            }            msg.recycleUnchecked();        }    }</span>
  它取出Looper,再取出它的MessageQueue,进入for(;;){}无限循环,加一句,这里以前是while(true){}无限循环,不知道为什么换成for了,可能跟其它代码有关。这段大致意思是,首先取消息,而且注释里有个might block说明可能会阻塞,然后分发消息,然后回收消息recycleUnchecked()。

  总结:1,自己new的线程要先调用prepare方法,它里面new出了looper,才能创建handler。

      2,主线程不用调用prepare方法就能创建handler,主线程的main方法调用的prepareMainLooper里调用了prepare方法.

  创建handler关联looper就讲完了。

二,获取消息

  首先要说明的是官方不建议new一个Message再发送,而是用obtain方法从回收队列中取一个再用一次。为什么呢,其实想想也是,new一个对象就要开辟一块内存,初始化很多默认属性,如果有过时不用的一块内存为什么不用呢,如果说感觉它过时为什么不回收,一会儿new一会儿回收一会儿new一会儿回收太麻烦,不如放那儿算了,让回收队列引用着,别回收,需要的时候再拿来设好需要的属性接着用,所以不是你重新设定好的属性不要用,万一上一次设定的不是你要的呢。而且我觉得这种回收适合那种要很多很多的对象,而且每个生命周期不长。

  其次,要是你直接new一个Message就发送了,就不要看这第二步了。

  注意,这是Message的回收队列,不是某个线程要处理的消息队列。

  发送消息时无论是调用Handler的obtainMessage方法还是Message的众多obtain方法,它最终都要调用Message.obtain()方法,其它操作都是对拿到的Message对象进行一些属性的赋值,所以获取Message的方法就看这个Message.obtain()方法。它的作用是从消息的回收队列中返回一个Message,我觉得要想知道怎么返回的,先知道怎么回收的比较好,也就是知道这个回收队列是怎么产生的比较好,还是先看上面代码里最后那句recycleUnchecked()方法吧。

<span style="font-family:FangSong_GB2312;font-size:14px;">void recycleUnchecked() {        // Mark the message as in use while it remains in the recycled object pool.        // Clear out all other details.        flags = FLAG_IN_USE;        what = 0;        arg1 = 0;        arg2 = 0;        obj = null;        replyTo = null;        sendingUid = -1;        when = 0;        target = null;        callback = null;        data = null;        synchronized (sPoolSync) {            if (sPoolSize < MAX_POOL_SIZE) {                next = sPool;                sPool = this;                sPoolSize++;            }        }    }</span>
  
  哇,回收的时候人家已经把原来的值清空的,这巴掌,piapia嘎嘣脆大哭,好吧,不是你设定的值也能用了,先判空就行。

  拿出纸笔,我们开始画图。

  这个回收池叫sPool,它是个Message,而且还是静态的,刚开始它是空的,写上mPool,第一次来个消息,画个框,第一句next=sPool,sPool还空,第二句sPool=this,sPool里是新消息的地址,容量加。

  

  又来一个废物Message,next=sPool,新的消息的next里存sPool的内容,即原来消息的地址,sPool=this,新消息的地址存到sPool中。

  


    再来一个我就不画了,回收队列就是这样建好的,回来看obtain方法获取回收队列重新使用。

<span style="font-family:FangSong_GB2312;font-size:14px;"> public static Message obtain() {        synchronized (sPoolSync) {            if (sPool != null) {                Message m = sPool;                sPool = m.next;                m.next = null;                m.flags = 0; // clear in-use flag                sPoolSize--;                return m;            }        }        return new Message();    }</span>
  “Message m=sPool",m里也是sPool的地址,也就是后来那个消息的地址,"sPool=m.next", sPool现在放它的下一条的地址,也就是sPool现在指向第一条消息了。"m.next=null",后来那个消息的next不存第一条消息的地址了,上面那个图的横线消息了。"return m" 返回m, 上面的图变成更上面那张了,下次再取你自己画吧。

   获取消息就讲完了。

三,发送消息 
  不管你喜欢调用sendMessage(Message)还是sendEmptyMessage()还是post-runnable方法,最后都会调用sendMessageAtTime,post-runnable方法先从Message的回收队列里拿一个,再把runnable放进去,跟直接发message一样一样的。回到sendMessageAtTime,内容如下:

<span style="font-family:FangSong_GB2312;font-size:14px;"> public boolean sendMessageAtTime(Message msg, long uptimeMillis) {        MessageQueue queue = mQueue;        if (queue == null) {            RuntimeException e = new RuntimeException(                    this + " sendMessageAtTime() called with no mQueue");            Log.w("Looper", e.getMessage(), e);            return false;        }        return enqueueMessage(queue, msg, uptimeMillis);    }</span>
如果handler的消息队列是空就出错了,不空的话调用enqueueMessage方法,并且把handler的消息队列传进去,我猜是要把你要发的消息放到里面去。

<span style="font-family:FangSong_GB2312;font-size:14px;">    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {        msg.target = this;        if (mAsynchronous) {            msg.setAsynchronous(true);        }        return queue.enqueueMessage(msg, uptimeMillis);    }</span>

"msg.target=this"把消息和handler关联了起来,一个消息只属于一个handler,然后我们看enqueueMessage方法:

<span style="font-family:FangSong_GB2312;font-size:14px;">boolean enqueueMessage(Message msg, long when) {    if (msg.target == null) {        throw new IllegalArgumentException("Message must have a target.");    }    if (msg.isInUse()) {        throw new IllegalStateException(msg + " This message is already in use.");    }    synchronized (this) {        if (mQuitting) {            IllegalStateException e = new IllegalStateException(                    msg.target + " sending message to a Handler on a dead thread");            Log.w(TAG, e.getMessage(), e);            msg.recycle();            return false;        }        msg.markInUse();        msg.when = when;        Message p = mMessages;        boolean needWake;        if (p == null || when == 0 || when < p.when) {            // New head, wake up the event queue if blocked.            msg.next = p;            mMessages = msg;            needWake = mBlocked;        } else {            // Inserted within the middle of the queue.  Usually we don't have to wake            // up the event queue unless there is a barrier at the head of the queue            // and the message is the earliest asynchronous message in the queue.            needWake = mBlocked && p.target == null && msg.isAsynchronous();            Message prev;            for (;;) {                prev = p;                p = p.next;                if (p == null || when < p.when) {                    break;                }                if (needWake && p.isAsynchronous()) {                    needWake = false;                }            }            msg.next = p; // invariant: p == prev.next            prev.next = msg;        }        // We can assume mPtr != 0 because mQuitting is false.        if (needWake) {            nativeWake(mPtr);        }    }    return true;}</span>

这个方法,也是需要拿出纸笔画画的,最后的结果就是Handler中的消息队列按照时间when顺序排列,时间短的在前,最先被取出来。
这个方法最后返回true表示插入成功,中间返回false了就表示出错了。发送消息就这些了。
四,处理消息

  最后一步,加油加油。

  主线程里调用的loop方法不知道你还记不记得,它取出消息msg后就会执行msg.target.dispatchMessage(msg);方法,也就是处理方法。

  msg的target是Handler,查看Handler的dispachMessage方法如下:

<span style="font-family:FangSong_GB2312;font-size:14px;"> public void dispatchMessage(Message msg) {        if (msg.callback != null) {            handleCallback(msg);        } else {            if (mCallback != null) {                if (mCallback.handleMessage(msg)) {                    return;                }            }            handleMessage(msg);        }    }</span>
msg.callback如果不等于空,说明刚才发送消息是调用的post-runnable系列方法,它里面会在获取到消息后把runnable放在消息中,到这里取出执行就可了。如果不为空,一种情况是mCallback不为空就调用它的handlerMessage方法处理这个消息,从名字可以看出它是个成员变量,可以搜索到它是在Handler的构造方法中赋值的,自已看,如果构造handler时调用的是这个构造方法它也是为它进行上面讲的方法,放入队列等待执行。别一种情况是mCallback为空,调用的Handler其它构造方法创建的handler,这时调用handleMessage方法,点过去发现它是空的,这就是我们要实现它的原因,也是它能够被调用到的原因。而且因为main方法中调用的loop方法,loop方法中调用的dispachMessage方法,所以它们都是运行在主线程的,而且post-runnable方法发消息的话也是运行在主线程的。






1 0
原创粉丝点击