Handler消息机制

Handler消息机制(封装了线程间的通信)

    主线程中默认实现了Looper.prepare()和Loop.loop()方法

Loop.prepare() 

new Looper(quitAllowed):创建了一个消息队列

sThreadLocal.set();通过threadelocal把looper对象绑定叨当前的主线程中

 

 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));
    }

 private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

new Handler()

通过Looper.myLooper()获取到threadlocal绑定的looper对象从而获取到消息队列

  public Handler(Callback callback, boolean async) {
        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;
    }

 public static Looper myLooper() {
        return sThreadLocal.get();
    }

  mHandler.sendMessage(msg)

msg.target = this :把handler对象赋值给msg.target;

queue.enqueueMessage:把消息加入消息队列中;

   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);
    }
  private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

 Loop.loop()

Looper me = myLooper() 获取到当前线程threadlocal绑定的looper对象

    for (;;)进行死循环查找需要处理的消息 Message msg = queue.next();是个阻塞方法但不会消耗cpu资源;

msg.target.dispatchMessage(msg);调用sendmsg时候的handler的handlermsg方法;

 

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
            msg.target.dispatchMessage(msg);
            // 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.recycle();
        }
    }
    public static Looper myLooper() {
        return sThreadLocal.get();
    }
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

 附:

  ThreadLocal就是为每一个线程维护变量的副本。实现思路:在ThreadLocal类中有一个Map,用于存储每一个线程的变量副本,Map中元素的键为线程对象,而值对应线程的变量副本。我们自己就可以提供一个简单的实现版本:

 

posted @ 2016-11-02 00:02  你好,安卓  阅读(139)  评论(0)    收藏  举报