android源码解析-异步消息

android源码解析-异步消息

android异步消息中我们常用的就是如下方式

先创建一个handler实例:

private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        //处理message返回结果
};

接着开启一个线程:

new Thread(new Runnable() {
        @Override
        public void run() {
        handler.sendEmptyMessage(2);
        }
    }).start();

我们执行了handler.sendEmptyMessage();方法,但是在主线程接到了返回结果,下面我们来探究一下原因.

原因探究

我们先看Handler.class的构造方法

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

构造方法创建了Looper的实例和MessageQueue的引用对象.创建了Looper的实例也就找到了线程对应的looper和MessageQueue,因为一个MessageQueue对应的只有一个Looper.中间有一句mLooper = Looper.myLooper(); 我们稍后再看.
接下来看Handler调用的sendMessage方法。你会发现所有的方法调用的都是sendMessageAtTime()方法,那我们就看一下sendMessageAtTime()方法吧:

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

Handler的sendMessageAtTime()调用了queue.enqueueMessage()方法也就是messageQueue的入队方法。
我们看一下enqueueMessage:

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
}

我们看到handler把自己的实例放进了msg的target这个到后边会用到,接下来看MessageQueue类的enqueueMessage()方法:

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

里边的for循环就是把消息放到messagequeue里的方法,根据when时间顺序.
至此handler就把sendmessage中的message发送到messagequeue中.其中判断了之前我们定义到msg里的handler实例.
那么MessageQueue是在哪里维护的呢?
看上边的Handler构造方法我们发现mQueue = mLooper.mQueue;这个行代码.
也就是说MessageQueue是在Looper维护的.
首先看一下Looper.prepare()

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

实际上在子线程必须执行Looper.prepare()是因为需要通过sThreadLocal.set(new Looper(quitAllowed));建立Lopper与sThreadLocal的关系.我们再回看Handler的构造方法mLooper = Looper.myLooper(); 这个方法.

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

我们看到直接return了sThreadLocal.get() 这就说明了为什么要执行Looper.prepare(),因为需要先建立和sThreadLocal的关系.

接下来看 Looper.loop();方法是执行从enqueueMessage取出消息.


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 blockif (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();

    }

}

有一个死循环执行queue.next()方法.如果有消息就继续执行.然后执行消息分发msg.target.dispatchMessage(msg);,可以看到msg.target就是我们最开始在enqueueMessage步骤把handler.如果没消息就休息等待.

下面看一下dispatchMessage:

public void dispatchMessage(Message msg) {

    if (msg.callback != null) {

        handleCallback(msg);

    } else {

        if (mCallback != null) {

            if (mCallback.handleMessage(msg)) {

                return;

            }

        }

        handleMessage(msg);

    }

}

最后分发完方法后执行了handleMessage回调方法.handleMessage方法我们再熟悉不过了.就是我们new Handler创建的回调.

总结

Handler通过初始化创建了Looper和实例化了MessageQueue,Looper创建的时候需要先执行Looper.propar(),通过handler构造方法匹配了本地ThreadLocal和线程-Looper-MessageQueue三者的对应关系.
handler通过sendMessage方法执行MessageQueue的enqueueMessage()方法,实现了往MessageQueue插入消息.
Looper.loop()方法从MessageQueue中取出消息.由for循环执行queue.next()方法,然后执行Handler的消息分发msg.target.dispatchMessage(msg);,也就是我们new Handler的回调方法.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值