理解Android Handler机制

本文假定读者对Message. Loop. MessageQuene有一定了解,从开发常规用法出发,从源码的角度来理解android handler机制,然后做出自己的理解与总结!

  • 首先我们来看看Handler的习惯用法。
//第一步:实例化Handler
private Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
           //处理收到的消息
            if(msg.what==1){
            }
            return false;
        }
    });
//第二步:使用handler发送消息
private  void  sendMessage(){
        Message message=Message.obtain();
        message.what=1;
        handler.sendMessage(message);
    }
  • 构造方法: new Handler(Callback) 做了什么?
 public Handler(Callback callback) {
        this(callback, false);
    }
//实际调用
public Handler(Callback callback, boolean async) {
       // FIND_POTENTIAL_LEAKS的定义
    //private static final boolean FIND_POTENTIAL_LEAKS = false;
  //永远为fasle 为什么要还这个代码呢?!
  //有知道的同学希望告诉一下!!!
        if (FIND_POTENTIAL_LEAKS) {
            final Class 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());
            }
        }
      //获得Loop类
        mLooper = Looper.myLooper();
     //问题1:为什么mLoop不为空,后文有解释
        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()做什么了
public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
//为什么 sThreadLocal.get()返回不空啊?
//在哪里初始化了?

原来是ActivityThread 做了好事!
在ActivityThread的main方法有这么一句

Looper.prepareMainLooper();
//让我们看看实际做了什么
public static void prepareMainLooper() {
//在这里添加了loop
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
//
private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
//这里!!!同学,set一个新的对象
//所以就解释了问题1 为什么不为空了。
//原来在ActivityThread里面创建一个mainLoop
        sThreadLocal.set(new Looper(quitAllowed));
    }

下面代码验证了 我们的在activity创建的handler使用loop的是mainLoop

boolean is=handler.getLooper().equals(Looper.getMainLooper());
   //返回true 亲测!
  • 在ActivityThread#main方法还有一个重要操作
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();
      //一个无尽的loop
        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 {
                //重点看这里分发消息了
               //target是Handler实例
                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();
        }
    }


handler.sendMessage(message); 做了什么?

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

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

queue.enqueueMessage(msg, uptimeMillis);
又做了什么?!

//将消息加入队列!
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;
    }
总结

1.Message是消息的数据模型,可以存放各种消息。
2.Loop 是一个永动机,不断从消息队列里读出消息。
3.MessageQuene是一个消息队列,不过是链表实现的数据结构。
4.Handler是一个操作器,将消息传入MessageQuene,当Loop读出数据时,Handler的Callback回调处理消息。

你可能感兴趣的:(理解Android Handler机制)