我们可不可以在子线程中更新UI系列二Handler原理

本文详细解析了Android中Handler的工作原理,包括消息循环机制、消息队列结构及消息处理流程。介绍了如何利用Handler实现子线程与UI线程间的通信。

上一篇我们说到最好不要在子线程中更新UI,如果没有读过上一篇,麻烦移步到:https://blog.youkuaiyun.com/android_seven/article/details/88818203

看到这里的话,我默认你读过了,那么我们应该子线程怎么和UI线程通信呢,那就是Handler大法了了,那么今天总结一下Handler原理,同样的我们先来看一段代码

    private String TAG="HandlerActivity";
    Button btn;
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        btn=findViewById(R.id.button);
        textView=findViewById(R.id.text);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "run: "+Thread.currentThread().getName());
                       handler.post(new Runnable() {
                           @Override
                           public void run() {
                               Log.d(TAG, "Handler run: "+Thread.currentThread().getName());
                               textView.setText("我更新了。。。");
                           }
                       });

                    }
                }).start();
            }
        });
    }
    Handler handler=new Handler();

这个是Handler的常规用法,我们在主线程中new了一个Handler对象,无论是发消息还是postRunnable,我们通过打印当前线程名都是在主线程中执行了。 那为啥会这样呢,带着问题我们去看Handler的源码,

    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 " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

这个是Handler的构造方法, 我们可以看到这里有Looper、有messageQueue,Callback,然后我们跟到Loop.myLooper(),

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

 

 原来是从ThreadLocal里面取得,那么这个是什么时候去存的呢,我们去看ActivityThread.java这个类是发现主线程中looper对象在main方法中就帮我们创建好,并已经开始循环了,我们看代码

      Looper.prepareMainLooper();

        // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
        // It will be in the format "seq=114"
        long startSeq = 0;
        if (args != null) {
            for (int i = args.length - 1; i >= 0; --i) {
                if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                    startSeq = Long.parseLong(
                            args[i].substring(PROC_START_SEQ_IDENT.length()));
                }
            }
        }
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

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

 所以我们在activity里面去new 一个Handler时,并且在Handler的构造方法中去拿当前线程的looper对象时才不会抛异常退出,那么当我们拿到这个looper对象之后,主要是干啥呢,说到这先看下MessageQueue,我们在拿到looper对象后,并取出了looper对像中的MessageQueue这个对象,那么MessageQueue主要的功能是啥,看名字就大致知道了,是存储消息的队列,其实是个单链表的数据结构,而looper则是轮询器,不停的从MessageQueue里面获取消息,我们在上面代码的最后一行也看到了,那个方法就是不停的去轮询消息且分发给对象的target去处理消息,我们且看代码

 

 /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the 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();

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

        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 traceTag = me.mTraceTag;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;

            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            try {
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (logSlowDelivery) {
                if (slowDeliveryDetected) {
                    if ((dispatchStart - msg.when) <= 10) {
                        Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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();
        }
    }

 

里面有一个msg.target.dispatchMessages(msg),这一段代码是核心,我们记着这个核心调用。当我们调用Handler去sendMessage或者post一个Runnable时都会去最终调用Handler里面的equeueMessage这个方法,贴下代码先: 

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

 这个里面queue也就是之前looper对象取出来的queue,这个里面有个msg.tager=this是个知识点额,它指代的是当前对象也就是当前的Handler,这个方法最终执行到MessageQueue的equeue这个方法,我们来贴下代码,其实就是个消息单链表:

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

 

所以我们的流程就很清楚了,我们在ActivityThread这个main方法里面初始化了主线程的Looper对象,looper对象里面有个MessageQueue对象,并且调用了Looper.looper()这个方法开始一直轮询MessageQueue里面的消息,当我们去new一个Handler去发送消息时,会把消息添加到消息队列中,由于主线程的Looper的looper()这个方法一直在轮询消息队列,所以当查询到消息队列中有消息时便会调用上面的核心调用也就是msg.target.dispatchMessage()去分发消息,而这msg.target,我们在上文提到过,其实就是当前对象Handler,到这里是Handler到这里消息循环分发也就说了,在说说消息的处理,那Handler又是怎么处理的呢,我们来看源码Handler里面的dispatchMessage这个方法:

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

 

这个里面有三种情况:我们先来看第一种:msg.callback!=null的情况,这个callback其实就是runnable,为什么呢,当我们用Handler去post一个runnable时其实就是把runnable去包装成一个Message对象,不信你看源码:

 /**
     * Causes the Runnable r to be added to the message queue.
     * The runnable will be run on the thread to which this handler is 
     * attached. 
     *  
     * @param r The Runnable that will be executed.
     * 
     * @return Returns true if the Runnable was successfully placed in to the 
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     */
    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
       
 private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

点进去getPostMessage(r)这个方法就会发现,所以当我们使用Handler去post一个Runnable 时就会走到这个第一种情况里面来

 处理消息,那又是怎么处理的呢。在往下看,当我们去到的runnable不为null时,就会调用:

 private static void handleCallback(Message message) {
        message.callback.run();
    }

 这个方法,调用的就是runnable的run方法而已,由于Handler是在主线程,所以这个方法是在主线程中执行。

好了,那我们来分析第二种情况:mCallBack不等于null的情况,这个CallBack其实就是我们Handler里面的内部一个接口,我们在创建Handler对象时去传一个实现该接口的对象过来,并赋值更Handler对象里面的mCallBack,这样在调用该接口里面的方法时其实就是调用实现该接口对象里面的重写的回调方法,这个应该很好理解吧,第三种就是普通的咯,我们在两种情况都不符合的情况下便会调用这个方法咯。

 至此。我们已经大概知道了Handler的梗概,流程其实也不难,每个线程都有自己的Looper对象,而这个Looper负责维护一个循环消息,如果有消息便让Handler去处理,而MessageQueue则是用来存放消息的单链表数据结构,Handler调用postRunnable或sendMessage负责往里面存消息,Looper去取完之后会让Handler去处理消息,就是这么个流程。

下一篇,我们在整理下子线程使用Handler和HandlerThread,以及防止Handler引起的内存泄漏,本文如有不正之处,烦请大神指出。

参考博客:https://blog.youkuaiyun.com/fnhfire_7030/article/details/79518819

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值