Handler的源码分析

最近复习到了Handler一直只知道怎么用,却没有仔细分析过源码,这下就来看看

为什么要使用handler呢?

因为在安卓应用中ui操作是线程安全的,只能ui线程去操作ui组件,但是在现实开发中,可能有多个线程去并发操作ui,所以将会导致线程不安全,所以就用到了handler

Looper1.主要负责创建message Queue和自身的创建    2.    消息的循环

public static void prepare() {
    prepare(true);
}

private static void prepare(boolean quitAllowed) {
//判断当前的对象是否为空 ,即prepare不能调用两次
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    创建looper对象放入线程中

    sThreadLocal.set(new Looper(quitAllowed));
}
private Looper(boolean quitAllowed) {
        //looper对象创建了messagequeue
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

2.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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

        final long traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        final long end;
        try {
//吧msg交给msg.target实际就是绑定的handler去处理这个方法中调用了handlemessage所以在创建handler
的时候要重写handlemessage方法

            msg.target.dispatchMessage(msg);
            end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (slowDispatchThresholdMs > 0) {
            final long time = end - start;
            if (time > slowDispatchThresholdMs) {
                Slog.w(TAG, "Dispatch took " + time + "ms on "
                        + Thread.currentThread().getName() + ", h=" +
                        msg.target + " cb=" + msg.callback + " msg=" + msg.what);
            }
        }

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

Looper的作用就是创建message队列,然后吧队列中的消息派发给handler,然后handler去处理消息

然后我们在去看下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创建的时候就会绑定他的looper并找见他的队列

handler有两种发送消息的方法 send和post

public final boolean sendMessage(Message msg)
{
    return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
//看出来最后调用了队列的方法,也就是handler发出的消息,最后会保存到对应的队列中
    return queue.enqueueMessage(msg, uptimeMillis);
}

所以就是一个应用的创建,系统会自动给你生成一个主线程,并在这个主线程中生成一个Looper对象来让你和子线程之间进行消息的传递,Looper会创建一个消息队列,当我们在子线程中给主线程发消息的时候就需要用到handler,handler创建的时候就会去找到这个对应的looper。looper不断的执行loop方法去发消息给队列中 ,没当handler去发送一个消息的时候,就吧消息加入到队列中 ,然后队列的loop方法就会接收到这个消息,然后消息去调用dispatchmsg方法,然后dispatchmsg方法就会调用handler中的handlemessage方法,我们就能接收到这个消息

猜你喜欢

转载自my.oschina.net/u/3234136/blog/1794086