Android Handler实现机制

来源:互联网 发布:小学英语网络培训心得 编辑:程序博客网 时间:2024/06/18 15:17
       其实网络上已经有很多Handler的讲解了,写这篇博客其实也只是为了记录一下,加深下理解。其实写这篇博客是因为以前再面试的时候被问到Thread Handler Looper之间的关系的时候,我回答错了,我说的是三者之间都是一一对应的关系。其实只有Thread和Looper之间是一一对应的关系,而Looper和Handler之间其实可以说是一对多的关系。而且我是在看了老罗写的关于Handler机制的博客后面试的,当时以为自己对Handler理解的挺深的,然后发现自己错了,看了博客而没有深入的理解源代码,所以理解还是有一定的偏差,所以决定再好好看看顺带写博客记录下。
       现在对Handler机制的理解概括如下,handler传递消息到MessageQueue, MessageQueue根据message的发生时间进行排序,Looper循环遍历MessageQueue里面的消息,然后通过调用message.target.handlerMessage()把对应的message返回给handler。下面针对具体的实现细节进行解释。
      
       Looper类:
       Looper的作用是循环遍历MessageQueue里面的消息队列,然后返回给Handler。Looper的构造方法被private修饰,不能通过new Looper()的方式创建Looper对象,Looper本身提供了两个静态函数来创建Looper对象:
       Looper.prepare():

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

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}
       
      ThreadLocal是Thread的一个私有的全局集合变量,用于存放一些Thread私有的数据,这些数据会随着Thread的销毁而被回收。这个方法能够保证一个Thread里面只有一个Looper对象,亦即这个方法在线程里面只需要调用一次即可。在子线程里面使用Handler对象之前必须先调用Looper.prepare()方法,然后调用Looper.loop()方法才能使Handler机制运行起来。因为新创建的子线程不会自己创建Looper和MessageQueue对象,所以需要开发者自己在子线程里面调用。
      Looper.prepareMainLooper()

public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}
       
这个方法会先调用prepare()方法创建Looper和MessageQueue对象,然后把当前创建的Looper对象赋值给sMainLooper。这个方法会在ActivityThread类的main()函数里面调用,所以开发者可以在Activity里面直接创建Handler对应并且使用它。大家可以想想为什么会专门创建一个sMainLooper对象?  (这个问题可以在之后讲解Handler的时候会找到答案 !)
       Looper还有一个loop()方法,里面实现了一个无限for循环,从MessageQueue里面获取消息,并且传递给对应的Handler对象。
       Looper.loop():

public static void loop() {
    ...
    for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            // 当MessageQueue里面没有message之后就会退出这个for循环
            return;
        }
        ...
        try {
            msg.target.dispatchMessage(msg);
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        // 把msg放入缓存中
        msg.recycleUnchecked();
    }
}
      
      到现在Looper类的创建和循环遍历功能实现都已经说明。

      Handler类:
      Handler用于发送消息和处理消息。这个类我主要说明两点,一个是Handler的创建,一个是消息发送
      1)、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;
}


public Handler(Looper looper, Callback callback, boolean async) {
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}
      Handler创建有两类方法,一个是构造方法的参数里面不带Looper对象的,一个是构造方法的参数里面带Looper对象的。不带Looper对象的构造函数在Handler创建是会检测这个对象是否用static修饰,因为如果在主线程中创建Handler且重写了handleMessage而又没有用static修饰的话则又可能导致内存泄漏。因为重写了handleMessage就相当于定义了一个内部类,而内部类会持有外部类的引用。创建Handler之后会给它的变量looper赋值,这个值是sMainLooper不会被销毁,根据可达性原则这个handler就不会被回收,所以就又可能出现内存泄漏。那么对于带Looper参数的构造函数就有一个问题,为什么它没有检测是否用static修饰那?在源码中没有找到对应的解释文案,但是可以这样理解。当你传递的looper是Looper.getMainLooper()的时候就知道这个handler不会被回收了,所以这个时候需要开发者自己对这些做处理。还有在讲解Looper的时候提了一个问题为什么Looper会创建一个sMainLooper
哪,想想Handler的构造函数你就能找到答案。
      2)、消息发送:    
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}
      消息发送比较简单就是把消息传递给MessageQueue,然后由MessageQueue进行处理。

      MessageQueue类:
      messageQueue用于管理message , 并对其进行排列。MessageQueue还有很多native方法的调用,这篇博客只针对MessageQueue的两个方法进行讲解,  enqueueMessage()和next()
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) {
        ...

        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;
}
mMessages是一个顶部的message类似链表实现的集合里的header,当mMessages为空或者是先的msg的when属性为0或小于mMessages.when的时候就让它和mMessages进行切换角色。当msg的when为一个中间值的时候就会通过for循环的方式变量消息列表然后让它插入到合适的位置上去。

Message next() {
    ...
    for (;;) {
        ...
        synchronized (this) {
            // Try to retrieve the next message.  Return if found.
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                // Stalled by a barrier.  Find the next asynchronous message in the queue.
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) {
                    // Next message is not ready.  Set a timeout to wake up when it is ready.
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    // Got a message.
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                    msg.markInUse();
                    return msg;
                }
            } else {
                // No more messages.
                nextPollTimeoutMillis = -1;
            }
            ...
     }
}
在这个方法里面会从mMessage获取满足message.when <= now条件的message然后返回给Looper,如果都不满足则会进入等待的状态。

到此Looper,Handler和MessageQueue的关系就讲完了,其实最主要的就是讲了Handler机制是怎么实现循环的,每个类又在这个循环中起到了什么作用。但是感觉还是有遗漏的地方,比如Message的Async是怎么处理的,MessageQueue底层实现也没有介绍,这些以后搞明白了再补充上吧。


















原创粉丝点击