Android进阶笔记(二)Handler消息机制理解

          之前本人看完技术书很少写博客,技术没有及时巩固,过一段时间后一些概念又变得模糊了,所以决定今后学完一个知识点就写一篇技术博客总结,尽管写好一篇博客不易,但技术在于点滴积累。

         本博客吸取了两位大牛@任玉刚《android 开发艺术探索》,@何红辉《android开发进阶——从小工到专家》书中讲解,同时借鉴了@HujiaweiBujidao的读书笔记,再结合源代码一步一步了解Handler消息机制的原理。

第一个问题是:Handler消息机制到底是怎样的一个流程?


     不好意思由于电脑没装画图visio,所以图片非常丑,还有就是没有把 Handler到handleMessage()的dispatchMessage方法标上去


        

第二个问题是:如何理解上述流程中一些概念?

MessageQueue:虽然叫消息队列,但是它的内部实现并不是用的队列,实际上它是以单链表的数据结构存储消息列表但是以队列的形式对外提供插入和删除消息操作的消息队列,它包含两个主要操作enqueueMessagenext,前者是插入消息,后者是取出一条消息并移除。

Handler:发送和处理消息。如果要Handler正常工作,在当前线程中必须要有一个Looper对象。Handler的创建会采用当前线程的Looper来构建内部的消息循环系统,如果当前线程中不存在Looper的话就会报错。Handler可以用post方法将一个Runnable投递到消息队列中,也可以用send方法发送一个消息投递到消息队列中,其实post最终还是调用了send方法


Looper:每个线程只能有一个Looper对象,在主线程被创建的时候,会在主线程中初始化一个Looper对象,调用Looper的loop()方法后,会陷入一个无限的循环中——每当发现MessageQueue中存在一条消息,就会将它取出,传递到Handler的handleMessage()方法中。


第三个问题是:为啥Android提供这个Handler消息机制?

Handler的主要作用是将一个任务切换到某个指定的线程中去执行。Android规定UI操作只能在主线程中进行,为啥呢?因为多个线程并发操作UI,可能会产生线程不安全现象,因此规定只能在主线程中更新UI。而网络请求等操作如果放在主线程,考虑到网速等原因,可能会造成ANR(程序未响应),导致主线程被阻塞,所以这类耗时操作应该放在子线程。


  ThreadLocal的工作原理

  ThreadLocal是什么东西?望文生义好像是本地线程,其实是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据,对于其他线程来说则无法获取到数据。一般来说,当某些数据是以线程为作用域并且不同线程具有不同的数据副本的时候,可以考虑使用ThreadLocal。 对于Handler来说,它需要获取当前线程的Looper,而Looper的作用域就是线程并且不同线程具有不同的Looper,这个时候通过ThreadLocal就可以实现Looper在线程中的存取了。

下面分析  ThreadLocal的内部实现,  ThreadLocal是一个泛型类,只要弄清  ThreadLocal的getset方法就能明白它的工作原理,看源码:

public void set(T value) {
    Thread currentThread = Thread.currentThread();
    Values values = values(currentThread);
    if (values == null) {
        values = initializeValues(currentThread);
    }
    values.put(this, value);
}

可以看出通过ThreadLocal的put方法将当前线程ThreadLocal.values存储到一个 Object[] table

void put(ThreadLocal<?> key, Object value) {
    cleanUp();

    // Keep track of first tombstone. That's where we want to go back
    // and add an entry if necessary.
    int firstTombstone = -1;

    for (int index = key.hash & mask;; index = next(index)) {
        Object k = table[index];

        if (k == key.reference) {
            // Replace existing entry.
            table[index + 1] = value;
            return;
        }

        if (k == null) {
            if (firstTombstone == -1) {
                // Fill in null slot.
                table[index] = key.reference;
                table[index + 1] = value;
                size++;
                return;
            }

            // Go back and replace first tombstone.
            table[firstTombstone] = key.reference;
            table[firstTombstone + 1] = value;
            tombstones--;
            size++;
            return;
        }

        // Remember first tombstone.
        if (firstTombstone == -1 && k == TOMBSTONE) {
            firstTombstone = index;
        }
    }
}


从源码可以看出ThreadLocal的值在table数组中的索引就是index+1,最终ThreadLocal 的值将会存储到table中 ,table[index+1]=value.

public T get() {
    // Optimized for the fast path.
    Thread currentThread = Thread.currentThread();
    Values values = values(currentThread);
    if (values != null) {
        Object[] table = values.table;
        int index = hash & values.mask;
        if (this.reference == table[index]) {
            return (T) table[index + 1];
        }
    } else {
        values = initializeValues(currentThread);
    }

    return (T) values.getAfterMiss(this);
}

