安卓中的消息循环模型

引子

Android应用程序是通过消息来驱动的,即在应用程序的主线程(UI线程)中有一个消息循环,负责处理消息队列中的消息。Android应用程序是支持多线程的,即可以创建子线程来执行一些计算型的任务。

  • 这些子线程能不能像应用程序的主线程一样具有消息循环呢?
  • 这些子线程又能不能往应用程序的主线程中发送消息呢?

一、原理

在开发Android应用程序中,有时候我们需要在应用程序中创建一些常驻的子线程来不定期地执行一些不需要与应用程序界面交互的计算型的任务。如果这些子线程具有消息循环,那么它们就能够常驻在应用程序中不定期的执行一些计算型任务了:当我们需要用这些子线程来执行任务时,就往这个子线程的消息队列中发送一个消息,然后就可以在子线程的消息循环中执行我们的计算型任务了。

但是,Android应用程序的子线程是不可以操作主线程的UI的,那么,这个子线程应该如何在应用程序界面上显示信息呢?如果我们能够在子线程中往主线程的消息队列中发送消息,那么问题就迎刃而解了,因为发往主线程消息队列的消息最终是由主线程来处理的,在处理这个消息的时候,我们就可以在应用程序界面上显示信息了。

二、消息循环模型

2.1 应用程序主线程消息循环模型

当运行在Android应用程序框架层中的ActivityManagerService决定要为当前启动的应用程序创建一个主线程的时候,它会在ActivityManagerService中的startProcessLocked成员函数调用Process类的静态成员函数start为当前应用程序创建一个主线程:

public final class ActivityManagerService extends ActivityManagerNative    
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {    
    
    ......    
    
    private final void startProcessLocked(ProcessRecord app,    
                String hostingType, String hostingNameStr) {    
    
        ......    
    
        try {    
            int uid = app.info.uid;    
            int[] gids = null;    
            try {    
                gids = mContext.getPackageManager().getPackageGids(    
                    app.info.packageName);    
            } catch (PackageManager.NameNotFoundException e) {    
                ......    
            }    
                
            ......    
    
            int debugFlags = 0;    
                
            ......    
                
            int pid = Process.start("android.app.ActivityThread",    
                mSimpleProcessManagement ? app.processName : null, uid, uid,    
                gids, debugFlags, null);    
                
            ......    
    
        } catch (RuntimeException e) {    
                
            ......    
    
        }    
    }    
    
    ......    
    
}    

Process.start函数的第一个参数“android.app.ActivityThread”,它表示要在当前新建的线程中加载android.app.ActivityThread类,并且调用这个类的静态成员函数main作为应用程序的入口点。ActivityThread类定义在frameworks/base/core/java/android/app/ActivityThread.java文件中:

public final class ActivityThread {  
    ......  
  
    public static final void main(String[] args) {  
        ......
  
        Looper.prepareMainLooper();  
         
        ......  
  
        ActivityThread thread = new ActivityThread();  
        thread.attach(false);  
  
        ...... 
        Looper.loop();  
  
        ...... 
  
        thread.detach();  
        ......  
    }  
  
    ......  
}  

在这个main函数里面,除了创建一个ActivityThread实例外,就是在进行消息循环了。

在进行消息循环之前,首先会通过Looper类的静态成员函数prepareMainLooper为当前线程准备一个消息循环对象。Looper类定义在frameworks/base/core/java/android/os/Looper.java文件中:

public class Looper {
    ......
 
    private static final ThreadLocal sThreadLocal = new ThreadLocal();
 
    final MessageQueue mQueue;
 
    ......
 
