Handler的原理

Handler 、Looper、MessageQueue三者之间的关系

ThreadLocal:内部通过map实现

Looper.prepare()方法创建出一个ThreadLoacl实例   Looper只能被调用一次且整个过程当中只能有一个Looper实例不然报Only one 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));
    }
Looper的构造方法当中,new出新的MessageQueue并获取当前的Thread实例

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
loop得到Looper实例 开启一个无线循环从MessageQueue消息队列当中获取出Message进行处理

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

获取MessgeQueue、与当前线程绑定。无限循环从MessageQueue当中取出Message  通过msg.target.dispatchMessage(msg)(这个方法当中调用而来Handler的handlerMessage)交由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());
            }
        }

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


Handler主要来处理Message以及发送Message

通过mLooper= Looper.myLooper();得到了Looper实例通过mQueue=mLooper.mQueue;获取到对应的MessageQueue这样Handler就与MessageQueue进行了关联


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

这样发送了messageQueue

    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中首先为meg.target赋值为this 所以最终Looper的loop方法当中msg.target.dispatcherMessage最后交由的是Handler处理
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
最后执行handleMessage方法
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

自我总结:

1、Looper当中的prepare方法将构造出Looper实例并实现整个只有一个Looper实例 将此保存在MessageQueue当中,MessageQueue仅允许次在唯一实例

2、Looper的loop方法将msg从MessageQueue当中取出交友msg.target.dispatcher处理

3、Handle构造方法当中会先获取到当前的Looer实例进而得到MessageQueue的实例

4、Handler的sendMessage方法当中会将Hander赋值给Loop的msg.target 这样Looper取出的消息就交由Handler处理

5、重写handMessage方法,真正的处理Message消息



  1. 在Looper.prepare()中会通过sThreadLocal保存一个looper实例,控制当前线程只能有一个looper实例;

  2. 创建looper实例时,会创建一个MessageQueue与looper关联;

  3. 因为looper只会存在一个实例,所以 当前线程也会只存在一个MessageQueue队列;

  4. 调用Looper.loop()让looper跑起来吧,然后looper就可以不停的从MessageQueue把消息拿出来,然后通过调用msg.target.dispatchMessage(msg)处理消息,也是让消息最终进入我们的Handler.handleMessage方法,被我们给处理了;所以我们在实例化handler时需要重写handleMessage方法;

  5. 实例化Handler时,handler中会获得当前线程的looper以及looper的messageQueue;

  6. 在调用sendMessage发送消息时,最终会调用enqueueMessage方法,在enqueueMessage方法里会将msg.target=handler,讲handler关联到msg中,这样looper在取出messageQueue中的消息时,才知道该消息是要发给那个handler处理的,将handler与msg关联后,就将msg加入队列中去了,等待looper处理。



注意:

1、创建Message时推荐使用obtain()方法因为Message会维护一个Message池用于Message的复用。这样相对于new Message可以减少对内存的开销

2、Handler的handMessage如果有调用Fragment或者Activity一定要使用软引用,handle定义成static这样可以避免造成内存泄漏










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值