Android中的Handler机制

本文深入解析Android中的Handler机制,包括Handler、Looper、MessageQueue的工作原理及其交互过程,帮助理解多线程通信机制。

Android中的Handler机制

Handler

Handler初识

先看源码中关于handler的解释:

  1. Handler允许你发送和处理与*线程消息队列相关联的***Message和Runnable对象;
  2. 每个Handler实例只与一个线程相关联,而一个线程只有一个消息队列,从而Handler只与一个消息队列相关联;
  3. 当在一个线程中创建Handler对象时,创建的Handler对象就和创建它的线程的消息队列绑定了,之后它就开始工作了(调度消息)

主要作用

  • 调度消息——调度消息和Runnable对象以使其在将来某个时间点执行;
  • 线程通信——将一个action加入到另一个线程的消息队列;
  • 定时触发操作——通过sendMessageAtTime、postAtTime等方法来实现;

消息调度方式

  • send方式

    即利用sendMessage、sendMessageAtTime和sendMessageDelayed等方法,这些方法将一个携带了数据信息的*会被Handler的handlerMessage方法处理的***Message对象加入到消息队列(这种情况要求你定义一个Handler的子类以自己实现handlerMessage方法)。

  • post方式

    即利用post、postAtTime和postDelayed等方法,这些方法将可执行的Runnable对象加入到线程的消息对列中以被执行。

扩展

当一个应用(Application)的进程被创建时,它的主线程(UI线程)就致力于运行一个管理应用级对象(activities、broadcast、receivers等)和应用级对象创建的窗口的消息队列。你可以创建自己的线程,然后通过Handler来与主线程(UI线程)进行通信。具体实现方式就是在你创建的线程中调用post和sendMessage等方法,传递过去的Runnable和Message对象会在Handler的消息队列中完成调度

上面多次提到消息队列(MessageQueue),那么Handler是在什么时候给MessageQueue赋值的呢?观察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的mQueue是通过Looper来赋值的,而mLooper又是通过Looper.myLooper()来赋值的,那么接下来我们看看Looper到底是何方神圣。

Looper

Looper初识

先看源码中的解释:

一个类,什么类?为线程进行消息循环的类。

线程默认是没有与之关联的消息循环的,要得到消息循环,首先要在线程中调用Looper.prepare(),然后写处理代码,在调用Looper.loop();开启消息循环。代码实例:

class LooperThread extends Thread {
    public Handler mHandler;
    public void run() {
        // 初始化
        Looper.prepare();
        //
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // process incomming messages here
            }  
        };
        // 开启looper
        Looper.loop();
    }
}

注意:通常情况下在线程中创建Handler实例,必须显示的调用Looper.prepare()和Looper.loop()方法,但是在主线程(UI线程)中创建Handler时,是不需要显示调用的,因为主线程默认会自己创建Looper对象(其实看源码你会发现,在ActivityTread中,有调用Looper.prepareMainLooper()方法)。

核心方法

prepare()
/** Initialize the current thread as a looper.
 * This gives you a chance to create handlers that then reference
 * this looper, before actually starting the loop. Be sure to call
 * {@link #loop()} after calling this method, and end it by calling
 * {@link #quit()}.
 */
public static void prepare() {
    prepare(true);
}

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

由此可见,prepare(boolean quitAllowed)负责了Looper的创建,并保证了其唯一性。唯一性由ThreadLocal对象来实现。

那么这个sThreadLocal是什么呢?它是一个本地线程存储类,所有线程共享这个对象,但是这个对象对每一个线程而言却具有不同的值,且每个线程对这个对象的访问或修改都不会影响到其他线程,即它的值对于每个线程来说都是独立的。

Looper的构造函数
private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

私有方法,防止手动调用破坏唯一性,主要工作就是初始化消息队列,绑定当前线程。

Loop()方法
/**
 * 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();

  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;
    if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
      Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
    }
    try {
      msg.target.dispatchMessage(msg);
    } finally {
      if (traceTag != 0) {
        Trace.traceEnd(traceTag);
      }
    }

    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);
    }
    // 回收Message对象
    msg.recycleUnchecked();
  }
}

上面代码主要工作:得到Looper实例me,然后通过me.mQueue得到MessageQueue实例queue,身份核查,开启无限循环不断的读取消息(通过MessageQueue的next()方法)分发消息(通过msg.target.dispatchMessage()实现),最后回收Message对象(通过Message.recycleUnchecked()实现),至此,Looper核心方法分析完毕。

MessageQueue

MessageQueue是用来存放Message的集合,并由Looper实例来分发里面的Message对象。同时,message并不是直接加入到MessageQueue中的, 而是通过与Looper对象相关联的MessageQueue.IdleHandler 对象来完成的。我们可以通过Looper.myQueue() 方法来获得当前线程的MessageQueue。

注意:MessageQueue的中文翻译是消息队列,顾名思义,它的内部存储了一组消息,以队列的形式对外提供插入和删除的工作。虽然叫消息队列,但是它的内部存储结构并不是真正的队列,而是采用单链表的数据结构来存储消息列表。

为了证实上面的单链表存储结构,可以看看MessageQueue的源码

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 (DEBUG) Log.v(TAG, "Returning message: " + msg);
                    msg.markInUse();
                    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(TAG, "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;
    }
}

遍历链表取消息部分主要发生在sychronised部分,代码如下:

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

得到msg后,判断其处理时间是否到达,到达就予以处理,未到达就设置一个唤醒时间以待处理。遍历完成后,如果Looper是可退出的,就退出。接下来就处理IdleHandler(与Looper及MessageQueue关联的Handler)了。

上面Looper部分还说到了一个方法,那就是dispatchMessage(即消息分发),该方法位于Handler中,由Message的target(target为Handler的一个实例)在lopper中进行调用,该方法源码如下:

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

从上面的代码可以看出,handler中处理分发小刺的函数有三个,分别如下:

  • Message的回调方法优先级最高,即message.callback.run();
  • Handler的回调方法优先级次之,即Handler.mCallback.handleMessage(msg);
  • Handler的默认方法优先级最低,即Handler.handleMessage(msg)。

Message

先从源码的注释中来了解Message

定义了一个包含一个自身描述信息和任意数据对象的结构用以交给Handler处理,有两个extra int field和一个extra object field。

虽然它的构造函数是public的,但实例化其对象的方式官方推荐的还是Message.obtain和Handler.obtainMessage,因为后面两种方式是从一个可回收对象池中创建的。

也就是说,Message对象包含两个额外的int类型变量和一个额外的对象,利用它们大多数情况下我们不用再做内存分配相关工作。实例化Message最好的方法是调用Message.obtain()Handler.obtainMessage()(实际上最终调用的仍然是Message.obtain()),因为这两个方法都是从一个可回收利用的对象池中获取Message的。

总结

Android的Handler机制在Android多线程编程中应用十分广泛,通过阅读Handler以及相关类(MessageQueue、Looper、Message)的源码,可以很清楚的了解其大致运行机制。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值