Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 線程管理(二)——ActivityThread 深入解析

編輯:關於 Android 開發

Android 線程管理(二)——ActivityThread 深入解析

線程通信、ActivityThread 與 Thread 類別,是理解 Android 線程管理的關鍵。線程作為 CPU 調度資源的基本單位,在 Android 這類針對嵌入式裝置的作業系統中,扮演著極為重要且基礎的角色。


二、ActivityThread 的主要工作與實現機制

ActivityThread 是 Android 應用的主線程(UI 線程)。談到 ActivityThread,不得不提到 Activity 的建立、啟動過程以及 ActivityManagerService。本文僅從線程管理的角度切入,ActivityManagerService、ActivityStack、ApplicationThread 等會在後續文章中詳述。不過為了說清 ActivityThread 的由來,仍需簡單鋪陳一下。

以下引用自羅升陽的部落格《Android 應用程序的 Activity 啟動過程簡要介紹和學習計劃》:

 

Step 1. 無論是通過Launcher來啟動Activity,還是通過Activity內部調用startActivity接口來啟動新的Activity,都通過Binder進程間通信進入到ActivityManagerService進程中,並且調用ActivityManagerService.startActivity接口; 

Step 2. ActivityManagerService調用ActivityStack.startActivityMayWait來做准備要啟動的Activity的相關信息;

Step 3. ActivityStack通知ApplicationThread要進行Activity啟動調度了,這裡的ApplicationThread代表的是調用ActivityManagerService.startActivity接口的進程,對於通過點擊應用程序圖標的情景來說,這個進程就是Launcher了,而對於通過在Activity內部調用startActivity的情景來說,這個進程就是這個Activity所在的進程了;

Step 4. ApplicationThread不執行真正的啟動操作,它通過調用ActivityManagerService.activityPaused接口進入到ActivityManagerService進程中,看看是否需要創建新的進程來啟動Activity;

Step 5. 對於通過點擊應用程序圖標來啟動Activity的情景來說,ActivityManagerService在這一步中,會調用startProcessLocked來創建一個新的進程,而對於通過在Activity內部調用startActivity來啟動新的Activity來說,這一步是不需要執行的,因為新的Activity就在原來的Activity所在的進程中進行啟動;

Step 6. ActivityManagerServic調用ApplicationThread.scheduleLaunchActivity接口,通知相應的進程執行啟動Activity的操作;

Step 7. ApplicationThread把這個啟動Activity的操作轉發給ActivityThread,ActivityThread通過ClassLoader導入相應的Activity類,然後把它啟動起來。

這段描述把 ActivityManagerService、ActivityStack、ApplicationThread 與 ActivityThread 的呼叫關係講得很清楚。本文將從 ActivityThread 的 main() 方法開始,分析其主要工作與實現機制。

ActivityThread 源碼來自:https://github.com/android/platform_frameworks_base/blob/master/core/java/android/app/ActivityThread.java

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()); AndroidKeyStoreProvider.install(); // 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>"); 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")); } // End of event ActivityThreadMain. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }

上述程式碼中,較前面的部分主要用於環境初始化、AndroidKeyStoreProvider 安裝等,這裡不贅述。核心部分可分為兩大功能塊:1)綁定應用進程到 ActivityManagerService;2)主線程 Handler 消息處理。

關於線程通信機制,Handler、MessageQueue、Message 與 Looper 四者的關係請參考上一篇文章《Android 線程管理——線程通信》。

2.1 應用進程綁定

main() 方法透過 thread.attach(false) 綁定應用進程。ActivityManagerNative 透過 getDefault() 回傳 ActivityManagerService 實例,後者再透過 attachApplication 把 ApplicationThread 物件綁定到 ActivityManagerService,而 ApplicationThread 作為 Binder,實現了 ActivityManagerService 對應用進程的通信與控制。

