android 中的Handler简要总结

Handler是android提供的一个工具类,也是必不可少的,在主线程中控制着UI包括生命周期,然后自己画了这么个图,哈哈。


Handler源码牵扯的比较多,先有个大概的认识再去看源码,会比较顺畅。

Android的UI线程(主线程)就是个死循环,包括Activity的生命周期都在这个死循环中执行。

Looper:就是启动这个循环的类,它有个方法loop就把循环启动了,线程是被这个循环占住了。这个循环有两个作用:(1)不断的去MessageQueue中取message。(2)根据dispathMessage处理任务,调用HandlerMessage()的回调,也包括onCreate(),onResume()生命周期。

MessageQueue:将信息按照时间排成队,供给Loop循环获取,一部分是来自Handler自己sendMessage(),一部分是系统来的。

就这样的一个模型,带着这个模型来分析源码。

考虑一个最常用的UI线程,是怎么使用Handler的:

android应用怎么说也是个java程序,应该有个入口函数的main()就在ActivityThread.java这个类中,在这个函数中看到有两句代码。这第一句是:

ActivityThread.java

Looper.prepareMainLooper();


Looper.java
public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }


在分析之前,先说明ThreadLocal<T>这个java类,看过thinkinginjava的介绍,每个线程保存的T泛型的对象会保存各自的线程中,通常声明为单实例,内部使用map与线程建立对应关系,具体不分析了。

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

也就是说我在线程1中保存了T的一个对象,那在线程1中使用sThreadLocal.get(),就会得到这个T的对象,线程2就取不到线程1的对象。


进来之后,首先调用的是这个方法prepare()如下,sThreadLocal里保存了一个Looper对象。
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));
    }

之后又调用了mLooper(),将这个Looper取了出来,赋值给了sMainLooper,也是一个单实例对象


至此,Looper已经准备好了,之后将循环跑起来,就可以了,回到入口函数Main(),调用了一句:

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

            msg.recycleUnchecked();
        }
    }


在代码中看到,for循环就是处理信息调用回调的循环了,到这里核心的模型已经建立起来了,再分析一个场景使用Handler来sendEmptyMessage(),走一遍流程。

1)通常先创建一个Handler()

Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {


                super.handleMessage(msg);
            }
        };

使用无参数的构造函数最终会调用的构造如下:

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

看到这个new出来的Handler是使用的ThreadLocal中取出来的Looper,就是在Main函数里创建的那一个looper是同一个,包括Looper中的mQueue,也是同一个,在这一个线程中,只存在这一个Looper,MessageQueue,都是唯一的。


2)使用handler.sendEmptyMessage(123456);最终会调用到这里

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

enqueueMessage()这个方法会将msg加入到MessageQueue中,并且按照时间拍好顺序,时间靠前执行的在队列的前面,在后的在队列的尾部,同时还在message中加入taget为当前的Handler。信息已经加入到了messageQueue中了,这时候Loop的循环还在不停的读,在它之前的消息读完了,就读到它了。

3)loop读取,在循环代码中有这样一句调用

Message msg = queue.next();

这句中将队列中的msg取了出来。

msg.target.dispatchMessage(msg);

这句调用target的dispatchMessage(),这个target即是开始new的那一个handler,在Handler中代码如下:

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }


看到了我们的回调
handleMessage(msg);
这样就完成了一个取messge到处理的过程,然后继续循环以此类推。

因为这些代码是在主线程的循环里的,如果这里有耗时的代码,会阻塞掉主线程,MessageQueue中的message始终不能够读取和处理,界面就卡住了,严重些就出现了ANR。

如果这个Handler对象传递到了其他线程,由于Looper还是主线程的,发的Message也是在主线程的MessageQueue中,当然就是主线程来接受了,就跨线程通信了。其他线程可以适时回调主线程的方法。


其他线程也可以使用Handler这样的工具,但是记得准备好Looper并且让他循环起来就可以了。


Handler源码真是好!真是好!真是好!重要的事情说三遍。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值