Android消息机制

Android消息机制 也就是Hanlder的工作原理要比四大组件的要简单很多,所以也是面试时经常被问到的。网上分析Handler的文章很多,但只有自己分析了,才能更加深刻的去理解。

要搞清消息机制,首选要弄清五个对象: Handler, MessageQueue, Looper, ThreadLocal能及消息实体Message

  • Handler 是android提供给我们操作消息的的工具,使用handler可以非常方便的实现消息的跨线程传递。
  • MessageQueue, 消息队列,消息从发出到被handler处理中间一段时间内,消息的临时存储单元。
  • ThreadLocal, 可以简单的理解为与线程绑定,作用域为当前线程的数据集合。
  • Looper, 消息队列的操纵者, 用于消息的插入与查看。
  • Message, 存储消息数据 的实体。

首先从最简单的Message开始分析 。 Message这个类实现了Parcelable可序列化接口,说明他可以在intent或IPC中传递。
我们一般使用Message.obtain方法获取一个Message的实例。这样可以保证在一个线程内Message是单例的。

public static Message obtain() {
    synchronized (sPoolSync) {
        if (sPool != null) {
            Message m = sPool;
            sPool = m.next;
            m.next = null;
            m.flags = 0; // clear in-use flag
            sPoolSize--;
            return m;
        }
    }
    return new Message();
}

除了这个方法外,还要关注 obtain的一个重写方法 。

public static Message obtain(Handler h, Runnable callback) {
    Message m = obtain();
    m.target = h;
    m.callback = callback;

    return m;
}

通过 这个方法 ,我们需要传一个Runnable的回调到Message,使用这个方法 发送的消息,handler在会在接收到消息后回调这里的Runnble而不是自己的回调,这点在下面的Handler的分析中解析。

接下来分析MessageQueue这个消息对列,我们把他理解成一个先进先出的队列结构。只需要两个方法 boolean enqueueMessage(Message msg, long when) 插入
msg.next = p; // invariant: p == prev.next
prev.next = msg;
这里是一个链表操作,把消息播放到链表的头部。

Message next() 取出 。

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

这里有一个死循环,当消息为空时,线程会一直阻塞并处于等侍状态 ,flushPendingCommands是一个本地化方法,注释中已经说的很清楚。

/**
 * Flush any Binder commands pending in the current thread to the kernel
 * driver.  This can be
 * useful to call before performing an operation that may block for a long
 * time, to ensure that any pending object references have been released
 * in order to prevent the process from holding on to objects longer than
 * it needs to.
 */
public static final native void flushPendingCommands();

当 Message的target为空时,消息队列会继续向下遍历,拿到下一个为异步的消息,然后再下边的分支中把该消息移出队列,并返回。

下面分析Loopper的原理,Looper是与线程绑定的对象,要使用handler就必须先初始化looper.所以looper的初始化必定使用了ThreadLocal. prepare方法 用于Looper的初始化

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

可以看出,Looper初始化时,已经绑定到当前线程的ThreadLocal中。 关于ThreadLocal,在Web开发中会经常用到,比如事务处理时,要在Service中使用transaction。这里就不分析了。

而实现消息轮训的方法是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
        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();
    }
}
方法的开始就可以看出。重点是for循环中, 调用了queue.next(), 上面已经分析到 MessageQueue.next方法是线程阻塞的,所以这个循环中,looper会不断的调用queue.next()取消息,当没有消息时就会阻塞并处于等侍状态。
住下看,到了msg.target.dispatchMessage(msg), 这里会回调到Handler的方法 ,并回到主线程去处理消息。

下面就得分析到Handler了,接上面的先分析 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);
    }
}

方法很简单,首先判断了 Message.callback是否为空,当不为空时,就会执行Message中传入的回调,而不会执行Handler的handleMessage方法。 当然更多的使用Message.obtain方法去得到一个Message,这样就会执行到handleMessage方法,去处理消息。

下面只剩下Handler的sendMessage方法,看看是怎么发消息的。

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方法 把消息放入消息队列中。

到这里消息从发出,到被Handler接收并调用回调处理的方法的过程 就分析完了。下面还要看看Looper到底是怎么被初始化,并开启looper方法去接收消息的。这里需要来到应用程序 的入口,ActivityThread.main 方法 中

Process.setArgV0("<pre-initialized>");

Looper.prepareMainLooper();

ActivityThread thread = new ActivityThread();
thread.attach(false);

if (sMainThreadHandler == null) {
    sMainThreadHandler = thread.getHandler();
}

if (false) {
    Looper.myLooper().setMessageLogging(new
            LogPrinter(Log.DEBUG, "ActivityThread"));
}

// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();

这里调用了Looper.prepareMainLooper();其实内部也是调用了prepare方法。 可以 看出UI线程的looper是在这里开启的,所以我们在UI线程中looper是系统给我们开启的,所以可以直接使用handler. 而当我们在子线程去实现Handler时必须手动去开启looper,如下。

new Thread(new Runnable() {
     @Override
     public void run() {
         Looper.prepare();
         Log.d("xx", "xx11");
         Handler handler = new Handler(){
             @Override
             public void handleMessage(Message msg) {
                 Log.d("msg", msg.obj.toString());
             }
         };
         Looper.loop();
         Log.d("xx", "xx");
         Message message = Message.obtain();
         message.obj = "helloworld";
         handler.sendMessage(message);

     }
 }).start();

上面Looper.loop()下面的都不会被执行到,因为线程会一直阻塞。 再看看上边的main方法, UI线程其实是ActivityThread这个线程, Looper.loop()在方法 必须是在最后执行。主线程中也有一个自己的Handler H,这个handler就是用来处理组件运行。

Handler的运行机制已经分析完了,下面再理一下UI线程中Handler的工作流程

  • 程序入口main- > Looper.prepareMainLooper() -> ActivityThread 开启UI线程 ->
    Looper.loop() 等侍;

  • UI线程-> 初始化Handler- > 子线程 Handler.SendMessage->
    MessageQueue.enqueueMessage插入消息 -> Loop.loop() - > MessageQueue.next
    -> Handler.dispathcerMessage-> HandlerMessage.

不会画图,只能这样表示下了。下面再看下Handler.post方法, 这个方法可以直接在子线程中使用,并在内部的Runnable中去更新UI.

public final boolean post(Runnable r)
{
   return  sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

看其实内部还是使用了Message,并把这里Runnable传递 到Message的callback中,并在 Handler.dispatcher中调用,上面已经分析到。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值