Handler,Looper 原理分析

来源:互联网 发布:淘宝城三期 招商 编辑:程序博客网 时间:2024/06/05 20:30

在Android中,对于每一个Thread,可以创建一个Looper对象(Only One!)和多个Handler。然后在Handler的构造函数中会调用mLooper=Looper.myLooper()与其所在线程中的Looper对象进行绑定。

Looper中有四个我们必须要了解的变量:

static sMainLooper;static sThreadLocal;mQueue;mThread;


  对于一个线程来说,想要使用Handel对象,那么必须要创建一个Looper实例,那么如何去创建Looper对象呢?

 

Looper.prepare();Looper.Loop();

在Looper.prepare()中,会创建一个新的Looper对象,并放入全局的sThreadLocal中

 sThreadLocal.set(new Looper(quitAllowed));

我们再继续深入看看new Looper(quitAllowed)中到底干了啥,很简单,就两行代码而已:

mQueue = new MessageQueue(quitAllowed);mThread = Thread.currentThread();

原来只是初始化mQueue和mThread这两个变量。

以上就是Looper的创建过程了,那么问题来了,我们再Activity中也并没有去这样创建Looper啊,为什么照样可以使用Handler呢?其实Activity所在的主线程照样也创建了Looper对象,替你干了活而已,虽然它是主线程,也得照样按照规则办事啊。

Activity所在的主线程是ActivityThread,其实这样说并不准确,因为ActivityThread并不是一个线程,它只是主线程的一个入口:ActivityThread中的void main(String[] args) .

在 main()中,它到底帮我们干了啥?

Looper.prepareMainLooper();.......Looper.loop();

我擦,你看它已经默默做好了一切!

细心的你应该发现了,这里调用的是Looper.prepareMainLooper(),而不是之前所说的Looper.prepare()。是啊,它可是主线程,总得有点不一样的地方吧,岂能完全平起平坐。

我们来挖一挖这个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(false)方法,只不过又多做了一些事,
sMainLooper = myLooper();

初始化了sMainLooper这个变量。你看这个主线程,老是喜欢多干活!

这时你要问了,这个变量有啥用啊?大家还记得这个变量是静态的吧,这样在子线程中,你就可以通过getMainLooper()来获得主线程的Looper对象了。而对于其他的子线程,因为它们的Looper对象只存储在sThreadLocal中,所以只能够取出自己的Looper对象了。why?看名字也知道啊,这个sThreadLocal是个ThreadLocal对象,至于ThreadLocal能干啥,我就不解释了。

好了,整个Looper的创建相信大家已经很清楚了。那么接下来就是介绍Handler了。

先来看看Handler的构造函数:

    public Handler(<span style="color:#ff0000;">Callback callback</span>, boolean async) {<span style="color:#ff0000;">//callback就是我们平时写的处理消息的回调,后面要用到</span>        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;    }

这里大家仔细看看,就是前面所说的,将Looper与Handler进行绑定,并且将Looper的mQueue赋值给Handler的mQueue。

大家平时调用Handler都是怎么用?这个应该不用说了吧,最简单的就是:

handler.sendEmptyMessage(int)

我们直接深入到这个方法的最底层:sendMessageAtTime(Message msg,long uptimeMills);

  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);  }
直接看最后一句,这里应该是将我们发送的msg入列了。再向下挖:

   private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {        msg.target = this;//将msg的目的地设为自己。        if (mAsynchronous) {            msg.setAsynchronous(true);        }        return queue.enqueueMessage(msg, uptimeMillis);   }
果然,这里是将msg放入了mQueue中了。注意注意!这个mQueue指向的可是Looper的mQueue,忘记了请看前述Hander的构造函数。

好了,消息放到队列中去了,有进就有出啊,你个送信的总得把信送出去吧。

还记得前面创建Looper时所说的Looper.loop()吗?loop是啥意思,循环啊!接下来看看这个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;        .......        for (;;) {            Message msg = queue.next(); // might block            if (msg == null) {                // No message indicates that the message queue is quitting.                return;            }            .......            msg.target.dispatchMessage(msg);            .......            msg.recycleUnchecked();        }    }

这里原来是开启了一个无限循环的for循环!for循环中,源源不断的将消息给发送出去。

msg.target就是Hander对象它自己。我们来看看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);        }    }
哈哈,看见了啥?handleMessage(msg) 啊。我们平时new Hander时咋写的记得吧。
    Handler handler=new Handler(){           @Override           public void handleMessage(Message message){                           }    };
我们重写了handleMessage方法,好了,消息终于送达到目的地了!

以上就是Handler与Looper的哀怨情仇。总得来说,Looper就是一个邮局,Handler其实就是一个信使。Handler中的Callback就是收信人。这个送信的Handler从我们这拿到信,通过 sendMessage() 放到邮局的仓库mQueue里,邮局Looper再不断的从仓库中取出信,交还给信对应的信使Handler,送到收信人Callback手中,收信人调用handleMessage(Message msg)来读信。



0 0
原创粉丝点击