安卓looper,messager,hander 详解

Android中的应用程序是靠消息驱动来工作的,如图示:
消息处理图

根据原理图可以看出事件被不停的添加的消息队列中,有一个处理线程不断的去循环遍历这个消息队列,去处理这个消息

在Android中Looper和Hander这两个类用来实现这些,在Looper类主要存在一个消息队列和不停的循环,hander类主要是添加消息和消息处理

Looper源码:先来看看looper的prepare方法

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

sThreadLocal(线程局部变量)。线程局部变量(ThreadLocal)其实的功用非常简单,就是为每一个使用该变量的线程都提供一个变量值的副本,是Java中一种较为特殊的线程绑定机制,是每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突。可以通过get方法或set方法来设置,因为一个线程只允许有一个looper,所以当prepare时会是否创建了loop,若没有创建,则给sThreadLocal设置

   private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

在Looper构造方法中创建了一个消息队列MessageQueue,解析来就是循环获取MessageQueue的消息

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

myLooper()方法获取的是之前 sThreadLocal.set(new Looper(quitAllowed))设置的Looper对象

public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}

那么接下来就是处理消息了

final MessageQueue queue = me.mQueue; //获取此线程的Looper中的MessageQueue消息队列

在MessageQueue中获取消息

 Message msg = queue.next();

接下来

 msg.target.dispatchMessage(msg);

这里msg.target表示的对象是Handler,也就是将这条消息发送给Hander处理

再来看看Hander,是如何发送消息和处理消息的,一般情况下我们用handler会是这样的:

Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
    }
};

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

 public Handler(boolean async) {
    this(null, async);
}

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


}

   public Handler(Looper looper, Callback callback, boolean async) {
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

一般情况下我们用无参的构造方法,其它构造方法要么设置了Callback要么主动传入Looper

再来看看Handler是怎么发送消息的

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

在sendMessageAtTime这个类中,有一个MessageQueue,看看这个MessageQueue是如何来的,在构造方法中

 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;

在这里设置了MessageQueue(mQueue = mLooper.mQueue;),看看 Looper.myLooper()中做了什么

public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}

这里就是返回当前线程的looper,如果没有设置那就为空了,现在MessageQueue获取到了,如何就调用

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

方法往MessageQueue里添加消息,别忘了msg.target = this;接下来就是处理消息逻辑了,在Looper中的loop()方法有这么一句 msg.target.dispatchMessage(msg);,也就是把message给Handler的dispatchMessage(msg)方法来处理:

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.callback来处理,Handler全局设置了Callback,那么消息会给这个Callback调用,负责就会调用handleMessage(msg)这个方法处理,这也就是我们重新handleMessage的原因

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值