private void attach(boolean system) { sCurrentActivityThread = this; mSystemThread = system; if (!system) { ……
 RuntimeInit.setApplicationObject(mAppThread.asBinder()); final IActivityManager mgr = ActivityManagerNative.getDefault(); try { mgr.attachApplication(mAppThread); } catch (RemoteException ex) { // Ignore } ……
 } else { …… } }

在 ActivityManagerService 內部,attachApplication 實際是透過 attachApplicationLocked 實現,並以 synchronized 關鍵字保證同步。

@Override public final void attachApplication(IApplicationThread thread) { synchronized (this) { int callingPid = Binder.getCallingPid(); final long origId = Binder.clearCallingIdentity(); attachApplicationLocked(thread, callingPid); Binder.restoreCallingIdentity(origId); } }

attachApplicationLocked 的實現較為複雜,主要分為兩部分:thread.bindApplication 與 mStackSupervisor.attachApplicationLocked(app)。

private final boolean attachApplicationLocked(IApplicationThread thread, int pid) { // Find the application record that is being attached... either via // the pid if we are running in multiple processes, or just pull the // next app record if we are emulating process with anonymous threads. ProcessRecord app; if (pid != MY_PID && pid >= 0) { synchronized (mPidsSelfLocked) { app = mPidsSelfLocked.get(pid); } } else { app = null; } // …… try { // …… thread.bindApplication(processName, appInfo, providers, app.instrumentationClass, profilerInfo, app.instrumentationArguments, app.instrumentationWatcher, app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace, enableTrackAllocation, isRestrictedBackupMode || !normalMode, app.persistent, new Configuration(mConfiguration), app.compat, getCommonServicesLocked(app.isolated), mCoreSettingsObserver.getCoreSettingsLocked()); updateLruProcessLocked(app, false, null); app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis(); } catch (Exception e) { // todo: Yikes! What should we do? For now we will try to // start another process, but that could easily get us in // an infinite loop of restarting processes... Slog.wtf(TAG, "Exception thrown during bind of " + app, e); app.resetPackageList(mProcessStats); app.unlinkDeathRecipient(); startProcessLocked(app, "bind fail", processName); return false; } // See if the top visible activity is waiting to run in this process... if (normalMode) { try { if (mStackSupervisor.attachApplicationLocked(app)) { didSomething = true; } } catch (Exception e) { Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); badApp = true; } } // …… }

這裡的 thread 物件其實是 ActivityThread 中 ApplicationThread 物件在 ActivityManagerService 的代理,因此執行 thread.bindApplication 最終會呼叫 ApplicationThread 的 bindApplication 方法。該方法的實質,是向 ActivityThread 的消息佇列發送 BIND_APPLICATION 消息,進而呼叫 handleBindApplication。其中較關鍵的一步是:

mInstrumentation.callApplicationOnCreate(app);

也就是呼叫應用程式 Application 的 onCreate(),這說明 Application 的 onCreate() 會比所有 Activity 的 onCreate() 更早被呼叫。

mStackSupervisor 是 ActivityManagerService 的成員變數,型別為 ActivityStackSupervisor,是 Activity 堆疊管理的輔助類別。其 attachApplicationLocked() 會呼叫 realStartActivityLocked(),後者再呼叫 scheduleLaunchActivity():

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume, boolean checkConfig) throws RemoteException { //... try { //... app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken, System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration), r.compat, r.icicle, results, newIntents, !andResume, mService.isNextTransitionForward(), profileFile, profileFd, profileAutoStop); //... } catch (RemoteException e) { //... } //... return true; }

app.thread 同樣是 ApplicationThread 在 ActivityManagerService 的代理,最終會呼叫 ApplicationThread 的 scheduleLaunchActivity 方法,透過向 ActivityThread 的消息佇列發送消息,在 ActivityThread 中完成實際的 LAUNCH_ACTIVITY 操作。

// we use token to identify this activity without having to send the // activity itself back to the activity manager. (matters more with ipc) @Override public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident, ActivityInfo info, Configuration curConfig, Configuration overrideConfig, CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state, PersistableBundle persistentState, List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) { updateProcessState(procState, false); ActivityClientRecord r = new ActivityClientRecord(); …… sendMessage(H.LAUNCH_ACTIVITY, r); }

在 ActivityThread 的 handleMessage 中,會針對 LAUNCH_ACTIVITY 呼叫 handleLaunchActivity(r, null) 來啟動 Activity。具體的啟動流程這裡不細述,重點在於釐清 ApplicationThread 與 ActivityThread 的線程通信機制。

2.2 主線程消息處理

那麼 ActivityThread 中的線程通信與普通線程有何不同呢?主要體現在兩點:1)Looper 的初始化方式;2)Handler 的生成方式。

首先,ActivityThread 透過 Looper.prepareMainLooper() 初始化 Looper。對比兩種初始化方式:

/** 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)); } /** * 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. See also: {@link #prepare()} */ public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }

差異在於:普通線程的 prepare() 預設 quitAllowed 為 true,表示允許退出;而 ActivityThread 在 prepareMainLooper() 中呼叫 prepare(false),表示主線程不允許退出。此外,ActivityThread 在呼叫 prepare() 之後,會透過 myLooper() 把本地線程 ThreadLocal 中的 Looper 參照交給 sMainLooper,藉此透過 getMainLooper() 將主線程的 Looper 開放給其他線程。

其次,普通線程只需生成一個與 Looper 綁定的 Handler 即可;而 ActivityThread 透過 sMainThreadHandler 指向 getHandler() 的回傳值,實際上回傳的是一個繼承 Handler 的 H 物件。

private class H extends Handler { …… } final H mH = new H(); final Handler getHandler() { return mH; }

真正讓消息機制「暢通」的,其實是 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.recycle(); } }

大致流程如下:

首先透過 myLooper() 取得 Looper 物件,取出其持有的 MessageQueue;接著從 MessageQueue 取出 Message,若 Message 為 null 表示線程正在退出;若不為空,則呼叫 Message 的 target handler 進行分發處理;處理完畢後,呼叫 recycle() 進行回收。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved