一、寫在前面
在開始之前,你需要知道下面幾點:
- 有一份編譯好的 Android 原始碼,現在的 AS 基本能滿足,動手跟著步驟走,理解更深刻
- 對 Binder 機制有一定的了解
- 本文基于 API 26,用什么版本的原始碼并不重要,大體的流程并無本質上的區別
- 從用戶手指觸摸點擊桌面圖示到 Activity 啟動
關鍵類簡介
- ActivityManagerService:AMS 是 Android 中最核心的服務之一,主要負責系統中四大組件的啟動、切換、調度及應用行程的管理和調度等作業,其職責與作業系統中的行程管理和調度模塊相類似,它本身也是一個 Binder 的實作類,應用行程能通過 Binder 機制呼叫系統服務,
- ActivityThread:應用的入口類,系統通過呼叫main函式,開啟訊息回圈佇列,ActivityThread 所在執行緒被稱為應用的主執行緒(UI 執行緒),
- Instrumentation:工具類,它用來監控應用程式和系統的互動,包裝了 ActivityManagerService 的呼叫,一些插件化方案就是通過 hook 該類實作的,
- ActivityStarter:Activity 啟動的工具類,處理啟動 Activity 的各種 flag ,
- ActivityStackSupervisor:管理所有應用的 Activity 的堆疊,其中 mFocusedStack 就是當前應用的 Activity 堆疊,
應用行程介紹
- 在大多數情況下,每個 Android 應用都在各自的 Linux 行程中運行,當需要運行應用的一些代碼時,系統會為應用創建此行程,并使其保持運行,直到不再需要它且系統需要回收其記憶體以供其他應用使用,
- 應用行程的生命周期并不由應用本身直接控制,而是由系統綜合多種因素來確定的,比如系統所知道的正在運行的應用部分、這些內容對用戶的重要程度,以及系統中可用的總記憶體量,這是 Android 非常獨特的一個基本功能,
- 當應用組件啟動且該應用未運行任何其他組件時,Android 系統會使用單個執行執行緒為應用啟動新的 Linux 行程,默認情況下,同一應用的所有組件會在相同的行程和執行緒(稱為“主”執行緒)中運行,如果某個應用組件啟動且該應用已存在行程(因為存在該應用的其他組件),則該組件會在此行程內啟動并使用相同的執行執行緒,但是,您可以安排應用中的其他組件在單獨的行程中運行,并為任何行程創建額外的執行緒,
- 每個應用行程都相當于一個 Sandbox 沙箱,Android 通過對每一個應用分配一個 UID,注意這里的 UID 不同于 Linux 系統的 User ID,可以將每個應用理解為一個 User ,只能對其目錄下的內容具有訪問和讀寫權限,
- Android 利用遠程程序呼叫 (RPC) 提供了一種行程間通信 (IPC) 機制,在此機制中,系統會(在其他行程中)遠程執行由 Activity 或其他應用組件呼叫的方法,并將所有結果回傳給呼叫方,因此,您需將方法呼叫及其資料分解至作業系統可識別的程度,并將其從本地行程和地址空間傳輸至遠程行程和地址空間,然后在遠程行程中重新組裝并執行該呼叫,然后,回傳值將沿相反方向傳輸回來,Android 提供執行這些 IPC 事務所需的全部代碼,因此您只需集中精力定義和實作 RPC 編程介面,
下面這張圖可以補充理解一下行程的概念:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-L0wkWHQT-1632919531109)(//upload-images.jianshu.io/upload_images/1856419-c04a4f0fb34a7926.png?imageMogr2/auto-orient/strip|imageView2/2/w/678/format/webp)]
二、流程分析
先來一張流程簡圖:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-dv73EZ0Y-1632919531112)(//upload-images.jianshu.io/upload_images/1856419-234677e55f408b9c.png?imageMogr2/auto-orient/strip|imageView2/2/w/1106/format/webp)]
下面是流程詳細圖,帶你看完整個啟動流程及其所涉及到的類:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-4geW8WPo-1632919531115)(//upload-images.jianshu.io/upload_images/1856419-f334b3f2122b430c.png?imageMogr2/auto-orient/strip|imageView2/2/w/917/format/webp)]
下面補充一張 Gityuan 大神的系統啟動架構圖幫助理解,其實只要看看這張圖的上半部分就足夠了:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-3MMQZcf5-1632919531121)(//upload-images.jianshu.io/upload_images/1856419-88d738be242f6233.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp)]
三、概述
簡單地講,從 用戶手指觸摸點擊桌面圖示到 Activity啟動 可以用下面 4 步概括:
- 當點擊桌面 App 的時候,發起行程就是 Launcher 所在的行程,啟動遠程行程,利用 Binder 發送訊息給 system_server 行程;
- 在 system_server 中,啟動行程的操作會先呼叫
ActivityManagerService#startProcessLocked()方法,該方法內部呼叫Process.start(android.app.ActivityThread);而后通過 socket 通信告知 Zygote 行程 fork 子行程,即 app 行程,行程創建后將 ActivityThread 加載進去,執行ActivityThread#main()方法;
- 在 app 行程中,
main()方法會實體化 ActivityThread,同時創建 ApplicationThread,Looper,Handler 物件,呼叫ActivityThread#attach(false)方法進行 Binder 通信,方法里面呼叫ActivityManagerService#attachApplication(mAppThread)方法,將 thread 資訊告知 ActivityManagerService , 接著 Looper 啟動回圈;
- 回到 system_server 中,
ActivityManagerService#attachApplication(mAppThread)方法內部呼叫了thread#bindApplication()和mStackSupervisor#attachApplicationLocked()我們依次講解這兩個方法;
4.1thread#bindApplication()方法呼叫了ActivityThread#sendMessage(H.BIND_APPLICATION, data)方法,最終走到了ActivityThread#handleBindApplication(),進而創建 Application 物件,然后呼叫Application#attach(context)來系結 Context ,創建完 Application 物件后便是呼叫mInstrumentation#callApplicationOnCreate()執行Application#onCreate()生命周期;
4.2mStackSupervisor#attachApplicationLocked()方法中呼叫app#thread#scheduleLaunchActivity()即ActivityThread#ApplicationThread#scheduleLaunchActivity()方法,進而通過ActivityThread#sendMessage(H.LAUNCH_ACTIVITY, r)方法,最終走到了ActivityThread#handleLaunchActivity(),進而創建 Activity 物件,然后呼叫activity.attach()方法,再呼叫mInstrumentation#callActivityOnCreate()執行Activity#onCreate()生命周期;
四、原始碼呼叫探究
對應本文第一張流程圖的每一個步驟,下面逐步來看看原始碼是怎么呼叫的:
STEP 1
用戶點擊 app 圖示;
STEP 2
Launcher 捕獲點擊事件,呼叫 Activity#startActivity();
STEP 3
Activity#startActivity() 呼叫 Instrumentation;
Activity.java
@Override
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
@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);
}
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
···
} else {
···
}
}
STEP 4
Instrumentation 通過 Binder 通信發送訊息給 system_server 行程,具體 呼叫 ActivityManager#getService()#startActivity() ,ActivityManager#getService() 的具體實作是 ActivityManagerService ;
Instrumentation.java
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
···
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
ActivityManager.java
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
STEP 5
ActivityManagerService 呼叫 ActivityStarter;
ActivityManagerService.java
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
enforceNotIsolatedCaller("startActivity");
userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
userId, false, ALLOW_FULL_ONLY, "startActivity", null);
// TODO: Switch to user app stacks here.
return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, bOptions, false, userId, null, null,
"startActivityAsUser");
}
STEP 6
ActivityStarter 呼叫 ActivityStackSupervisor;
final int startActivityMayWait(IApplicationThread caller, int callingUid,
String callingPackage, Intent intent, String resolvedType,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, WaitResult outResult,
Configuration globalConfig, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
IActivityContainer iContainer, TaskRecord inTask, String reason) {
···
int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor,
resultTo, resultWho, requestCode, callingPid,
callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified, outRecord, container,
inTask, reason);
···
}
int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
TaskRecord inTask, String reason) {
···
mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
container, inTask);
···
return mLastStartActivityResult;
}
private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
TaskRecord inTask) {
···
return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,
options, inTask, outActivity);
}
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
···
try {
mService.mWindowManager.deferSurfaceLayout();
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity);
} finally {
···
}
···
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
···
if (mDoResume) {
final ActivityRecord topTaskActivity =
mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isFocusable()
|| (topTaskActivity != null && topTaskActivity.mTaskOverlay
&& mStartActivity != topTaskActivity)) {
···
} else {
···
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
mOptions);
}
} else {
···
}
···
}
STEP 7
ActivityStackSupervisor 呼叫 ActivityStack;
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (targetStack != null && isFocusedStack(targetStack)) {
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
···
return false;
}
STEP 8
ActivityStack 回呼到 ActivityStackSupervisor ;
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
···
try {
···
result = resumeTopActivityInnerLocked(prev, options);
} finally {
···
}
···
return result;
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
···
if (next.app != null && next.app.thread != null) {
···
} else {
···
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
···
}
STEP 9
ActivityStackSupervisor 回呼到 ActivityManagerService,這里會判斷要啟動 App 的行程是否存在,存在則通知行程啟動 Activity,否則就先將行程創建出來;
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
···
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);
}
STEP 10
接著我們來看看行程尚未創建的情況,我們看到這里最終呼叫的是 Process#start() 來啟動行程;
ActivityManagerService.java
final ProcessRecord startProcessLocked(String processName,
ApplicationInfo info, boolean knownToBeDead, int intentFlags,
String hostingType, ComponentName hostingName, boolean allowWhileBooting,
boolean isolated, boolean keepIfLarge) {
return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
null /* crashHandler */);
}
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
···
startProcessLocked(
app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);
···
}
private final void startProcessLocked(ProcessRecord app, String hostingType,
String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
···
if (entryPoint == null) entryPoint = "android.app.ActivityThread";
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
app.processName);
checkTime(startTime, "startProcess: asking zygote to start proc");
ProcessStartResult startResult;
if (hostingType.equals("webview_service")) {
···
} else {
startResult = Process.start(entryPoint,
app.processName, uid, uid, gids, debugFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, invokeWith, entryPointArgs);
}
···
}
STEP 11
ActivityManagerService 通過 socket 通信告知 Zygote 行程 fork 子行程,即 app 行程;
STEP 12
行程創建后將 ActivityThread 加載進去,執行 ActivityThread#main() 方法,實體化 ActivityThread,同時創建 ApplicationThread,Looper,Hander 物件,呼叫 ActivityThread#attach(false) 方法進行 Binder 通信, 接著 Looper 啟動回圈;
ActivityThread.java
public static void main(String[] args) {
···
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
···
Looper.loop();
···
}
private void attach(boolean system) {
···
if (!system) {
···
final IActivityManager mgr = ActivityManager.getService();
try {
mgr.attachApplication(mAppThread);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
···
} else {
···
}
···
}
回到 system_server 中,ActivityManagerService#attachApplication(mAppThread) 方法內部呼叫了 thread#bindApplication() 和 mStackSupervisor#attachApplicationLocked() 這兩個方法,
STEP 13
其中,thread#bindApplication() 方法呼叫了 ActivityThread#sendMessage(H.BIND_APPLICATION, data) 方法,最終走到了 ActivityThread#handleBindApplication(),進而創建 Application 物件,然后呼叫 Application#attach(context) 來系結 Context ,創建完 Application 物件后便是呼叫 mInstrumentation#callApplicationOnCreate() 執行 Application#onCreate() 生命周期;
ActivityManagerService.java
@Override
public final void attachApplication(IApplicationThread thread) {
synchronized (this) {
···
attachApplicationLocked(thread, callingPid);
···
}
}
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid) {
···
try {
···
if (app.instr != null) {
thread.bindApplication(processName, appInfo, providers,
app.instr.mClass,
profilerInfo, app.instr.mArguments,
app.instr.mWatcher,
app.instr.mUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial);
} else {
thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
null, null, null, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial);
}
···
} catch (Exception e) {
···
}
···
// 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) {
···
}
}
···
}
ActivityThread#ApplicationThread.java
public final void bindApplication(String processName, ApplicationInfo appInfo,
···
sendMessage(H.BIND_APPLICATION, data);
}
ActivityThread.java
private void sendMessage(int what, Object obj) {
sendMessage(what, obj, 0, 0, false);
}
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
···
mH.sendMessage(msg);
}
我們來看看這個 mH 的 handleMessage() 方法;
ActivityThread#H.java
public void handleMessage(Message msg) {
···
switch (msg.what) {
···
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
···
}
···
}
創建 mInstrumentation 物件,呼叫 data#info#makeApplication 來創建 Application 物件;
ActivityThread.java
private void handleBindApplication(AppBindData data) {
···
try {
// 創建 Application 實體
Application app = data.info.makeApplication(data.restrictedBackupMode, null);
mInitialApplication = app;
···
try {
mInstrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
···
}
} finally {
···
}
···
}
LoadedApk.java
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
if (mApplication != null) {
return mApplication;
}
···
Application app = null;
···
try {
···
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
···
} catch (Exception e) {
···
}
···
if (instrumentation != null) {
try {
//執行 Application#onCreate() 生命周期
instrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
···
}
}
···
return app;
}
STEP 14
mStackSupervisor#attachApplicationLocked() 方法中呼叫 app#thread#scheduleLaunchActivity() 即 ActivityThread#ApplicationThread#scheduleLaunchActivity() 方法,進而通過 ActivityThread#sendMessage(H.LAUNCH_ACTIVITY, r) 方法,最終走到了 ActivityThread#handleLaunchActivity() ,進而創建 Activity 物件,然后呼叫 activity.attach() 方法,再呼叫 mInstrumentation#callActivityOnCreate() 執行 Activity#onCreate() 生命周期;
ActivityStackSupervisor.java
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
···
for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
···
if (hr != null) {
if (hr.app == null && app.uid == hr.info.applicationInfo.uid
&& processName.equals(hr.processName)) {
try {
if (realStartActivityLocked(hr, app, true, true)) {
didSomething = true;
}
} catch (RemoteException e) {
···
}
}
}
}
}
···
}
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,
// TODO: Have this take the merged configuration instead of separate global and
// override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, !andResume,
mService.isNextTransitionForward(), profilerInfo);
···
} catch (RemoteException e) {
···
}
···
}
ActivityThread#ApplicationThread.java
@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) {
···
sendMessage(H.LAUNCH_ACTIVITY, r);
}
ActivityThread.java
private void sendMessage(int what, Object obj) {
sendMessage(what, obj, 0, 0, false);
}
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
···
mH.sendMessage(msg);
}
我們同樣來看看這個 mH 的 handleMessage() 方法;
ActivityThread#H.java
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case LAUNCH_ACTIVITY: {
···
handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
···
} break;
···
}
···
}
ActivityThread.java
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
···
Activity a = performLaunchActivity(r, customIntent);
···
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
···
Activity activity = null;
try {
//創建 Activity 物件
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
···
} catch (Exception e) {
···
}
try {
···
if (activity != null) {
···
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback);
···
//執行 Activity#onCreate() 生命周期
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
···
}
···
} catch (SuperNotCalledException e) {
···
} catch (Exception e) {
···
}
到這里,整個 app 啟動流程以及原始碼呼叫皆已分析完畢,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/304291.html
標籤:其他
上一篇:如何學習作業系統這門課程?
下一篇:linux網路配置
