Handler源码分析

转载请注明来源 https://blog.csdn.net/u011453163/article/details/80162281

Handler的基本使用

一般情况下 我们都是在主线程初始化Handler的,主要是用Handler来处理UI相关的操作。

 mHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
            }
        };

然后在需要操作的时候

  mHandler.sendMessage(msg);

如果是在工作线程中初始化Handler 以上的方法就行不通了

  new Thread(){
            @Override
            public void run() {
                super.run();
                mThreadHandler=new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                    }
                };
            }
        }.start();

初始化的时候直接就报错了

 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

这是因为在Handler需要和Looper一起才能正常工作

new Thread(){
            @Override
            public void run() {
                super.run();
                Looper.prepare();
                mThreadHandler=new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                    }
                };
                Looper.loop();
            }
        }.start();

加上 Looper就能正常使用了

Looper.prepare();
Looper.loop();

为什么在主线程初始化Handler的时候不需要构建Looper呢?
因为主线程的Looper在ActivityThread 的main 方法就已经初始化了。

Handler源码分析

  • 从构建一个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 that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

以上代码可以直接看出 handler和looper的关系非常密切,hanlder的创建必须存在looper。这也是为什么在工作线程直接构建hanlder会崩溃的原因。

  • Looper从何而来
mLooper = Looper.myLooper();
 public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<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));
    }

以上是Looper类里 关于looper如何构建和获取的源码。Looper本身是个单例类,所以数据可以全局共享。
大概逻辑是这样的
Looper的prepare构建并把looper存储在ThreadLocal里。这里创建的looper因为是在Looper类内部创建的所以都是互不关联的独立对象。ThreadLocal是个存储的集合(其实是数组),然后在使用到looper的时候通过sThreadLocal.get();获取对应的looper。

  • 现在Looper 有了,满足了Handler的构建条件。该发送message了
public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
 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);
    }

发送Message的最终结果是执行了

queue.enqueueMessage(msg, uptimeMillis);
  • MessageQueue队列出场
queue.enqueueMessage(msg, uptimeMillis);
  boolean enqueueMessage(Message msg, long when) {
      .....
            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;
            }
    .....
        return true;
    }

MessageQueue的enqueueMessage方法将message加到链表中,Message是一个链表块。所以Handler发送消息实际上就是将消息加到链表中。

  • 消息有入链也就有出链 Looper.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);
                }
            }
           ......
        }
    }

这是loop方法的关键方法,方法的逻辑是起一个无限循环从MessageQueue中取出message

try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

这里的msg.target就是handler对象,而dispatchMessage最终也是调用了handleMessage方法

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

target实在handler发送message message加入链表的时候赋值,就是发送者本身。

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

到这里 handler从构建 到发送message(sendMessage) 到 处理message(handleMessage)整个过程就打通了。

  • 线程切换的核心ThreadLocal 和 ThreadLocalMap

ThreadLocalMap是ThreadLocal 的一个静态内部类。ThreadLocalMap的存储容器是数组,而且自己有一套扩容机制。ThreadLocal的大致作用是给Thread里的ThreadLocalMap容器添加对象,操作的都是Thread里的ThreadLocalMap容器。

使用代码

 public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

 public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

Handler之所以能切换线程 是因为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));
    }

Looper.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.");
        }
        ......
  }

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

所以Looper一直运行在它被构建时的线程中,并且Looper时持有MessageQueue的,所其他的线程发送的message会存储到Looper的MessageQueue中,并且在Looper所在的线程中得到执行,达到线程切换的效果。

总结

hanlder机制示例图大概是这样的
这里写图片描述

Handler机制几个相关类之间的关系

Message(消息体)
(一个链表块)
持有handler 对象 用于调用handleMessage

MessageQueue(消息队列)
存储消息方式:链表
持有Message
作用 消息的入链 和 出链

Looper (搬运消息的)
持有MessageQueue
无限循环 取消息并且调用handler的 dispatchMessage->handleMessage方法

Handler
发送Message (sendMessage)
处理Message (handleMessage)

以上是我对handler的一些理解 有什么不对的欢迎指点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值