天天看點

android Handler、Looper、Messsage、MessageQueue源碼解析

Handler:發送和接收消息

Looper:消息(循環)輪詢器

Message:消息池

MessageQueue:消息隊列。雖然名為隊列,但事實上它的内部存儲結構并不是真正的隊列,而是采用單連結清單的資料結構來存儲消息清單的

先來看Handler,其實系統很多東西都是通過Handler消息來實作的,其中也包括activity的生命周期,應用程式的退出等;在ActivityThread類中的main方法中可以很清楚的看到,同時main方法也是android應用程式的主入口;

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

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");
	//執行個體化一個main Looper
        Looper.prepareMainLooper();
	//執行個體化ActivityThread
        ActivityThread thread = new ActivityThread();
	//調用attach方法
        thread.attach(false);
	//通過ActivityThread擷取Handler對象
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
	//開啟消息輪詢器
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
           

在執行個體化一個main looper的時候調用的是prepareMainLooper();方法;prepareMainLooper();方法是Looper類中的方法;

public static void prepareMainLooper() {
	//調用prepare方法
        prepare(false);
        synchronized (Looper.class) {
	//這裡需要注意隻能執行個體化一個main Looper對象,多次執行個體化會報錯
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
           

prepare();方法這裡就暫時不講了,後面會講到,執行個體化完mian looper後,就會去執行個體化ActivityThread對象并調用其中的attach()方法及getHandler()方法去執行個體化一個Handler對象;

final Handler getHandler() {
	//mH extends Handler 在加載ActivityThread的時候就已經初始化了
        return mH;
    }
           
private class H extends Handler {
        public static final int LAUNCH_ACTIVITY         = 100;
        public static final int PAUSE_ACTIVITY          = 101;      
        public static final int DESTROY_ACTIVITY        = 109;
        public static final int EXIT_APPLICATION        = 111;
        public static final int STOP_SERVICE            = 116;

        String codeToString(int code) {
            if (DEBUG_MESSAGES) {
                switch (code) {
                    case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
                    case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
                    case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
                    case EXIT_APPLICATION: return "EXIT_APPLICATION";                   
                    case STOP_SERVICE: return "STOP_SERVICE";                  
                }
            }
            return Integer.toString(code);
        }
        public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
                case LAUNCH_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;              
                case PAUSE_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
                    SomeArgs args = (SomeArgs) msg.obj;
                    handlePauseActivity((IBinder) args.arg1, false,
                            (args.argi1 & USER_LEAVING) != 0, args.argi2,
                            (args.argi1 & DONT_REPORT) != 0, args.argi3);
                    maybeSnapshot();
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;                
                case DESTROY_ACTIVITY:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityDestroy");
                    handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
                            msg.arg2, false);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;              
                case EXIT_APPLICATION:
                    if (mInitialApplication != null) {
                        mInitialApplication.onTerminate();
                    }
                    Looper.myLooper().quit();
                    break;                
                case STOP_SERVICE:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
                    handleStopService((IBinder)msg.obj);
                    maybeSnapshot();
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;                
            }         
    }
           

H類就是一個内部類,看到LAUNCH_ACTIVITY、PAUSE_ACTIVITY、EXIT_APPLICATION、STOP_SERVICE等很多消息辨別,這樣通過handler消息來控制activity的生命周期以及一些其他東西;當msg.what為EXIT_APPLICATION時,應用程式就會退出,并不是activity的生命周期都會走,當消息辨別為EXIT_APPLICATION應用程式就已經退出了,而應用程式的退出時調用Looper中的quit方法;

public void quit() {
        mQueue.quit(false);
    }
           

這裡就粗略而過,後面會詳細講;這是一些系統handler的使用,還是看看平時開發中的使用吧;

public class MainActivity extends AppCompatActivity {
    Handler mHanlder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //開啟子線程
        new MyThread().start();
    }

    class MyThread extends Thread implements Runnable {
        @Override
        public void run() {
            super.run();
            //執行個體化消息輪詢器
            Looper.prepare();
            //執行個體化handler對象
            mHanlder = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                }
            };
            //擷取message對象
            Message message = mHanlder.obtainMessage();
            message.what = 1;
            //發送消息
            mHanlder.sendMessage(message);
            //開啟looper輪詢器
            Looper.loop();
        }
    }
}
           

這是一段在子線程中執行個體化handler的代碼,當然了也可以不線上程中執行個體化handler,這樣子就不需要執行個體化一個Looper,系統已經實作了的,如果在子線中執行個體化handler就需要同樣執行個體化一個Looper,確定handler所線上程和Looper所在的線程一緻,否則會報錯;

先來看第一步Looper.prepare()執行個體化一個Looper;

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

private static void prepare(boolean quitAllowed) {
    //調用prepare方法quitAllowed就為true,調用的是prepareMainLooper方法quitAllowed就是false
    //sThreadLocal.get()是直接從ThreadLocal池中擷取 這裡同樣隻能執行個體化一個Looper,多次執行個體化會報錯
    if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
    }
    //直接new 一個Looper,并将執行個體化的Looper對象添加到ThreadLocal池中
    sThreadLocal.set(new Looper(quitAllowed));
}
           

在new 一個looper的時候會去執行個體化一個MessageQueue對象;

private Looper(boolean quitAllowed) {
    //直接執行個體化一個MessageQueue對象
    mQueue = new MessageQueue(quitAllowed);
    //擷取目前線程
    mThread = Thread.currentThread();
}
           

第二步handler的執行個體化

handler提供多個構造方法,可以傳入一個Looper,Callback回調等,這裡直接用了無參構造;

