Activity启动过程源码分析(Android 8.0)
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启动过程全解析