Activity啟動過程源碼分析
本文來Activity的啟動流程,一般我們都是通過startActivity或startActivityForResult來啟動目標activity,那么我們就由此出發探究系統是如何實現目標activity的啟動的。
startActivity(new Intent(context, MainActivity.class));
startActivityForResult(new Intent(context, SecondActivity.class),1000);
一般我們都是通過上面兩個函數來啟動目標activity,我們來看下startActivity的源碼
Activity:
@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);
}
}
我們可以看到startActivity其實也是調用startActivityForResult來啟動目標activity只不過此時requestcode為-1.
Activity:
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
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);//1調用Instrumentation.execStartActivity
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());//2發送請求結果
}
if (requestCode >= 0) {
// If this start is requesting a result, we can avoid making
// the activity visible until the result is received. Setting
// this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
// activity hidden during this time, to avoid flickering.
// This can only be done when a result is requested because
// that guarantees we will get information back when the
// activity is finished, no matter what happens to it.
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
// TODO Consider clearing/flushing other event sources and events for child windows.
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
在startActivityForResult中會先在注釋1處調用Instrumentation.execStartActivity來獲取一個ActivityResult實例,ActivityResult是用來描述目標activity執行結果的。由此我們可知activity的啟動肯定跟Instrumentation.execStartActivity有關。在注釋2處會調用ActivityThread.sendActivityResult來把啟動結果發送出去,其最終是通過handler發送一個SEND_RESULT message,這里就不展開詳述了有興趣的自行研究。
這里解釋幾個類概念:
ActivityThread:它App的真正入口,當App啟動后,會調用其main方法開始執行,開啟消息循環隊列。是傳說中的UI線程,即主線程。與ActivityManagerService配合,一起完成Activity的管理工作;
Instrumentation:每一個應用程序都只有一個Instrumentation對象,每個Activity內都有一個對該對象的引用。Instrumentation可以理解為應用進程的管家,ActivityThread要創建或者打開某個Activity時,都需要通過Instrumentation來進行具體的操作
下面看下Instrumentation.execStartActivity
Instrumentation:
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, String resultWho,
Intent intent, int requestCode, Bundle options, UserHandle user) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
//...
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
//1 調用AMS的startActivity
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, resultWho,
requestCode, 0, null, options, user.getIdentifier());
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
注釋1處首先調用了ActivityManager的getService()。
ActivityManager
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;
}
};
getService()在內部調用了IActivityManagerSingleton.get(),在get()中先通過ServiceManager.getService獲取一個AMS的binder,然后調用IActivityManager.Stub.asInterface。這些操作的作用就是使用AIDL進行IPC(進程間通信)與AMS進行通信。(注意7.0及以前版本IPC的流程是:(客戶端)ActivityManagerProxy -> Binder驅動 -> (服務端)ActivityManagerService,而8.0之后變為通過aidl進行IPC)
通過ActivityManager.getService()就可以拿到AMS的代理,然后調用了AMS的startActivity
ActivityManagerService
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());
}
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, "startActivityAsUser");
}
startActivity調用了startActivityAsUser,startActivityAsUser又調用了ActivityStarter.startActivityMayWait,這里解釋下ActivityStarter的作用。
ActivityStarter:啟動Activity的控制器,主要用於用來將Intent和flags轉換成activity和相關任務棧;
ActivityStarter:
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,
TaskRecord inTask, String reason) {
//...
//1
int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor,
resultTo, resultWho, requestCode, callingPid,
callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified, outRecord, 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, 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,
inTask);
//...
}
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, TaskRecord inTask) {
//...
doPendingActivityLaunchesLocked(false);
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) {
//...
//1
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity);
//...
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
//...
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
mOptions);
//...
}
在注釋1處調用startActivityLocked然后經過一系列的調用(startActivityMayWait---> startActivityLocked—->startActivity —->startActivity —> startActivityUnchecked—-> ActivityStackSupervisor.resumeFocusedStackTopActivityLocked)最終走到ActivityStackSupervisor.resumeFocusedStackTopActivityLocked
ActivityStackSupervisor:主要管理着mHomeStack和mFocusedStack兩個ActivityStack等相關信息;
ActivityStackSupervisor:
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (!readyToResume()) {
return false;
}
if (targetStack != null && isFocusedStack(targetStack)) {
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
if (r == null || r.state != RESUMED) {
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
} else if (r.state == RESUMED) {
// Kick off any lingering app transitions form the MoveTaskToFront operation.
mFocusedStack.executeAppTransition(targetOptions);
}
return false;
}
resumeFocusedStackTopActivityLocked內部又調用了ActivityStack.resumeTopActivityUncheckedLocked
ActivityStack:Activity在AMS的棧管理,用來記錄已經啟動的Activity的先后關系、狀態信息等。通過ActivityStack決定是否需要啟動新的進程
ActivityStack:
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
//...
result = resumeTopActivityInnerLocked(prev, options);
//...
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
//...
if (mResumedActivity != null) {
//同步等待pause當前Activity的結果
pausing |= startPausingLocked(userLeaving, false, next, false);
}
//...
}
由此我們知道啟動新的activity,需要先把當前activity pause。
ActivityStack:
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, ActivityRecord resuming, boolean pauseImmediately) {
//....
//去當前Activity所在應用進程暫停當前activity。
prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
userLeaving, prev.configChangeFlags, pauseImmediately);
//....
}
此處的prev.app.thread實際是ApplicationThread
它的作用是完成AMS與ActivityThread之間的通信,ApplicationThread本身是ActivityThread的一個內部類。
ActivityThread$ApplicationThread:
public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport) {
int seq = getLifecycleSeq();
if (DEBUG_ORDER) Slog.d(TAG, "pauseActivity " + ActivityThread.this
+ " operation received seq: " + seq);
sendMessage(
finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
token,
(userLeaving ? USER_LEAVING : 0) | (dontReport ? DONT_REPORT : 0),
configChanges,
seq);
}
內部發送了一條message,消息的發送和處理是在H類中,H是handler的子類且它是ActivityThread的一個內部類。
ActivityThread$H:
public void handleMessage(Message msg) {
//...
switch (msg.what) {
case PAUSE_ACTIVITY:
{
SomeArgs args = (SomeArgs) msg.obj;
handlePauseActivity((IBinder) args.arg1, false, (args.argi1 & USER_LEAVING) != 0,
args.argi2, (args.argi1 & DONT_REPORT) != 0, args.argi3);
}
break;
}
//...
}
在H中調用了handlePauseActivity方法。
ActivityThread:
private void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport, int seq) {
//...
performPauseActivity(token, finished, r.isPreHoneycomb(), "handlePauseActivity");//執行pause
// Make sure any pending writes are now committed.
if (r.isPreHoneycomb()) {
QueuedWork.waitToFinish();
}
// Tell the activity manager we have paused.
if (!dontReport) {
try {
ActivityManager.getService().activityPaused(token);//執行完后通知AMS當前Activity已經pause
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
}
final Bundle performPauseActivity(IBinder token, boolean finished,
boolean saveState, String reason) {
ActivityClientRecord r = mActivities.get(token);
return r != null ? performPauseActivity(r, finished, saveState, reason) : null;
}
final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
boolean saveState, String reason) {
//...
// Next have the activity save its current state and managed dialogs...
if (!r.activity.mFinished && saveState) {
callCallActivityOnSaveInstanceState(r);
}
performPauseActivityIfNeeded(r, reason);//執行pause
//...
}
private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
//...
mInstrumentation.callActivityOnPause(r.activity);
//...
}
handlePauseActivity內部會先去執行pause操作,執行完畢后會通知AMS。pause的執行經過一系列的調用最終調用了Instrumentation.callActivityOnPause
Instrumentation:
public void callActivityOnPause(Activity activity) {
activity.performPause();
}
final void performPause() {
mDoReportFullyDrawn = false;
mFragments.dispatchPause();
mCalled = false;
onPause();//調用activity的生命周期函數onPause()
mResumed = false;
if (!mCalled && getApplicationInfo().targetSdkVersion
>= android.os.Build.VERSION_CODES.GINGERBREAD) {
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onPause()");
}
mResumed = false;
}
至此當前activity處於onPause狀態。
在handlePauseActivity方法中pause操作后通知了AMS ,調用ActivityManager.getService().activityPaused
ActivityManagerService:
public final void activityPaused(IBinder token) {
final long origId = Binder.clearCallingIdentity();
synchronized(this) {
ActivityStack stack = ActivityRecord.getStackLocked(token);
if (stack != null) {
stack.activityPausedLocked(token, false);//1
}
}
Binder.restoreCallingIdentity(origId);
}
在注釋1處調用了ActivityStack得activityPausedLocked
ActivityStack:
final void activityPausedLocked(IBinder token, boolean timeout) {
if (DEBUG_PAUSE) Slog.v(TAG_PAUSE,
"Activity paused: token=" + token + ", timeout=" + timeout);
final ActivityRecord r = isInStackLocked(token);
if (r != null) {
mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
if (mPausingActivity == r) {
if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSED: " + r
+ (timeout ? " (due to timeout)" : " (pause complete)"));
mService.mWindowManager.deferSurfaceLayout();
try {
completePauseLocked(true /* resumeNext */, null /* resumingActivity */);//1 pause完成
} finally {
mService.mWindowManager.continueSurfaceLayout();
}
return;
}
//...
}
private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
//...
mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
//...
}
調用StackSupervisor.resumeFocusedStackTopActivityLocked
StackSupervisor:
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (!readyToResume()) {
return false;
}
/如果啟動Activity和要啟動的Activity在同一個ActivityStack中,調用targetStack對象的方法
if (targetStack != null && isFocusedStack(targetStack)) {
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
//如果不在同一個ActivityStack中,則調用mFocusStack對象的方法
if (r == null || r.state != RESUMED) {
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
} else if (r.state == RESUMED) {
// Kick off any lingering app transitions form the MoveTaskToFront operation.
mFocusedStack.executeAppTransition(targetOptions);
}
return false;
}
ActivityStack:
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
//...
result = resumeTopActivityInnerLocked(prev, options);
//...
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
//...
if (mResumedActivity != null) {
//又回到此處 但是因為之前pause時已經將mResumedActivity置null,所以不會再次調用startPausingLocked
pausing |= startPausingLocked(userLeaving, false, next, false);
}
//...
//啟動目標activity
mStackSupervisor.startSpecificActivityLocked(next, true, true);
//...
}
第二次來到resumeTopActivityUncheckedLocked函數,與上次不同的是這次已經完成了pause操作,所以會走到下面StackSupervisor.startSpecificActivityLocked處來啟動目標activity。
StackSupervisor:
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
//...
realStartActivityLocked(r, app, andResume, checkConfig);
//...
}
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
//...
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);
//...
}
可以看到最后走到了ActivityThread.scheduleLaunchActivity
ActivityThread:
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);
}
又回到了H類,我們直接看下H的handleMessage方法
ActivityThread$H:
public void handleMessage(Message msg) {
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;
}
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
//...
Activity a = performLaunchActivity(r, customIntent);
//...
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
//...
ContextImpl appContext = createBaseContextForActivity(r);//1 創建activity的BaseContext
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);//2 創建activity
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
}
//...
Application app = r.packageInfo.makeApplication(false, mInstrumentation);//3 創建Application
//...
appContext.setOuterContext(activity);
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);//4 調用attach
//...
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);//5 調用生命周期函數OnCreate
//...
}
H收到消息后調用了handleLaunchActivity方法,該方法還是比較重要的我們分析下有用的信息。
首先在注釋1處創建了activity的BaseContext,具體細節參考Contex知識詳解
在注釋2處則通過Instrumentation構造了activity實例,具體來說就是通過ClassLoader去的newInstance來創建的。
注釋3處則獲取了當前應用的Application,需要注意的是如果當前應用尚未創建Application那么此操作會創建Application並返回,如果已經創建則會返回已創建的Application。
注釋4處調用了attach
注釋5則是用來回調生命周期函數OnCreate,具體過程如下:
Instrumentation:
public void callActivityOnCreate(Activity activity, Bundle icicle,
PersistableBundle persistentState) {
prePerformCreate(activity);
activity.performCreate(icicle, persistentState);//1
postPerformCreate(activity);
}
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
mCanEnterPictureInPicture = true;
restoreHasCurrentPermissionRequest(icicle);
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);//回調onCreate
}
mActivityTransitionState.readState(icicle);
mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowNoDisplay, false);
mFragments.dispatchActivityCreated();
mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
}
至此目標activity就啟動完成了,我們可以在onCreate中做相應的初始化操作。
縱觀整個流程可以看出,啟動過程經過多次調用涉及到了不少類並且整個流程也甚是復雜繁瑣,所以我們有必要在分析完流程后總結一下,這可以幫我們從宏觀上對整體流程認識更加深刻。
首先我們來回顧下整個流程涉及的類以及其作用:
-
Instrumentation:每一個應用程序只有一個Instrumentation對象,每個Activity內都有一個對該對象的引用。Instrumentation可以理解為應用進程的管家,ActivityThread要創建或暫停某個Activity時,都需要通過Instrumentation來進行具體的操作。
-
ActivityManagerService: Android中最核心的服務之一,主要負責系統中四大組件的啟動、切換、調度及應用程序的管理和調度等工作
-
ActivityManager:該類提供與Activity、Service和Process相關的信息以及交互方法, 可以被看作是ActivityManagerService的輔助類
-
ActivityThread:App的真正入口,當App啟動后,會調用其main方法開始執行,開啟消息循環隊列。是傳說中的UI線程,即主線程。與ActivityManagerService配合,一起完成Activity的管理工作;
-
ApplicationThread:用來實現ActivityManagerService與ActivityThread之間的交互。在ActivityManagerService需要管理相關Application中的Activity的生命周期,通過ApplicationThread的代理對象與ActivityThread通訊;
-
ActvitityStack:Activity在AMS的棧管理,用來記錄已經啟動的Activity的先后關系、狀態信息等。通過ActivityStack決定是否需要啟動新的進程;
-
ActivityRecord:ActivityStatck的管理對象,每個Activity在AMS對應的一個ActivityRecord,來記錄Activity的狀態以及其他信息。可以理解為Activity在服務端的Activity對象的映射;
-
TaskRecord:AMS抽象出來的任務棧的概念。一個TaskRecord包含若干個ActivityRecord。ASM用它來確保Activity啟動和退出順序。它與Activity的啟動模式直接相關。
-
ActivityStarter:啟動Activity的控制器,主要用於用來將Intent和flags轉換成activity和相關任務棧;
-
ActivityStackSupervisor:負責所有Activity棧的管理。內部管理了mHomeStack、mFocusedStack和mLastFocusedStack三個Activity棧。其中,mHomeStack管理的是Launcher相關的Activity棧;mFocusedStack管理的是當前顯示在前台Activity的Activity棧;mLastFocusedStack管理的是上一次顯示在前台Activity的Activity棧。
對於以上類我們要熟悉其作用。
接下來就是啟動流程的總結了:(此處以 A啟動B為例)
1、Activity A通過startActivity等函數啟動B
2、步驟1調用之后當前應用會向AMS發送一個啟動Activity B的進程間通信請求;
3、AMS會將要啟動的Activity B的組件信息保存下來,ActivityManagerService接收到啟動請求后會進行必要的初始化以及狀態的刷新,然后解析Activity的啟動模式,為啟動Activity做一系列的准備工作。
4、然后判斷棧頂是否為空,如果不為空即當前有Activity A顯示在前台,則會先進行棧頂Activity的onPause流程,此過程是通過Binder通信(ApplicationThread及其接口定義語言)完成
5、Activity A完成pause操作后,通過Binder通信(ActivityManagerService及其接口定義語言)通知AMS,可以執行啟動Activity B的操作了(要啟動的activity信息保存在了棧頂)(此處需要注意的是如果Activity被啟動過則直接執行onRestart->onStart->onResume過程直接啟動Activity(熱啟動過程)。否則執行Activity所在應用的冷啟動過程。冷啟動的過程是通過Zygote進程fork出一個新的進程然后執行ActivityThread的main方法啟動新進程)
6、上述步驟完成后AMS執行一系列啟動Activity B的操作,並通過Binder通信(ApplicationThread及其接口定義語言)進行跨進程調用,將Activity B啟動起來;
參考:
Android Activity啟動流程(基於Android8.0系統)
Activity啟動流程源碼分析
Activity啟動流程簡直喪心病狂!
Activity啟動過程全解析