public Handler() {
    this(null, false);
}
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());
        }
    }
    //擷取執行個體化好的looper對象,這裡是從ThreadLocal池中直接擷取的
    mLooper = Looper.myLooper();
    //如果擷取到的looper對象為null就會報錯,是以要保證執行個體化好的looper對象和handler對象所在的線程要一緻,
    //也就是平時如果在子線程中執行個體化handler沒有執行個體化looper報錯的原因
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    //擷取MessageQueue對象,MessageQueue對象在執行個體化looper的構造方法中就已經執行個體化好了
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}
           
public static @Nullable Looper myLooper() {
//myLooper是looper類中的方法,從ThreadLocal池中直接擷取looper對象
    return sThreadLocal.get();
}
           

第三步Message對象的執行個體化,通過obtainMessage();方法擷取的Message對象,當然也可以直接new 一個Message,不過建議使用obtainMessage();方法擷取;

public final Message obtainMessage()
{
    //調用Handler類中的obtainMessage方法,傳回一個Message對象,不過調用的是Message中的obtain方法,并将Handler本身做參數傳入
    return Message.obtain(this);
}
           
public static Message obtain(Handler h) {
//這裡又調用了Message中的obtain()方法
    Message m = obtain();
//将傳入的handler對象指派給Message中的target變量
    m.target = h;
    return m;
}
/**
  * Return a new Message instance from the global pool. Allows us to
	傳回一個Message執行個體,從全局池中
  * avoid allocating new objects in many cases.
  */
public static Message obtain() {
    synchronized (sPoolSync) {
	//判斷Message池是否為null
        if (sPool != null) {
	    //不為null就将sPool對象指派個m
            Message m = sPool;
	    //又将m中的指派給sPool 這裡是連結清單結構
            sPool = m.next;
            m.next = null;
            m.flags = 0; // clear in-use flag
            sPoolSize--;
	    //将擷取到的message執行個體傳回
            return m;
        }
    }
    //sPool為null的情況下直接new 一個Message對象并傳回
    return new Message();
}
           

Message類中還提供了recycleUnchecked()方法,用于handler消息的回收,這裡暫不說;Message對象有了,調用sendMessage()發送消息,當然了Handler類中不隻這一個方法可以發送消息,還有其他的方法,具體可以看Handler源碼;

/**
  * Pushes a message onto the end of the message queue after all pending messages
  * before the current time. It will be received in {@link #handleMessage},
  * in the thread attached to this handler.
  *  
  * @return Returns true if the message was successfully placed in to the 
  *         message queue.  Returns false on failure, usually because the
  *         looper processing the message queue is exiting.
  */
public final boolean sendMessage(Message msg)
{
    return sendMessageDelayed(msg, 0);
}
           
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
    //delayMillis延遲發送的時間 毫秒值
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
           
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    //擷取MessageQueue對象,mQueue是在執行個體化handler時,通過looper對象擷取,最初是在執行個體化looper對象的構造方法中執行個體化的
    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指派給Message中的handler
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}
           

走到這裡就會去調用MessageQueue中的enqueueMessage()方法;

boolean enqueueMessage(Message msg, long when) {
        //msg.target就是handler對象,上面已經進行了指派操作
        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);
		//調用recycle方法,如果沒有被回收就會調用recycleUnchecked()方法進行handler消息的回收
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
	    //建立新的Message對象,并指派
            Message p = mMessages;
            boolean needWake;
	    //建立的message對象為null或者沒有延遲發送消息或者延遲發送消息的時間小于發送的時間
            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();開啟輪詢去取消息;

/**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
	//擷取looper對象,如果為null說明沒有執行個體化looper對象,會報錯
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
	//擷取MessageQueue對象,MessageQueue對象是在執行個體化looper對象的構造方法中執行個體化的
        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死循環,不管是ActivityThread中的void main方法,還是平時使用loop()方法都是在最後面調用,這樣不會阻塞
        for (;;) {
	    //這裡是連結清單結構,通過next()去擷取每一個message對象
            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 {
		//将擷取到的message消息通過handler中的dispatchMessage方法進行分發
                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);
            }
	    //通過messsage中的recycleUnchecked方法對消息進行回收
            msg.recycleUnchecked();
        }
    }
           
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();
            }

            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 {
			//将msg指派給prevMsg
                        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;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

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

            // 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;
        }
    }
           
/**
  * Handle system messages here.
  */
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
	//設定了callback就會走這裡
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
	//這裡是沒有設定callback
        handleMessage(msg);
    }
}
           
/**
  * Subclasses must implement this to receive messages.
  *執行個體化handler的時候都會去重寫該方法,在該方法中進行消息的處理
  */
public void handleMessage(Message msg) {
}
           

在消息處理完畢後,還會對消息進行回收的;

/**
     * Recycles a Message that may be in-use.
     * Used internally by the MessageQueue and Looper when disposing of queued Messages.
     */
    void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;

        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }
           

Looper.loop();中是一個死循環,是以在使用handler消息的時候需要注意當頁面銷毀後要将消息移除掉,避免造成記憶體洩漏什麼的;handler提供一些移除消息的方法;

/**
  * Remove any pending posts of callbacks and sent messages whose
  * <var>obj</var> is <var>token</var>.  If <var>token</var> is null,
  * all callbacks and messages will be removed.
  */
public final void removeCallbacksAndMessages(Object token) {
    //token為null的時候所有的callback和messages都會被移除掉
    mQueue.removeCallbacksAndMessages(this, token);
}
           

當然也可以移除指定的消息或者callback;上面就是對handler消息的一些源碼分析。