Android Looper解剖

首先提出几个问题,如果对以下几个问题都有深刻的了解,那么就不再建议看本文,直接略过

  • 1.我们常说的主线程指的是啥?
  • 2.Looper.getMainLooper()获取到的Looper是什么时候创建的?
  • 3.Looper是怎么处理消息的?怎么处理多个地方发送的Message先后顺序?
  • 4.MessageQueue在没有消息的处理时候是否会占用CPU?
  • 5.IdleHandler是什么原理,什么时候处理消息?

1.我们常说的主线程指的是啥?

程序启动后就执行的那个线程称为主线程(primary thread),主线程有两个特点,第一,它必须负责 GUI(Graphic User Interface)程序中的主消息循环。第二,这一线程的结束(不论是因为返回或因为调用了 ExitThread())会使得程序中的所有线程都被强迫结束,程序也因此而结束。其他线程没有机会做清理工作。

那么,主线程是啥时候启动的呢?

我们都知道,手机启动后,进入Launcher程序,里面会显示各种应用入口,当我们点击手机应用列表的图标后,应用就会启动,所以这里必然会有主线程的启动。

Luancher本身就是系统的一个app,有兴趣的可以看一下源码,这里就不做具体研究,非本文内容。既然Luancher也是一个应用,那从它那里点击应用列表中的图标后做了什么?这里就直接贴出onClick的代码(省略大部分代码)

public void onClick(View v) {
               .....

        Object tag = v.getTag();
        if (tag instanceof ShortcutInfo) {

            final Intent intent = ((ShortcutInfo) tag).intent;
            int[] pos = new int[2];
            v.getLocationOnScreen(pos);
            intent.setSourceBounds(new Rect(pos[0], pos[1],
                    pos[0] + v.getWidth(), pos[1] + v.getHeight()));
            boolean success = startActivitySafely(intent, tag);

           ....
        } else if (tag instanceof FolderInfo) {
             ....
        } else if (v == mAllAppsButton) {
           .....
        }
    }

boolean startActivitySafely(Intent intent, Object tag) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //注意这里的标志  是新的task
        try {
            startActivity(intent);
            return true;
        } catch (ActivityNotFoundException e) {
          ....
        } catch (SecurityException e) {
         ......
        }
        return false;
    }

这里做了一个操作,就是用一个设置了Intent.FLAG_ACTIVITY_NEW_TASK标志的intent,调用了startActivity()。有没有熟悉的感觉?没错,Launcher内部启动应用也是通过startActivity(),至于startActivity()怎么处理的,网上一搜一大把的activity启动流程,如果不太熟悉的,可以去研究一下。

startActivity()方法会执行到ActivityStackSupervisor.resumeTopActivityUncheckedLocked()

    void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid, true);
        if (app != null && app.thread != null) {
            try {
               ...
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                ...
            }
        }
        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                "activity", r.intent.getComponent(), false, false, true);
    }

在这里可以看到,如果app为空的话,会启动一个新的程序,这里可以继续看一下ActivityServiceManager. startProcessLocked()方法

    private final boolean startProcessLocked(ProcessRecord app, String hostingType,
            String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
        ...
        try {
          ...
            final String entryPoint = "android.app.ActivityThread";
            return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
                    runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
                    startTime);
        } catch (RuntimeException e) {
           ...
        }
    }

这里可以看到,通过startProcessLocked()传入的参数,其实就是ActivityThread,它由Process.start()调用到Zygote.start()方法,最后调用ZygoteProcess. zygoteSendArgsAndGetResult()方法,通过socket连接到Zygote进程后fork一个新的应用进程,这个新的进程会加载ActivityThread.java类,并执行它的main函数, 主角终于出现了,自此,主线程从main函数开始执行了。

到这里,我们已经知道第一个问题的答案了,那么,下面我们再找第二个问题的答案。

2.Looper.getMainLooper()获取到的Looper是什么时候创建的?

让我们先来看一下ActivityThread.main()方法的源码。

    public static void main(String[] args) {
        ...
        Looper.prepareMainLooper();
        ...
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        ...
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

简单整理一下main函数中完成了哪些工作

1.Looper.prepareMainLooper();这里会创建了一个Looper对象和一个MessageQueue对象
2.thread.attach(false);这里向MessageQueue队列中加入了一个Message,这个Message的what为H.BIND_APPLICATION

到这里,我想大家应该已经知道第二个问题的答案了,但我们还需要再深入解剖一下,这里就到了Looper.java中。

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

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

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

可以看到,在Looper. prepareMainLooper()中,对mainLooper进行了创建,也就是说,通过Looper .getMainLooper()方法获取到的looper,是在程序创建时,由ActivityThread.main()方法调用生成的。

3.Looper是怎么处理消息的?怎么处理多个地方发送的Message先后顺序?

再回过头看一下ActivityThread.main()方法,可以看到,最后执行了一个Looper.loop();,并且在这个方法执行完后,直接抛出了一个异常,我们知道,程序中抛出的异常如果没有被处理的话,程序是会GG的,这里这么做的话,肯定是不会想程序直接就崩了,也就是说这个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;
        ...
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            ...
            try {
                msg.target.dispatchMessage(msg);
               ...
            } finally {
               ...
            }
            ...
            msg.recycleUnchecked();
        }
    }

从上面的源码片段可以看出,这里果然有一个死循环,通过MessageQueue.next()取出message,再发交给Hanlder处理,这里的msg.target就是一个handler对象。

我们使用Hander发送消息比较简单,比如“任性”地使用:new Handler().sendMessage(new Message());,这样的一行代码,它实际上经过了如下几个处理:

