Android Handler消息机制

本文已同步发表到我的微信公众号,扫一扫文章底部的二维码或在微信搜索 “程序员驿站”即可关注,每天都会更新优质技术文章。

我们都知道,android许多异步操作都是基于Handler的一系列封装,Handler为何这么神奇?下面我们就来一步步开始分析。

Handler基本使用

主线程:

 private Handler handlerInMainThread = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0x11) {
                Log.d(TAG, "currentThread = "+ Thread.currentThread().getName()+",msg = " +msg.obj);
                Message message = new Message();
                message.what = 0x12;
                message.obj = "接收到主线程回应的消息 ";
                handlerInSonThread.sendMessage(message);
                return true;
            } else {
                return false;
            }
        }
    });

 

 

子线程:

 

 

    private Handler handlerInSonThread;

    public void sendMsg(View view) {
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                handlerInSonThread = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        if (msg.what == 0x12) {
                            Log.d(TAG, "currentThread = "+ Thread.currentThread().getName()+", msg = " +msg.obj);
                        } else {
                            super.handleMessage(msg);
                        }
                    }
                };

                Message message = new Message();
                message.what = 0x11;
                message.obj = "接收到子线程发送过来的消息";
                handlerInMainThread.sendMessage(message);

                Looper.loop();
            }
        }.start();
    }

 

点击运行,我们在日志中可以看到如下信息:

 

D/MainActivity: currentThread = main, msg = 接收到子线程发送过来的消息
D/MainActivity: currentThread = Thread-20, msg = 接收到主线程回应的消息 

以上都是我们经常使用的方式,没什么讲的,下面就从源码层面对Handler进行一步步分析。

源码分析

为了便于查看,我画了个类图,可能不是很规范,将就着看吧。

 完成整个消息传递,源码中主要涉及到四个类,分别是Handler,Message,MessageQueue,Looper.

1.Looper

从基本使用中我们知道,在子线程中获取主线程中的消息,我们使用到了Looper的prepare()和loop()方法。可能有人会问,为何主线程中接收消息没有调用prepare()和loop()呢?其实不是没有调用,而是这个事情系统帮我做了。

我们先看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));
    }

我们看到在prepare方法中创建了一个Looper,并且将该Looper放入sThreadLocal中,sThreadLocal是ThreadLocal 对象,用来存储变量。我们再看看Looper的构造方法

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

到这里我们知道prepare主要完成MessageQueue的初始化操作。

我们再看看loop方法

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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

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

首先调用myLooper方法拿到当前的Looper对象me,继而拿到对应的MessageQueue对象,然后开始一个无限循环,通过MessageQueue的next方法(该方法是阻塞式的)从队列中拿到Message,然后在调用

 msg.target.dispatchMessage(msg);

将消息分发出去。(msg.tartget就是我们创建的Hanlder对象,后面会有分析)

2.Handler

我们先看Handler对象构造方法

    public Handler() {
        this(null, false);
    }
    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的myLooper方法拿到当前Looper对象,再根据获取到的Looper对象拿到MessageQueue对象,从而完成了Handler对象与MessageQueue、Looper的绑定。

然后再看下sendMessage方法具体做了啥

    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
    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);
    }

再来看看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将当前的msg放入到消息队列中。

从Looper的loop方法,我们知道,通过for无限循环,拿到msg,然后调用msg.target.dispatchMessgage完成消息的分发出去。

    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }
    

handleMessage方法就是我们在子线程中重写方法。

             handlerInSonThread = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        if (msg.what == 0x12) {
                            Log.d(TAG, (String) msg.obj);
                        } else {
                            super.handleMessage(msg);
                        }
                    }
                };

到此,基本就完成了Handler从消息发送和接收的整个流程,为了便于查看,我整理了一份时序图

 

关注我的技术公众号"程序员驿站",每天都有优质技术文章推送,微信扫一扫下方二维码即可关注:


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值