Handler的原理,Handler ,Looper和MessageQueue 三者关系?

Handler:

Handler 负责发送消息,和接收消息;new 一个Handler 对象会在构造方法中会调用Looper.myLooper方法获取一个Looper对象,然后从Looper对象获取到MessageQueue对象, Handler将要发送的Message存放到MessageQueue,looper 循环获取MessageQueue里的消息,如果消息不为null,则交给Message的target属性(Message.target即Handler对象)的dispatchMessage去处理,然后回调到Handler 复写的handleMessage(Message msg)中去处理消息。

Looper:

负责消息的封装,和读取消息;new 一个looper 对象会在构造方法中调用 new一个MessageQueue,然后循环读取MessageQueue里的Message,如果消息不为null,则交给Handler处理

MessageQueue:

MessageQueue 就是一个消息队列,有消息过来就负责存储消息;Looper 循环从MessageQueue读取Message

 

源码分析

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());
        }
    }
    //获取Looper实例
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    //从Looper实例中获取MessageQueue
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

Looper.myLooper() 跟踪:

这是一个静态方法,直接调用,从sThreadLocal对象中获取Looper对象

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

sThreadLocal对象是一个ThreadLocal对象,可以在一个线程中存储变量,底层是ThreadLocalMap,即Map对象;

 

sThreadLocal对象中的Looper对象来源:

ActivityThread main():

ActvityThread 是android APP的进程初始类,他的Main 函数是这个App的进程入口;

public static final void main(String[] args) {
        //创建 prepareMainLooper
        Looper.prepareMainLooper();
        if (sMainThreadHandler == null) {
            sMainThreadHandler = new Handler();
        }

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

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

        Looper.loop();
        -----
}

关键代码在 Looper.prepareMainLooper() 和Looper.loop();

Looper.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()是Looper的内部方法:

private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    //new 一个Looper并保存到sThreadLocal中去
    sThreadLocal.set(new Looper(quitAllowed));
}

综上源码分析,我们就可以得知sThreadLocal中的Looper的来源

Looper分析:

looper的构造方法,即new一个looper对象同时new了一个MessageQueue对象

private Looper(boolean quitAllowed) {
    //new 一个MessageQueue对象
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

Looper 有两个重要的函数prepare() 和loop(),前面分析了prepare()就是创建Looper同时并保存到ThreadLocal中去,下面分析Loop()

Looper loop():

public static void loop() {
    final Looper me = myLooper();//获取Looper对象
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;//从Looper对象获取MessageQueue对象

    // 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 (;;) {//死循环  一直从MessageQueue中遍历消息
        Message msg = queue.next(); // might block
        if (msg == null) {
            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 {
            //调用handler的dispatchMessage方法,把消息交给handler处理
            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);
        }

        msg.recycleUnchecked();
    }
}

死循环一直会从MessageQueue中取消息,如果取到了消息呢,会执行msg.target.dispatchMessage(msg)这行代码,msg.target就是handler,其实就是调用handler的dispatchMessage方法,然后把从MessageQueue中取到的message传入进去。

Handler dispatchMessage()

public void dispatchMessage(Message msg) {
    //如果callback不为空,说明发送消息的时候是post一个Runnable对象
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {//这个是用来拦截消息的
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);//最终调用我们重写的handleMessage方法
    }
}

 

这个方法对消息做最后处理,如果是post类型调用handleCallback方法处理,如果是sendMessage发送的消息。看我们有没有拦截消息,如果没有最终调用handleMessage方法处理。

总结

Handler负责发送消息,looper负责接收消息Handler发送的消息和回传给handler 处理,MessageQueue就是一个消息存储容器

 

最后:

本文是参考  :     

:http://blog.csdn.net/lowprofile_coding/article/details/72580044 

http://blog.csdn.net/lmj623565791/article/details/38377229                                                                                                                                                                                                                         

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值