1.实例化一个Handler,调用Handler的sendMessage()发送Message
2.sendMessage()实际调用的是sendMessageDelayed(),通过这个方法设置Message处理的时间when(有delay的用当前时间加delay,否则直接设置当前时间)
3.最终调用的是sendMessageAtTime(),在这个方法会给message.target赋值,并把消息添加到MessageQueue

   public Handler(Callback callback, boolean async) {
        ...
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
    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;
        ...
        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);
    }

至此,再简单梳理一下整体的流程:

1.startActivity在启动新程序时,会fork一个新的进程,然后会调用ActivityThread.main方法
2.通过Activity.main方法,初始化mianLooper,并进入Looper.loop()方法一直循环,调用MessageQueue.next获取到message,并发送给handler处理
3.通过主线程中实例化的handler的sendXXX或postXXX,最终把Messsage添加到MessageQueue中

我们知道,很多地方都能调用Handler发送消息,不同时间点发送的消息,它是怎么处理这个消息先顺序的呢?

我们再来看一下消息加入时怎么处理,通上前面的分析,我们知道handler发送消息最终调用的是MessageQueue.enqueueMessage()方法,在这个方法中,通过传入的when和mMessages进行判断,若mMessages不为空并且when

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

分析到了这里,我们发面,在MessgeQueue里保存的是一个以mMessages为队首,按when时间点排序的message链表,每次通过handler发送的msg,都会以when判断插入到合适的位置。

那我们再回到Looper.loop()方法,前面我们知道,这个方法里有个循环在一直调用MessageQueue.next()获取msg,并给msg.target的handler实例处理,这里再来研究一下MessageQueue.next()方法,这个方法也不复杂,这里我们先上一个简化版本的源码。

    Message next() {
       ...
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
           ...
            nativePollOnce(ptr, nextPollTimeoutMillis);
            synchronized (this) {
                ...
                Message prevMsg = null;
                Message msg = mMessages;
                ...
                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;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }
                ...                
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }
                ...
            }
            ...
            nextPollTimeoutMillis = 0;
        }
    }

从这里可以看到,它每次取的就是mMessages,通过when判断是否大于当前时间,大于当前时间则return给Looper.loop()处理,否则通过与当前时间差计算出nextPollTimeoutMillis,在下次循环时,调用nativePollOnce()会阻塞,如果有超时时间,在超时后,再次来处理这个mMessages(这时这个mMessages可能已经变了,比如又调用了handler.sendXXX通过queueMessage修改了这个值)。

也就是说,通过enqueueMessage()按when时间顺序添加到队列中,再由next()方法取出第一个进行处理,保证了Message按when时间点节的先后顺序进行处理。

4.MessageQueue在没有消息的处理时候是否会占用CPU?

这里再来讨论一下nativePollOnce(),这个方法是底层c++实现,有两个参数,一个是mPtr,它其实就是native层的进程号,在构造函数中通过mPtr = nativeInit();赋值,其实看android源码中会发现有很多这样的操作,后续会用这个进程号做参数处理相关逻辑。

这个方法还有一个参数是nextPollTimeoutMillis,第一次进循环时,它等于0也就是不阻塞,所以直接就通过了,但如果后面获取到的message.when还未到时间,则会计算出nextPollTimeoutMillis,再次循环运行到它的时候,会阻塞nextPollTimeoutMillis,等超时后再直接处理mMesaages,我们还可以看到,如果mMessages为空时,会传入-1一直阻塞下去。

这里有就有一个疑问,如果调用nativePollOnce()在阻塞过程中,它有唤醒的逻辑吗?我们再回去看看enqueueMessage()方法,可以看到最后添加消息后,会调用nativeWake(mPtr);,向文件描述符写入1,唤醒nativePollOnce(),让next()方法做后续处理。

分析到了这里,第四个问题的答案也有了,虽然Looper.loop()方法在循环调用MessageQueue.next()获取msg,next()方法中又有一个循环,获取到队列头,如果未到达运行时间,或是队列头为空,就会调用nativePollOnce()阻塞线程,释放CPU竞争,所以可以说它在没有消息处理时,是不占用CPU资源的。

5.IdleHandler是什么原理,什么时候处理消息?

先弄明白一些基本概念,什么是 IdleHandler?有什么用?怎么用?

IdleHandler 可以用来提升性能,主要用在我们希望能够在当前线程消息队列空闲时做些事情(譬如 UI 线程在显示完成后,如果线程空闲我们就可以提前准备其他内容)的情况下,不过最好不要做耗时操作。具体用法如下。

//getMainLooper().myQueue()或者Looper.myQueue()
Looper.myQueue().addIdleHandler(new IdleHandler() {  
    @Override  
    public boolean queueIdle() {  
        //你要处理的事情
        return false;    
    }  
});

这里再来看一下addIdleHandler的源码,从这里我们可以得到两点:

1.添加是线程安全的
2.通过查找可以得知mIdleHandlers是一个ArrayList,因此这个接口是可以重复添加的,不必担心被替换问题

    public void addIdleHandler(@NonNull IdleHandler handler) {
        if (handler == null) {
            throw new NullPointerException("Can't add a null IdleHandler");
        }
        synchronized (this) {
            mIdleHandlers.add(handler);
        }
    }

那么mIdleHandlers在哪里使用呢?这里再上一个简化版的next()方法。

    Message next() {
        ...
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        for (;;) {
           ...
            synchronized (this) {
              ...
                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }
                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }
            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler
                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }
                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }
            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;
            ...
        }
    }

在这里可以看出,next的循环中,如果mMessage为空,或是mMessage.when时间未到时,会循环获取mIdleHanders,挨个执行idler.queueIdle();,也就是说,如果当前没有message需要处理,就调用IdleHandler.queueIdle()方法,这也是IdleHandler为什么能在空闲时做相关处理的原因。

你可能感兴趣的:(Android Looper解剖)