    /** Initialize the current thread as a looper.
    * This gives you a chance to create handlers that then reference
    * this looper, before actually starting the loop. Be sure to call
    * {@link #loop()} after calling this method, and end it by calling
    * {@link #quit()}.
    */
    public static final void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper());
    }
 
    /** Initialize the current thread as a looper, marking it as an application's main 
    *  looper. The main looper for your application is created by the Android environment,
    *  so you should never need to call this function yourself.
    * {@link #prepare()}
    */
 
    public static final void prepareMainLooper() {
        prepare();
        setMainLooper(myLooper());
        if (Process.supportsProcesses()) {
            myLooper().mQueue.mQuitAllowed = false;
        }
    }
 
    private synchronized static void setMainLooper(Looper looper) {
        mMainLooper = looper;
    }
 
    /**
    * Return the Looper object associated with the current thread.  Returns
    * null if the calling thread is not associated with a Looper.
    */
    public static final Looper myLooper() {
        return (Looper)sThreadLocal.get();
    }
 
    private Looper() {
        mQueue = new MessageQueue();
        mRun = true;
        mThread = Thread.currentThread();
    }
 
    ......
}

Looper类的静态成员函数prepareMainLooper是专门应用程序的主线程调用的,应用程序的其它子线程都不应该调用这个函数来在本线程中创建消息循环对象,而应该调用prepare函数来在本线程中创建消息循环对象。

函数prepareMainLooper做的事情其实就是在线程中创建一个Looper对象,这个Looper对象是存放在sThreadLocal成员变量里面的,成员变量sThreadLocal的类型为ThreadLocal,表示这是一个线程局部变量,即保证每一个调用了prepareMainLooper函数的线程里面都有一个独立的Looper对象。在线程是创建Looper对象的工作是由prepare函数来完成的,而在创建Looper对象的时候,会同时创建一个消息队列MessageQueue,保存在Looper的成员变量mQueue中,后续消息就是存放在这个队列中去。MessageQueue的具体定义和实现是通过JNI方法完成的。

为应用程序的主线程专门准备一个创建消息循环对象的函数,是为了让其它地方能够方便地通过Looper类的getMainLooper函数来获得应用程序主线程中的消息循环对象。获得应用程序主线程中的消息循环对象是为了能够向应用程序主线程发送消息了。

消息循环对象创建好之后,回到ActivityThread类的main函数中,接下来,就是要进入消息循环了:

 Looper.loop(); 

2.2 应用程序子线程消息循环模型

在Java框架中,如果我们想在当前应用程序中创建一个子线程,一般就是通过自己实现一个类,这个类继承于Thread类,然后重载Thread类的run函数,把我们想要在这个子线程执行的任务都放在这个run函数里面实现。最后实例这个自定义的类,并且调用它的start函数,这样一个子线程就创建好了,并且会调用这个自定义类的run函数。但是当这个run函数执行完成后,子线程也就结束了,它没有消息循环的概念。

不过有时候我们需要在应用程序中创建一些常驻的子线程来不定期地执行一些计算型任务,这时候就可以考虑使用Android系统提供的HandlerThread类了,它具有创建具有消息循环功能的子线程的作用。

HandlerThread类实现在frameworks/base/core/java/android/os/HandlerThread.java文件中。

public class HandlerThread extends Thread {
    ......
    private Looper mLooper;
 
    public HandlerThread(String name) {
        super(name);
        ......
    }
 
    ......
 
    public void run() {
        ......
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            ......
        }
        ......
        Looper.loop();
        ......
    }
 
    public Looper getLooper() {
        ......
        return mLooper;
    }
 
    ......
}

HandlerThread类继承了Thread类,因此,通过它可以在应用程序中创建一个子线程。在它的run函数中,会进入一个消息循环中,因此,这个子线程可以常驻在应用程序中,直到它接收收到一个退出消息为止。

在run函数中,首先是调用Looper类的静态成员函数prepare来准备一个消息循环对象:

Looper.prepare();

然后通过Looper类的myLooper成员函数将这个子线程中的消息循环对象保存在HandlerThread类中的成员变量mLooper中:

mLooper = Looper.myLooper();

这样,其它地方就可以方便地通过它的getLooper函数来获得这个消息循环对象了,有了这个消息循环对象后,就可以往这个子线程的消息队列中发送消息,通知这个子线程执行特定的任务了。