从源码可以看出不同线程访问同一个ThreadLocal的get方法时,ThreadLocal内部会从各自的线程中取出一个数组,然后再从数组中根据当前ThreadLocal的索引去查找出对应的value值,不同线程中的数组是不同的,这就是为什么通过ThreadLocal可以在不同线程中维护一套数据的副本并且彼此互不干扰。


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) {
        if (mQuitting) {
            IllegalStateException e = new IllegalStateException(
                    msg.target + " sending message to a Handler on a dead thread");
            Log.w("MessageQueue", 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;
}

next方法是一个无限循环的方法,如果消息队列中没有消息,那么next方法会一直阻塞的,当新消息到来时,next方法会返回这条消息并将其从单链表中移除。

Message next() {
    // Return here if the message loop has already quit and been disposed.
    // This can happen if the application tries to restart a looper after quit
    // which is not supported.
    final long ptr = mPtr;
    if (ptr == 0) {
        return null;
    }

    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }

        nativePollOnce(ptr, nextPollTimeoutMillis);

        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 (false) Log.v("MessageQueue", "Returning message: " + msg);
                    return msg;
                }
            } else {
                // No more messages.
                nextPollTimeoutMillis = -1;
            }

            // Process the quit message now that all pending messages have been handled.
            if (mQuitting) {
                dispose();
                return null;
            }

            // If first time idle, then get the number of idlers to run.
            // Idle handles only run if the queue is empty or if the first message
            // in the queue (possibly a barrier) is due to be handled in the future.
            if (pendingIdleHandlerCount < 0
                    && (mMessages == null || now < mMessages.when)) {
                pendingIdleHandlerCount = mIdleHandlers.size();
            }
            if (pendingIdleHandlerCount <= 0) {
                // No idle handlers to run.  Loop and wait some more.
                mBlocked = true;
                continue;
            }

            if (mPendingIdleHandlers == null) {
                mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
            }
            mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
        }

        // Run the idle handlers.
        // We only ever reach this code block during the first iteration.
        for (int i = 0; i < pendingIdleHandlerCount; i++) {
            final IdleHandler idler = mPendingIdleHandlers[i];
            mPendingIdleHandlers[i] = null; // release the reference to the handler

            boolean keep = false;
            try {
                keep = idler.queueIdle();
            } catch (Throwable t) {
                Log.wtf("MessageQueue", "IdleHandler threw exception", t);
            }

            if (!keep) {
                synchronized (this) {
                    mIdleHandlers.remove(idler);
                }
            }
        }

        // Reset the idle handler count to 0 so we do not run them again.
        pendingIdleHandlerCount = 0;

        // While calling an idle handler, a new message could have been delivered
        // so go back and look again for a pending message without waiting.
        nextPollTimeoutMillis = 0;
    }
}


Looper工作原理


Looper扮演着消息循环的角色,如果有消息就会立即处理,否则就一直阻塞在那里,看下它的构造方法,在构造方法中它会创建一个MessageQueue,然后将当前线程的对象保存起来。

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);//创建消息队列
    mThread = Thread.currentThread();//保存当前线程对象
}
 
我们知道,Handler的工作需要Looper,没有Looper的线程就会报错,那么如何为一个线程创建Looper对象呢?其实可以通过Looper.prepare()即可为当前线程创建一个Looper,接着通过Looper.loop()开启消息循环。

new Thread("Thread#1"){
    public void run(){
           Looper.prepare();
           Handler handler=new Handler();
           Looper.loop();//启动消息循坏
    }
   }.start();

Looper除了prepare方法外,还提供了prepareMainLooper方法,这个方法主要是给主线程也就是ActivityThread创建的Looper使用的,其本质也是通过prepare方法来实现的。

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

        msg.target.dispatchMessage(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();
    }
}


Looper最重要的一个方法是Loop方法,只有调用了Loop后,消息循环系统才会真正起作用,loop方法是一个死循环,唯一跳出循环的方式就是MessageQueue的next方法返回null。跳出整个loop()方法。如果MessageQueue的next方法返回新消息,Looper就会处理这条消息,msg.target.dispatchMessage(msg)就是发送消息给Handler对象,这时Handler发送的消息最终是它自己的  dispatchMessage方法处理,这时的 
dispatchMessage方法是在创建Handler是所用到的Looper对象中的方法,这样就实现了代码逻辑切换到指定线程中执行。dispatchMessage源码:

/**
 * 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);
    }
}
private static void handleCallback(Message message) {
    message.callback.run();
}



Handler工作原理


首先看下Handler构造方法:

  默认构造方法

public Handler() {
    this(null, false);
}
重构的构造方法

public Handler(Callback callback) {
    this(callback, false);
}
public Handler(Looper looper) {
    this(looper, null, false);
}
public Handler(Looper looper, Callback callback) {
    this(looper, callback, false);
}

就已默认构造方法为例子,因为在实际项目中经常新建一个Handler对象用new 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();//获取Looper对象
    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对象。

Handler的主要功能包括消息的发送和接收过程。消息的发送可以通过post方法和send方法来实现,post的一系列方法最终是通过send的一系列方法来实现的:

  这里只贴出一个方法的代码,其他方法可自行查源码

 */
public final boolean sendMessage(Message msg)
{
    return sendMessageDelayed(msg, 0);
}


为了能够更好的理清之间的关系,借用@ http://blog.csdn.net/qq6833288整理的图片:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值