編輯:Android 資訊
好久沒有認真寫過部落格了,突然意識到許多學過的知識若不及時總結消化,終究無法真正內化為自己的東西。而寫部落格的好處之一,就是能在梳理的過程中發現當初學習時未曾留意的問題。
自大二上學期自學 Android 以來,我一直沒有對「從系統啟動到 App 運行」這一整條鏈路做過系統性的歸納。恰逢最近又接觸了一些新知識,索性就以這篇文章為契機,把從 Android 開機到應用運行的全過程梳理一遍,順帶談談 ClassLoader、JVM、IPC、訊息處理機制等關鍵概念。當然,這裡不會糾結於過多細節,比如 PMS 內部為何要如此設計、優點何在,這類問題暫且留待日後。以我目前的水平與精力而言,先建立對整體流程的宏觀認知、養成大局觀,才是最要緊的事。
廢話不多說,我們正式進入主題。
首先,Android 是一個基於 Linux 的作業系統,它可以分為五層。下方是它的層次架構圖,建議記下來,因為後文會談到 SystemServer 等屬於 Application Framework 層的內容。

這五層架構從上到下依次為:應用層、應用框架層、函式庫層、執行環境層,以及最底層的 Linux 內核層。
在 Linux 中,啟動流程大致可以概括為:Boot Loader → 初始化內核 → 後續各項初始化。當內核初始化完成後,會啟動一個至關重要的祖先行程——init 行程。在 Linux 體系中,所有行程都是由 init 行程直接或間接 fork 出來的。
對 Android 而言,前面的流程與此一致。當 init 行程建立之後,它會 fork 出一個名為 Zygote 的行程,這個行程是所有 Java 行程的父行程。我們知道 Linux 基於 C,而 Android 的應用層基於 Java,因此系統會 fork 出一個 Zygote 的 Java 行程,用它來分裂出其他行程。【斷點 1】
在總結到這裡時,先介紹幾個後文將反覆出現的重要角色與一個關鍵概念:
Android 系統中的客戶端與伺服器概念
其實 Android 系統中也存在著伺服器與客戶端的概念。這裡的伺服器端,指的是所有 App 共用的系統服務,例如前面提到的 AMS、PackageManagerService 等。這些系統服務被所有 App 共享,當某個 App 需要執行某項操作時,便會向這些系統服務發出請求。
當 Zygote 完成初始化後,會 fork 出 System Server 行程。這個行程在整個 Android 體系中地位舉足輕重,可與 Zygote 相提並論,它屬於 Application Framework 層。Android 中所有的服務,諸如 AMS、WindowManager、PackageManagerService 等,都是由這個 System Server 分裂出來的,可見其分量之重。
而當 System Server 行程啟動後,它會初始化 AMS,同時載入本地系統的服務庫、建立系統上下文、建立 ActivityThread 並開啟各項服務。在此之後,系統才會啟動 Launcher 程式,完成系統介面的載入與顯示。【斷點 2】
Context 是一個抽象類,以下是摘自原始碼的註解資訊:
/** * Interface to global information about an application environment. This is * an abstract class whose implementation is provided by * the Android system. It * allows access to application-specific resources and classes, as well as * up-calls for application-level operations such as launching activities, * broadcasting and receiving intents, etc. */ public abstract class Context {
從這段註解可以簡單理解為:Context 是一個關於應用程式環境的全域介面,透過它能夠存取應用專屬的資源與類別,例如啟動 Activity、發送廣播、處理 Intent 等。
我的理解是:Context 的具體實作是 Application、Activity 與 Service,透過 Context 應用程式才能具備執行某些操作的「權限」,本質上是一個執行環境的問題。
需要注意的地方
由於 Android 開發中大量場景都涉及 Context,因此必須警惕可能引發的記憶體洩漏問題。舉例來說,Toast 的 Context 最好設定為 Application Context。因為若 Toast 在顯示內容期間 Activity 被關閉,而 Toast 仍持有該 Activity 的引用,那麼這個 Activity 就無法被回收,從而導致記憶體洩漏。
說到 Toast,其實它也是個頗有意思的元件,它的 show 方法並不像表面看起來那樣只是「顯示一段文字」這麼簡單。
Toast 實際上是一個佇列,show 方法會把新的任務加入佇列中,只要佇列裡存在訊息就會依次彈出顯示。據說佇列長度預設為 40 個(這是網上查到的說法,我在原始碼中沒有找到對應設定,覺得力有未逮便沒有深究)。
所以這裡要特別注意:show 這個操作並不是「顯示內容」,而是「把內容加入佇列」。
/** * Show the view for the specified duration. */ public void show() { if (mNextView == null) { throw new RuntimeException("setView must have been called"); } INotificationManager service = getService(); String pkg = mContext.getOpPackageName(); TN tn = mTN; tn.mNextView = mNextView; try { service.enqueueToast(pkg, tn, mDuration); } catch (RemoteException e) { // Empty } }
如果我們直接在 Android Studio 中建立一個非靜態內部類 Handler,那麼這一區塊會被 IDE 標記為黃色警告,相信很多人都遇過。這背後的原因,正是這樣的寫法可能造成記憶體洩漏:每個非靜態內部類都會持有外部類的引用,一旦 Activity 被銷毀時未與 Handler 解除關聯,Handler 仍會持有該 Activity 的引用,進而導致洩漏。
解決方案
使用 static 修飾 Handler,將其變為靜態內部類,如此便不再持有外部類的引用。此時可以在 Handler 內部建立一個 WeakReference(弱引用)來持有外部物件,只要外部解除對該引用的綁定,垃圾回收器在發現這個弱引用時便會立即將其回收。
關於垃圾回收的詳細總結,可以參考我之前的文章《JVM 原理及底層探索》。
既然談到了弱引用,就順便梳理一下 Java 的四種引用方式:
類別載入器按層級從上到下依次為:Bootstrap ClassLoader(啟動類別載入器)、Extension ClassLoader(擴充類別載入器)、Application ClassLoader(應用程式類別載入器)。
判斷兩個類是否為同一個類,關鍵在於它們是否由同一個類別載入器載入而來。
這裡需要介紹一下雙親委派模式:除了啟動類別載入器之外,其餘載入器都需要指定一個父載入器。當需要載入類別時,會先讓父載入器嘗試載入,若父載入器無法載入(即找不到該類別),才會交由子載入器去載入。
好處:防止記憶體中出現多份相同的位元組碼。
舉例來說,若類 A 和類 B 都要載入 System 類,如果沒有委派機制,A 會載入一份,B 也會載入一份,記憶體中便出現兩份 System 位元組碼。而採用委派機制時,會遞迴地向父類查找,優先由 Bootstrap 嘗試載入,找不到再逐層向下;若 A 已經載入過,便會直接返回記憶體中的 System,無需重新載入,如此便只會存在一份。
對 Java 而言,類別只有在被使用到時才會載入,這便形成了一種延遲載入的效果。而在延遲載入時,預設會保持同步,這正好催生了一種單例模式的實作方式(具體可參考我之前的文章《設計模式_單例模式》)。
我認為在 Android 所有的單例實作方式中,延遲載入(懶漢式)是最佳選擇之一。雖然列舉(enum)方式更為優秀,《Effective Java》也大力推薦,但它並不十分適用於 Android——Android 中列舉的記憶體消耗約為 static 的兩倍。而延遲載入方式只要我們在實作時妥善準備好反序列化的 readResolve() 返回值即可。
至此,我們已經完成了整個 Android 系統的開機與初始化。接下來,便可談談從點擊 App 圖示開始,到 App 內部程式真正跑起來的這一流程了。
當我們點擊螢幕時,觸控螢幕的兩層電極會接通,從而產生一個電壓變化,驅動程式便會將當前按壓點的 XY 座標上報給作業系統。作業系統取得座標後,會判斷按壓點落在哪個範圍內;若確認它位於某個 App 圖示或按鈕之上,便會認定使用者點擊了該元件,啟動對應的監聽。
而當系統判斷使用者點擊的是 App 圖示時,該 App 便由 Launcher 開始啟動。【斷點 3】
Launcher 是一個繼承自 Activity,同時實作了點擊事件、長按事件等多種監聽的應用程式。
public final class Launcher extends Activity implements View.OnClickListener,OnLongClickListener, LauncherModel.Callbacks,View.OnTouchListener
當我們點擊某個 App 的圖示時,會呼叫 Launcher 內部的 startActivitySafely() 方法。這個方法主要做兩件事:一是啟動目標 Activity,二是捕獲 ActivityNotFoundException 異常,也就是我們常見的「找不到 Activity,是否已在 AndroidManifest 中註冊?」提示。而在 startActivity 方法內部,經過一連串轉換,最終會呼叫到 startActivityForResult。
@Override public void startActivity(Intent intent, @Nullable Bundle options) { if (options != null) { startActivityForResult(intent, -1, options); } else { // Note we want to go through this call for compatibility with // applications that may have overridden the method. startActivityForResult(intent, -1); } }
所以,我對整個 Android 介面是這樣理解的:系統完成初始化與各項服務建立之後,便會啟動 Launcher 這個應用程式(它同樣繼承自 Activity,擁有自己對應的 XML 佈局),再把各種圖示按照正常 App 的佈局方式排列其上。當我們點擊 App 圖示時,就相當於在 Launcher 這個應用程式中,透過 startActivity(底層最終會轉為 startActivityForResult)來啟動目標 App。簡單來說,就是一個主要的 App(Launcher)裡啟動了其他功能各異的 App,例如 QQ、微信等。【個人理解,日後若有發現不對之處再修正】
當手指按下時,Android 是如何處理點擊事件的?又是如何決定由哪一個控制元件來響應的?
一句話概括:層層傳遞、類似冒泡的方式。
舉個例子:公司來了個小專案,老闆一看分配給經理,經理一看分配給小組長,小組長一看覺得簡單,分配給組員。在這個傳遞過程中(尚未分配到底層時),若某一層覺得自己來負責更合適,就會攔截下這個訊息並自行處理,下面各層便收不到通知。若一直傳到底層,組員能完成就由組員完成;若組員無法勝任,就回報給組長,組長也做不來就交給經理,經理也不會就交給老闆。如此便完成了一層層的傳遞與回退。
總結來說:訊息從上到下依次傳遞,若在傳遞途中被攔截便停止下傳;若未被攔截則一路傳到底部,而底部若無法消費該訊息,便又一層層往上返回,直到被某層消費或抵達最頂層。
在 Android 中,有三個關鍵方法:
第一個方法負責事件的分發,其返回值表示是否消費當前事件。
第二個方法用於判斷是否攔截訊息,一旦某個 View 攔截了某事件,那麼在同一事件序列中,此方法不會被再次呼叫;返回值表示是否攔截當前事件。
第三個方法負責處理事件,返回值表示是否消費當前事件;若不消費,則在同一事件序列中,當前 View 將無法再次接收到事件。
以一個根 ViewGroup 為例:點擊事件產生後,首先傳遞給它,呼叫其 dispatch 方法。若這個 ViewGroup 的 onIntercept 返回 true,表示它要攔截當前事件;返回 false 則表示不攔截,事件便會繼續傳遞給子元素,接著呼叫子元素的 dispatch 方法,直到被處理為止。
順帶總結一下滑動衝突的處理。View 的滑動衝突一般可分為三種情況:
比如一個常見場景:外層一個 ListView,內層一個 ScrollView,這時該如何解決?其實可以借鑑 ViewPager 的思路,它內部已經處理過滑動衝突。
滑動處理規則
一般來說,我們可以根據使用者手指滑動的方向與角度,判斷使用者意圖朝哪個方向滑動;很多時候也可以依據專案需求,制定一套合適的滑動方案。
外部攔截法
這種方法指所有點擊事件都先經過父容器的攔截處理:父容器需要此事件就攔截,不需要就不攔截。透過重寫父容器的 onInterceptTouchEvent 方法:
case MotionEvent.ACTION_DOWN: intercepted = false; break; case MotionEvent.ACTION_MOVE: if(父類容器需要) { intercepted = true; } else { intercepted = false; } break; case MotionEvent.ACTION_UP: intercepted = false; break; return intercepted;
這裡有一點需特別注意:ACTION_DOWN 事件父容器必須返回 false,因為一旦父容器攔截了它,後續的 MOVE 等所有事件都會直接由父容器處理,無法再傳給子元素。UP 事件也應返回 false,因為它本身意義不大,但對子元素而言卻不同——若被攔截,子元素的 onClick 事件便無法觸發。
內部攔截法
這種方法指父容器不攔截任何事件,所有事件都傳給子元素,子元素若需要就直接消費,否則交回父容器處理。它需要配合 requestDisallowInterceptTouchEvent 方法才能正常運作,我們需要重寫子元素的 dispatch 方法:
case MotionEvent.ACTION_DOWN: parent.requestDisallowInterceptTouchEvent(true); break; MotionEvent.ACTION_MOVE: if(父容器需要此類點擊事件) { parent.requestDisallowInterceptTouchEvent(false); } break; return super.dispatchTouchEvent(event);
這種方法中,父容器需預設攔截除 ACTION_DOWN 以外的其他事件,這樣當子元素呼叫 request 方法時,父元素才能重新攔截所需的事件。
其他方式
如果覺得上述兩種方式過於繁瑣,也可以依據專案實際需求自行制定策略。例如根據手指按壓點的位置,判斷當前觸碰的是哪個控制元件,藉此推測使用者是否要對該元件進行操作;若點擊的是空白處,則操作外部控制元件即可。
【待日後有暇,再總結一下 ViewPager 的處理方式,這部分挺重要的】
Android 的訊息機制主要指 Handler 的運行機制,而 Handler 的運行需要底層的 MessageQueue 與 Looper 支撐。
雖然 MessageQueue 名為「訊息佇列」,但它內部的儲存結構其實是單向鏈結串列。由於 Message 只是一個訊息的儲存單元,本身無法處理訊息,這時 Looper 便補上了這一環節:Looper 以無限循環的形式檢查是否有新訊息,有則處理,無則等待。而對 Looper 來說,還存在一個非常重要的概念——ThreadLocal。
ThreadLocal 並不是一個執行緒,而是一個能在每個執行緒中獨立儲存資料的類別。透過它可以在指定執行緒中儲存資料,且這些資料只有在該執行緒中才能取得,其他執行緒則無法存取。
舉例來說,多個執行緒透過同一個 ThreadLocal 取得的東西是不同的。即使偶爾出現結果相同的情況(兩執行緒分別存了兩份相同內容),它們取值的本質仍然不同。
那為什麼會有這種差異?又為何要如此設計?我們先來探究結果背後的原理。
ThreadLocal 中有兩個關鍵方法:get 與 set,一個負責讀取,一個負責設定。
/** * Returns the value of this variable for the current thread. If an entry * doesn't yet exist for this variable on this thread, this method will * create an entry, populating the value with the result of * {@link #initialValue()}. * * @return the current value of the variable for the calling thread. */ @SuppressWarnings("unchecked") public T get() { // Optimized for the fast path. Thread currentThread = Thread.currentThread(); Values values = values(currentThread); if (values != null) { Object[] table = values.table; int index = hash & values.mask; if (this.reference == table[index]) { return (T) table[index + 1]; } } else { values = initializeValues(currentThread); } return (T) values.getAfterMiss(this); } /** * Sets the value of this variable for the current thread. If set to * {@code null}, the value will be set to null and the underlying entry will * still be present. * * @param value the new value of the variable for the caller thread. */ public void set(T value) { Thread currentThread = Thread.currentThread(); Values values = values(currentThread); if (values == null) { values = initializeValues(currentThread); } values.put(this, value); }
先研究 get 方法。從註解可以看出,get 會返回「當前執行緒」的變數值,若陣列不存在則建立一個新的。這裡有兩個關鍵詞:「當前執行緒」與「陣列」。
這裡提到的陣列對每個執行緒而言都是不同的(values.table),而 values 是透過當前執行緒取得的 Values 物件,因此這個陣列是每個執行緒獨有的、不能共用。接下來幾行程式碼更直白:先取一個索引,再透過索引返回陣列中對應的值。這便解釋了為何多個執行緒透過同一個 ThreadLocal 返回的是不同內容。
那為什麼要這樣設計呢?翻書查資料後,可以總結為以下幾點:
前面提到了 Handler、Looper、Message Queue,它們實際上是一個整體,只是我們在開發中接觸最多的是 Handler。Handler 的主要作用,是把一個任務切換到某個指定執行緒中去執行。而 Android 之所以提供這套機制,是因為系統規定 UI 只能在主執行緒中操作,若在子執行緒中存取 UI 就會拋出異常。
為什麼 Android 不允許在子執行緒存取 UI
其實這不僅是 Android,所有圖形介面系統目前採用的都是單執行緒模型。
因為對多執行緒而言,若子執行緒修改了 UI,那麼它的相關操作就必須對其他子執行緒可見,也就是 Java 並發中極重要的「執行緒可見性」與 Happen-before 原則。而對這種並發存取,通常採用加鎖機制,但加鎖存在明顯問題:會讓 UI 存取之間的邏輯變得複雜、效率降低,甚至有時還會造成死鎖,那就更麻煩了。
至於究竟能否實現 UI 介面的多執行緒?SUN 公司某位技術專家曾表示:「實現肯定沒問題,但非常考驗技術,因為必須兼顧各種情況,需要技術專家來設計。而這種設計出來的東西,對廣大普通程序員而言異常棘手,即便實現了多執行緒,普通人用起來也會怨聲載道。所以還是建議採用單執行緒。」
順帶談談死鎖。
死鎖的四個必要條件
舉個常見的死鎖例子:行程 A 持有資源 A,行程 B 持有資源 B,A 下一步需要資源 B,B 下一步需要資源 A,於是兩者互相等待對方釋放佔有的資源,形成循環等待死鎖。
處理死鎖的方法
MessageQueue 主要包含兩個操作:插入與讀取,而讀取操作本身伴隨著刪除。插入與讀取對應的方法分別是 enqueueMessage 與 next:enqueueMessage 負責往佇列中插入一條訊息,next 則從佇列中取出一條訊息並將其移除。這也正是採用單向鏈結串列維護訊息列表的原因——它在插入與刪除上更具優勢(只需切換下一個連結點即可)。
對 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(); } 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; } } 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; } }
原始碼有點長,總結一下就是:next 方法是一個死循環,若訊息佇列中沒有訊息,它就會一直阻塞在這裡;當有新訊息到來時,它便返回這條訊息並將其從單向鏈結串列中移除。
而此時 Looper 正在等待,它同樣一直循環,不停地從 MessageQueue 中檢查是否有新訊息,有則立即處理,無則阻塞等待。而對 Looper 來說,它是唯一且只能建立一個的,這要歸功於它的 prepare 方法。
/** 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 void prepare() { prepare(true); } 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)); }
由此可見,prepare 方法會先檢測是否已存在 Looper:若不存在則建立一個新的,若已存在則拋出異常。之後呼叫 Looper.loop() 便能開啟訊息循環。
/** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the 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 Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); 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(); } }
從中可以看到,它也是個死循環,會不停地呼叫 queue.next() 取得訊息:若沒有就 return,若有就處理。
注意
這裡有一個容易被忽略的重點:若在子執行緒中手動為其建立了 Looper,那麼所有事情完成後,應呼叫 quit 方法終止訊息循環,否則該子執行緒會一直處於等待狀態;而退出 Looper 後,執行緒便會立即終止。所以建議在不再需要時終止 Looper。
Handler
前面總結了 Looper 與 MessageQueue,這裡再談談 Handler。它的工作主要包含訊息的發送與接收:發送可透過一系列 post 方法或 send 方法實現,而 post 系列最終也是透過 send 系列來完成的。
實際上,它發送訊息的過程僅僅是向訊息佇列中插入一條訊息,MessageQueue 的 next 方法便會返回這條訊息給 Looper,Looper 收到後開始處理,最後交給 Handler 的 handleMessage() 方法來處理。
總結完 Android 的訊息處理機制,就順便談談 IPC 通訊,畢竟前面多次提到了 Binder 與 Socket。
行程的定義
UNIX 標準把行程定義為「一個其中運行著一個或多個執行緒的位址空間,以及這些執行緒所需的系統資源」。目前可以簡單地把行程看作正在運行的程式。
每個行程都會被分配一個唯一的數字編號,我們稱之為 PID(行程識別符),它通常是一個取值範圍從 2 到 32768 的正整數。行程啟動時,系統會按順序選擇下一個未被使用的數字作為 PID,當數字繞行一圈後,新的 PID 會重新從 2 開始,數字 1 一般保留給 init。行程中擁有自己獨立的堆疊空間,用於保存函式中的區域變數以及控制函式的呼叫與返回;行程還有自己的環境空間,包含專為該行程建立的環境變數,同時必須維護自己的程式計數器,用來記錄執行到的位置。
守護行程
這裡需要提到守護行程,它在各類底層系統中經常被提及。在 Linux 或 UNIX 中,系統引導時會開啟許多服務,這些服務便稱為守護行程。守護行程是脫離於終端並在背景運行的行程;之所以要脫離終端,是為了避免行程執行過程中的資訊在任何終端上顯示,也避免行程被終端產生的資訊所打斷。守護行程常在系統引導時啟動、系統關閉時終止。若想讓某個行程不受使用者、終端或其他變化的影響,就必須把它變成守護行程。
防止手機服務背景被殺死
在手機設定介面查看正在運行的服務時,你會發現有些 App 不止存在一個服務,有的背景存在兩個甚至三個。部分惡意軟體也會這樣設置,以此長期駐留背景、讓使用者關也關不掉(當然並非所有這樣設置的都是惡意軟體,有些軟體確實需要保持長期背景在線,這是由功能決定的)。
這裡總結兩種常見方法:
IPC 通訊
總結完行程相關基礎,這裡便開始談談行程間通訊(IPC)。目前 Linux 現有的 IPC 方式主要有:
於是問題來了:既然 Linux 已有這麼多優良的 IPC 方案,Android 為何還要另起爐灶採用 Binder 機制?
猜測:我認為 Android 採用這種新方式(當然也在大面積沿用 Linux 的 IPC 方式),無非兩個原因:一是手機廠商自定義 ROM 底層的保密性或公司間的利益關係;二是在某些情況下,它更適合手機這種低配置、對效率要求極高、用戶體驗至關重要的裝置。
資料
對 Binder 而言,具有以下優勢:
剛才談 Binder 時提到了效能問題,那這裡就不得不說說反射。反射允許一個類別在運行過程中取得任意類別的任意方法,這是 Java 的一項重要特性,它方便了程式員的開發,卻也降低了效率。
實際上,對非 Android 的大型專案而言,反射對效能的影響微乎其微,與其帶來的開發便利相比更是划算。但 Android 是運行於手機的系統,硬體資源有限,必須把用戶體驗放在首位。國外曾有統計:某 App 的 Splash 頁面使用了反射,結果運行時間增加了約一秒,這已是相當嚴重的效能損耗。
為什麼反射影響效能
這裡需要提到 JIT 編譯器。JIT 能把位元組碼轉換為處理器可直接使用的機器碼,經它處理的位元組碼效率提升巨大,但它有個缺點:把位元組碼轉換為機器碼的過程很慢,有時甚至還不如不轉換(轉換後存在複用問題,機器碼使用次數越多越划算)。因此 JVM 中產生了一種機制:把常用的、使用頻率高的位元組碼透過 JIT 轉換,頻率低的則不管。而反射則直接繞過了 JIT 編譯器,無論常用與否一律未經轉化,所以效率較低。
在 Android 中,5.0 之前使用的是 Dalvik 虛擬機,正是上述機制;而 5.0 之後,Google 推出了全新的 ART 虛擬機取而代之。ART 會在程式安裝時就將所有位元組碼全部轉化為機器碼,這雖會導致安裝時間變長,卻能大幅提升運行效率。
【疑問:那麼在 Android 5.0 之後的系統上,反射是否就沒有影響了?由於目前做專案更多考慮向下相容,尚未深入驗證 5.0 的單獨情況,待日後有需求或機會時再深入了解,以後更新】
前面總結了訊息處理機制與 IPC 通訊,那麼主執行緒的訊息處理機制是從何時開始的呢?我們知道,在主執行緒中並不需要手動呼叫 Looper.prepare() 與 Looper.loop()。
Android 的主執行緒就是 ActivityThread,其入口方法是 main。在 main 方法中,系統會透過 Looper.prepareMainLooper() 建立主執行緒的 Looper 與 MessageQueue,並透過 Looper.loop 開啟訊息循環——這一步系統已為我們代勞,無需自己動手。
ActivityThread 透過 ApplicationThread 與 AMS 進行行程間通訊。AMS 以行程間通訊方式完成 ActivityThread 的請求後,會回呼 ApplicationThread 中的 Binder 方法,隨後 ApplicationThread 向 Handler 發送訊息,Handler 收到後便將 ApplicationThread 中的邏輯切換到主執行緒執行,這便是主執行緒的訊息循環模型。
前面談到 App 開始運行、依序呼叫 onCreate/onStart/onResume 等方法,那麼 onCreate 中常用的 setContentView 與 findViewById 又做了什麼呢?
首先看 setContentView 做了什麼。這需要區分你繼承的 Activity 類型。若是直接繼承 Activity,其 setContentView 原始碼如下:
/** * Set the activity content from a layout resource. The resource will be * inflated, adding all top-level views to the activity. * * @param layoutResID Resource ID to be inflated. * * @see #setContentView(android.view.View) * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams) */ public void setContentView(@LayoutRes int layoutResID) { getWindow().setContentView(layoutResID); initWindowDecorActionBar(); } /** * Set the activity content to an explicit view. This view is placed * directly into the activity's view hierarchy. It can itself be a complex * view hierarchy. When calling this method, the layout parameters of the * specified view are ignored. Both the width and the height of the view * are set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use * your own layout parameters, invoke * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)} * instead. * * @param view The desired content to display. * * @see #setContentView(int) * @see #setContentView(android.view.View) */ public void setContentView(View view) { getWindow().setContentView(view); initWindowDecorActionBar(); } /** * Set the activity content to an explicit view. This view is placed * directly into the activity's view hierarchy. It can itself be a complex * view hierarchy. * * @param view The desired content to display. * @param params Layout parameters for the view. * * @see #setContentView(android.view.View) * @see #setContentView(int) */ public void setContentView(View view, ViewGroup.LayoutParams params) { getWindow().setContentView(view, params); initWindowDecorActionBar(); }
這裡有三個重載函式,但無論你呼叫哪一個,最終都會呼叫到 initWindowDecorActionBar() 方法。
而對於新的 AppCompatActivity,它內建了一些新特性,我目前的專案基本都用 AppCompatActivity 替代原生的 Activity(當然也並非絕對,仍需依專案實際情況選擇)。在 AppCompatActivity 中,setContentView 是這樣的:
@Override public void setContentView(@LayoutRes int layoutResID) { getDelegate().setContentView(layoutResID); } @Override public void setContentView(View view) { getDelegate().setContentView(view); } @Override public void setContentView(View view, ViewGroup.LayoutParams params) { getDelegate().setContentView(view, params); }
同樣是三個重載函式,只是內部不再有 init 方法,取而代之的是 getDelegate().setContentView。這個 delegate 顧名思義是一個委託物件,原始碼如下:
/** * @return The {@link AppCompatDelegate} being used by this Activity. */ @NonNull public AppCompatDelegate getDelegate() { if (mDelegate == null) { mDelegate = AppCompatDelegate.create(this, this); } return mDelegate; }
而在 AppCompatDelegate.create 方法中,會返回一個頗有意思的東西:
/** * Create a {@link android.support.v7.app.AppCompatDelegate} to use with {@code activity}. * * @param callback An optional callback for AppCompat specific events */ public static AppCompatDelegate create(Activity activity, AppCompatCallback callback) { return create(activity, activity.getWindow(), callback); } private static AppCompatDelegate create(Context context, Window window, AppCompatCallback callback) { final int sdk = Build.VERSION.SDK_INT; if (sdk >= 23) { return new AppCompatDelegateImplV23(context, window, callback); } else if (sdk >= 14) { return new AppCompatDelegateImplV14(context, window, callback); } else if (sdk >= 11) { return new AppCompatDelegateImplV11(context, window, callback); } else { return new AppCompatDelegateImplV7(context, window, callback); } }
這裡會依據 SDK 等級返回不同的實作,具體就不深究了。我掃了一眼底層,原理應該與 Activity 一致,可能存在一些差異,這裡就用 Activity 來談談它的 setContentView 究竟做了什麼。
setContentView 上方有一段註解:
Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.
這段話介紹了它的功能:它會依據一個佈局資源來設定 Activity 的內容,而該佈局資源會被 inflate(引入),然後把所有頂層 Views 添加到這個 Activity 中。
從網上找了一張示意圖:

這裡呈現了整個 Activity 的層級:最外層是我們的 Activity,它包含內部的一切;往上一層是 PhoneWindow,它由 Window 類派生而來,每個 PhoneWindow 都含有一個 DecorView 物件,而 Window 是一個抽象類;再往上就是 DecorView,我理解它本質上是一個 ViewGroup,用來裝載 View。在 DecorView 中,最上方的 View 是 TitleActionBar,下面就是我們要設定的 content。所以前面 initWindowDecorActionBar 方法的用意,也就不言自明了。
在 initWindowDecorActionBar 方法中有這麼一段程式碼:
/** * Creates a new ActionBar, locates the inflated ActionBarView, * initializes the ActionBar with the view, and sets mActionBar. */ private void initWindowDecorActionBar() { Window window = getWindow(); // Initializing the window decor can change window feature flags. // Make sure that we have the correct set before performing the test below. window.getDecorView(); if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) { return; } mActionBar = new WindowDecorActionBar(this); mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp); mWindow.setDefaultIcon(mActivityInfo.getIconResource()); mWindow.setDefaultLogo(mActivityInfo.getLogoResource()); }
請留意 window.getDecorView() 方法的註解:該方法會設定一些 window 的標誌位,而一旦此方法執行完畢,這些標誌位便無法再更改。這也正是為什麼許多第三方 SDK 在設定 window 標誌位時,一定要求在 setContentView 方法之前呼叫。
我們透過 findViewById 方法實現物件綁定,那它底層究竟是如何實現的呢?
findViewById 依繼承的 Activity 類型不同也存在差異,老規矩,仍以 Activity 為例。
/** * Finds a view that was identified by the id attribute from the XML that * was processed in {@link #onCreate}. * * @return The view if found or null otherwise. */ @Nullable public View findViewById(@IdRes int id) { return getWindow().findViewById(id); }
從原始碼看,findViewById 也是一層層往下呼叫,其功能如註解所述:透過 View 的 id 屬性查找 View。這裡同樣出現了熟悉的 getWindow 方法,說明 findViewById 實際上也是 Activity 把它交給了自己的 window 來處理。
/** * Finds a view that was identified by the id attribute from the XML that * was processed in {@link android.app.Activity#onCreate}. This will * implicitly call {@link #getDecorView} for you, with all of the * associated side-effects. * * @return The view if found or null otherwise. */ @Nullable public View findViewById(@IdRes int id) { return getDecorView().findViewById(id); }
在這裡面,又呼叫了 getDecorView 的 findViewById 方法,這同樣是一個層層傳遞的過程。由於 DecorView 本質上是一個 ViewGroup,而當運行 getDecorView().findViewById() 時,便會進入 View 裡面的 findViewById 方法。它會用給定的 id 去匹配子 View 的 Id,若匹配成功,便返回該 View,完成綁定。
/** * Look for a child view with the given id. If this view has the given * id, return this view. * * @param id The id to search for. * @return The view that has the given id in the hierarchy or null */ @Nullable public final View findViewById(@IdRes int id) { if (id < 0) { return null; } return findViewTraversal(id); } /** * {@hide} * @param id the id of the view to be found * @return the view of the specified id, null if cannot be found */ protected View findViewTraversal(@IdRes int id) { if (id == mID) { return this; } return null; }
最後總結一下(以 Activity 為例),findViewById 的過程是這樣的:
Activity → Window → DecorView → View
Android Studio Preview 常見問題與實用技巧大全
Android Studio 提供了一個強大的「Preview」工具,能幫助我們預覽布局文件在用戶設備上的呈現效果。XML 布局可能是 Android 開發中最常用的資源
深入解析 Android Window 與 WindowManager 機制
WindowManagerServiceWindow 分類WindowManager 使用WindowManager 的內部機制Window 的創建過程總結
九個能提升 Android 開發效率的 Web 工具
Android 原生工具很強,但有些工作放在瀏覽器裡反而更順手。以下工具涵蓋搜尋範例、查詢原始碼、產生素材、下載應用與資料格式化等常見場景。 1. Codota:尋找可
正確使用 Android 性能分析工具 TraceView
前面唠叨 最近公司 app 中有些列表在滑動時會有卡頓現象,我便著手解決這些問題。解決問題之前,首先要分析列表滑動的性能瓶頸在哪裡。因為之前不會正確使用 TraceVie