最在这个run函数通过Looper类的loop函数进入消息循环中:

Looper.loop();

这样,一个具有消息循环的应用程序子线程就准备就绪了。

三、应用程序消息处理机制(Looper、Handler)

Android应用程序通过消息来驱动,系统为每一个应用程序维护一个消息队例,应用程序的主线程不断地从这个消息队例中获取消息(Looper),然后对这些消息进行处理(Handler),这样就实现了通过消息来驱动应用程序的执行。

3.1 消息循环

在消息处理机制中,消息都是存放在一个消息队列中去,而应用程序的主线程就是围绕这个消息队列进入一个无限循环的,直到应用程序退出。如果队列中有消息,应用程序的主线程就会把它取出来,并分发给相应的Handler进行处理;如果队列中没有消息,应用程序的主线程就会进入空闲等待状态,等待下一个消息的到来。在Android应用程序中,这个消息循环过程是由Looper类来实现的,它定义在frameworks/base/core/java/android/os/Looper.java文件中,上文已经介绍过。

在上面这些工作都准备好之后,就调用Looper类的loop函数进入到消息循环中去了:

public class Looper {
    ......
 
    public static final void loop() {
        Looper me = myLooper();
        MessageQueue queue = me.mQueue;
 
        ......
 
        while (true) {
            Message msg = queue.next(); // might block
            ......
 
            if (msg != null) {
                if (msg.target == null) {
                    // No target is a magic identifier for the quit message.
                    return;
                }
 
                ......
 
                msg.target.dispatchMessage(msg);
                
                ......
 
                msg.recycle();
            }
        }
    }
 
    ......
}

这里就是进入到消息循环中去了,它不断地从消息队列mQueue中去获取下一个要处理的消息msg,如果消息的target成员变量为null,就表示要退出消息循环了,否则的话就要调用这个target对象的dispatchMessage成员函数来处理这个消息,这个target对象的类型为Handler,下面我们分析消息的发送时会看到这个消息对象msg是如设置的。

这个函数最关键的地方便是从消息队列中获取下一个要处理的消息了,即MessageQueue.next函数,它实现在frameworks/base/core/java/android/os/MessageQueue.java文件中:

public class MessageQueue {
    ......
 
    final Message next() {
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
 
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            nativePollOnce(mPtr, nextPollTimeoutMillis);
 
            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                final Message msg = mMessages;
                if (msg != null) {
                    final long when = msg.when;
                    if (now >= when) {
                        mBlocked = false;
                        mMessages = msg.next;
                        msg.next = null;
                        if (Config.LOGV) Log.v("MessageQueue", "Returning message: " + msg);
                        return msg;
                    } else {
                        nextPollTimeoutMillis = (int) Math.min(when - now, Integer.MAX_VALUE);
                    }
                } else {
                    nextPollTimeoutMillis = -1;
                }
 
                // If first time, then get the number of idlers to run.
                if (pendingIdleHandlerCount < 0) {
                    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("MessageQueue", "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;
 
            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }
 
    ......
}

调用这个函数的时候,有可能会让线程进入等待状态。什么情况下,线程会进入等待状态呢?两种情况:

  • 一是当消息队列中没有消息时,它会使线程进入等待状态;
  • 二是消息队列中有消息,但是消息指定了执行的时间,而现在还没有到这个时间,线程也会进入等待状态。

消息队列中的消息是按时间先后来排序的,后面我们在分析消息的发送时会看到。

这里的等待,是空闲等待,而不是忙等待,在进入空闲等待状态前,如果应用程序注册了IdleHandler接口来处理一些事情,那么就会先执行这里IdleHandler,然后再进入等待状态。IdlerHandler是定义在MessageQueue的一个内部类:

public class MessageQueue {
    ......
 
    /**
    * Callback interface for discovering when a thread is going to block
    * waiting for more messages.
    */
    public static interface IdleHandler {
        /**
        * Called when the message queue has run out of messages and will now
        * wait for more.  Return true to keep your idle handler active, false
        * to have it removed.  This may be called if there are still messages
        * pending in the queue, but they are all scheduled to be dispatched
        * after the current time.
        */
        boolean queueIdle();
    }
 
    ......
}

它只有一个成员函数queueIdle,执行这个函数时,如果返回值为false,那么就会从应用程序中移除这个IdleHandler,否则的话就会在应用程序中继续维护着这个IdleHandler,下次空闲时仍会再执会这个IdleHandler。MessageQueue提供了addIdleHandler和removeIdleHandler两注册和删除IdleHandler。

3.2 消息的发送

应用程序的主线程准备好消息队列并且进入到消息循环后,其它地方就可以往这个消息队列中发送消息了。

代码中需要将消息封装成Message对象msg,然后通过Handler类的基类实现的sendMessage函数把这个消息对象msg加入到应用程序的消息队列中去。自定义的基类继承于Handler类,安卓源码中的样例如下:

public final class ActivityThread {  
  
    ......  
  
    private final class H extends Handler {  
  
        ......  
  
        public void handleMessage(Message msg) {  
            ......  
            switch (msg.what) {    
            ......  
            }  
  
        ......  
  
    }  
  
    ......  
} 

这个H类就是通过其成员函数handleMessage函数来处理消息的。H类继承于Handler类,当创建这个H对象时,会调用Handler类的构造函数,这个函数定义在frameworks/base/core/java/android/os/Handler.java文件中:

public class Handler {
    ......
 
    public Handler() {
        ......
 
        mLooper = Looper.myLooper();
        ......
 
        mQueue = mLooper.mQueue;
        ......
    }
 
 
    final MessageQueue mQueue;
    final Looper mLooper;
    ......
}

在Hanlder类的构造函数中,主要就是初始成员变量mLooper和mQueue了。这里的myLooper是Looper类的静态成员函数,通过它来获得一个Looper对象,这个Looper对象就是前面我们在分析消息循环时,在ActivityThread类的main函数中通过Looper.prepareMainLooper函数创建的。Looper.myLooper函数实现在frameworks/base/core/java/android/os/Looper.java文件中:

public class Looper {
    ......
 
    public static final Looper myLooper() {
        return (Looper)sThreadLocal.get();
    }
 
    ......
}

有了这个Looper对象后,就可以通过Looper.mQueue来访问应用程序的消息队列了。

有了这个Handler对象H后,就可以通过它来往应用程序的消息队列中加入新的消息了。就开始调用H.sendMessage函数来发送消息了,这个函数定义在frameworks/base/core/java/android/os/Handler.java文件中:

public class Handler {
    ......
 
    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)
    {
        boolean sent = false;
        MessageQueue queue = mQueue;
        if (queue != null) {
            msg.target = this;
            sent = queue.enqueueMessage(msg, uptimeMillis);
        }
        else {
            ......
        }
        return sent;
    }
 
    ......
}

在发送消息时,是可以指定消息的处理时间的,但是通过sendMessage函数发送的消息的处理时间默认就为当前时间,即表示要马上处理,因此,从sendMessage函数中调用sendMessageDelayed函数,传入的时间参数为0,表示这个消息不要延时处理,而在sendMessageDelayed函数中,则会先获得当前时间,然后加上消息要延时处理的时间,即得到这个处理这个消息的绝对时间,然后调用sendMessageAtTime函数来把消息加入到应用程序的消息队列中去。

在sendMessageAtTime函数,首先得到应用程序的消息队列mQueue,这是在Handler对象构造时初始化好的,前面已经分析过了,接着设置这个消息的目标对象target,即这个消息最终是由谁来处理的:

msg.target = this;

这里将它赋值为this,即表示这个消息最终由这个Handler对象来处理,设置为别的对象,则会控制其他进程实现。

函数最后调用queue.enqueueMessage来把这个消息加入到应用程序的消息队列中去,这个函数实现在frameworks/base/core/java/android/os/MessageQueue.java文件中:

public class MessageQueue {
    ......
 
    final boolean enqueueMessage(Message msg, long when) {
        ......
 
        final boolean needWake;
        synchronized (this) {
            ......
 
            msg.when = when;
            //Log.d("MessageQueue", "Enqueing: " + msg);
            Message p = mMessages;
            if (p == null || when == 0 || when < p.when) {
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked; // new head, might need to wake up
            } else {
                Message prev = null;
                while (p != null && p.when <= when) {
                    prev = p;
                    p = p.next;
                }
                msg.next = prev.next;
                prev.next = msg;
                needWake = false; // still waiting on head, no need to wake up
            }
 
        }
        if (needWake) {
            nativeWake(mPtr);
        }
        return true;
    }
 
    ......
}

把消息加入到消息队列时,分两种情况,一种当前消息队列为空时,这时候应用程序的主线程一般就是处于空闲等待状态了,这时候就要唤醒它,另一种情况是应用程序的消息队列不为空,这时候就不需要唤醒应用程序的主线程了,因为这时候它一定是在忙着处于消息队列中的消息,因此不会处于空闲等待的状态。

第一种情况比较简单,只要把消息放在消息队列头就可以了:

msg.next = p;
mMessages = msg;
needWake = mBlocked; // new head, might need to wake up

第二种情况相对就比较复杂一些了,前面我们说过,当往消息队列中发送消息时,是可以指定消息的处理时间的,而消息队列中的消息,就是按照这个时间从小到大来排序的,因此,当把新的消息加入到消息队列时,就要根据它的处理时间来找到合适的位置,然后再放进消息队列中去:

Message prev = null;
while (p != null && p.when <= when) {
    prev = p;
    p = p.next;
}
msg.next = prev.next;
prev.next = msg;
needWake = false; // still waiting on head, no need to wake up

把消息加入到消息队列去后,如果应用程序的主线程正处于空闲等待状态,就需要调用natvieWake函数来唤醒它了,这是一个JNI方法。

3.3 消息的处理

在Looper类的loop成员函数中进行消息循环过程, 它从消息队列中获得消息对象msg后,就会调用它的target成员变量的dispatchMessage函数来处理这个消息。

在前面分析消息的发送时说过,这个消息对象msg的成员变量target是在发送消息的时候设置好的,一般就通过哪个Handler来发送消息,就通过哪个Handler来处理消息。

dispatchMessage函数定义在frameworks/base/core/java/android/os/ Handler.java文件中:

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

这里的消息对象msg的callback成员变量和Handler类的mCallBack成员变量一般都为null,于是,就会调用Handler类的handleMessage函数来处理这个消息,由于子类在继承Handler类时,一般会重写handleMessage函数,因此,这里调用的实际上是子类的handleMessage函数。例:

public final class ActivityThread {  
  
    ......  
  
    private final class H extends Handler {  
  
        ......  
  
        public void handleMessage(Message msg) {  
            ......  
            switch (msg.what) {  
            case LAUNCH_ACTIVITY: {  
                ActivityClientRecord r = (ActivityClientRecord)msg.obj;  
  
                r.packageInfo = getPackageInfoNoCheck(  
                    r.activityInfo.applicationInfo);  
                handleLaunchActivity(r, null);  
            } break;  
            ......  
            }  
  
        ......  
  
    }  
  
    ......  
}  

四、总结

整个Handler的处理模型可以用下图来说明:

安卓中的消息循环模型_第1张图片
Handler处理模型

而安卓中的多线程消息模型如下表示:

安卓中的消息循环模型_第2张图片
安卓消息机制

线程模型的序列图如下:

安卓中的消息循环模型_第3张图片
初始化阶段
安卓中的消息循环模型_第4张图片
执行阶段

参考文章:

老罗博客

你可能感兴趣的:(安卓中的消息循环模型)