Handler原理解析

###文章简介:本文通过阅读android源码来搞懂handler运行原理,好了废话不多说,马上开始装逼:

几个定义

Looper:轮询从消息队列中取消息的对象
MessageQueue:用来保存所有消息的消息队列
Message:消息对象,可以保存数据
Handler:用来发送消息和处理消息的对象

Message创建的三种方式:

new Message();
Message.obtain();
Handler.obtainMessage();
注:Handler.obtainMessage()其实最后也是调用Message.obtain(),用Message.obtain()的原因是这种方法可以复用消息池中的消息

Handler初始化
new Handler(){
    handleMessage(){
    }
}
//sdk中handler初始化源代码
public Handler(Callback callback, boolean async) {
    //给自己的mLooper对象赋值
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    //将looper中的消息队列赋值给mQueue变量
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}
Looper中myLooper()方法的代码如下
public static @Nullable Looper myLooper() {
        //从当前线程中获取looper对象
        return sThreadLocal.get();
    }
    

注:threadLocal是用来保证多线程并发时数据一致性的一个对象,类似于一个map对象,可以存取数据,使不同线程的数据不受其他线程的干扰

因为handler大多是在主线程创建的,因此这个looper是从主线程()也就是ActivityThread中取出来的.那么ActivityThread是什么时候将looper对象Put进LocalThread的呢?看下方代码

public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, “ActivityThreadMain”);
SamplingProfilerIntegration.start();

    CloseGuard.setEnabled(false);

    Environment.initForCurrentUser();

    EventLogger.setReporter(new EventLoggingReporter());

    final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
    TrustedCertificateStore.setDefaultUserDirectory(configDir);

    Process.setArgV0("<pre-initialized>");
    //准备looper对象
    Looper.prepareMainLooper();

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

    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }

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

    
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    //开始轮询消息队列
    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");
}
可以看到上述代码中出现了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();
        }
}
    
private static void prepare(boolean quitAllowed) {
        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) {
        // 创建消息队列
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
上面的代码最终调用到了prepare方法,在这个方法中创建了一个Looper对象并set到了sThreadLocal对象中.至此,Handler创建时的Looper来源已经找到了,是ActivityThread线程main方法设置到主线程ThreadLocal对象中的一个looper.因此可以得出一个结论在同一个线程中创建的handler共享同一个looper.那么问题来了,looper取出消息后如何知道将消息交给谁处理?再往后看
handler发送消息
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);
    }
    //将消息加入到消息队列
    return queue.enqueueMessage(msg, uptimeMillis);
}
boolean enqueueMessage(Message msg, long when) {
    if (msg.target == null) {
        throw new IllegalArgumentException("Message must have a target.");
    }
    if (msg.isInUse()) {
        throw new IllegalStateException(msg + " This message is already in use.");
    }

    synchronized (this) {
        if (mQuitting) {
            IllegalStateException e = new IllegalStateException(
                    msg.target + " sending message to a Handler on a dead thread");
            Log.w(TAG, e.getMessage(), e);
            msg.recycle();
            return false;
        }

        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        //消息需要立即处理,放在队头
        if (p == null || when == 0 || when < p.when) {
            // New head, wake up the event queue if blocked.
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            // Inserted within the middle of the queue.  Usually we don't have to wake
            // up the event queue unless there is a barrier at the head of the queue
            // and the message is the earliest asynchronous message in the queue.
            needWake = mBlocked && p.target == null && msg.isAsynchronous();
            Message prev;
            for (;;) {
                prev = p;
                p = p.next;
                if (p == null || when < p.when) {
                    break;
                }
                if (needWake && p.isAsynchronous()) {
                    needWake = false;
                }
            }
            msg.next = p; // invariant: p == prev.next
            prev.next = msg;
        }

        // We can assume mPtr != 0 because mQuitting is false.
        //判断是否应该唤醒
        if (needWake) {
            //拿写描述符写数据,会唤醒主线程
            nativeWake(mPtr);
        }
    }
    return true;
}
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中保存的target变量,即发消息的handler的dispatchMessage方法
            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();
    }
}
阻塞机制,采用的是linux中的一种进程间通信方式,管道(pipe),有一个特殊的文件,有两个描述符,一个读,一个写.一个进程拿读描述符读数据,另一个进程拿写描述符写数据.如果读数据进程读不到数据就会阻塞,写数据进程写入数据后就会唤醒读数据进程读数据
messageQueue 调用next()会去读消息,读不到就会阻塞, 代码如下
Message next() {
    // Return here if the message loop has already quit and been disposed.
    // This can happen if the application tries to restart a looper after quit
    // which is not supported.
    final long ptr = mPtr;
    if (ptr == 0) {
        return null;
    }

    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;//阻塞的时间
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }
        //就是这个native方法会产生阻塞
        nativePollOnce(ptr, nextPollTimeoutMillis);

        synchronized (this) {
            // Try to retrieve the next message.  Return if found.
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                // Stalled by a barrier.  Find the next asynchronous message in the queue.
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                //根据时间判断当前消息是否需要处理
                if (now < msg.when) {
                //当前消息没到时间不需要处理,根据当前时间计算新的睡眠时间
                    // Next message is not ready.  Set a timeout to wake up when it is ready.
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                }else {
                    //当前消息需要处理,返回该消息
                    // Got a message.
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                    msg.markInUse();
                    return msg;
                }
        }        
    }
}
Looper.loop()方法中调用了msg.target.dispatchMessage(msg)方法,那么这个target是什么呢?我们回到sendMessageAtTime()方法
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) {
    //此处将当前的handler对象赋值给msg.target
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    //将消息加入到消息队列
    return queue.enqueueMessage(msg, uptimeMillis);
}
从上面的代码可以看出,msg.target.dispatchMessage(msg)中的target就是发送该消息的handler,下面跟进dispatchMessage方法
public void dispatchMessage(Message msg) {
    //此处的callback就是postdelay中传入Runnable对象
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //如果没有callback就调用用户重写的handleMessage()方法
        handleMessage(msg);
    }
}
好了,逼装完了,领盒饭了.urpig.jpg
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值