基于Android-28 的源码 Activity 启动流程分析详解手机开发

之前介绍了Android IPC通信机制 Binder,接下来开始梳理Activity启动流程。

常见的Activity的启动有两种方式:
  1. 通过LaunchActivity启动一个应用,启动Activity。
  2. 通过同一个进程内的startActivity。

以下是基于Android 28的源码进行分析,顺便说一个AS很好用的快捷键:ctrl+shift+N 搜索打开文件

在接下来的流程中重要的几个类:
  1. Instrumentation:每个应用程序都有一个Instrumentation,每个Actviity持有它的引用,ActivityThread要创建或暂停Activity时,都是通过Instrumentation进行操作。

  2. ActivityManagerService:SystemServer中启动的独立进程,负责管理四大组件,可以利用binder跟它通信

  3. ActivityStarter:负责处理intenth和flags、选择启动的task、复用Activity等逻辑。

  4. ActivityRecord:每个Activity在AMS中对应一个ActivityRecod,记录Acitivty的信息

  5. TaskRecord:就是我们所讲的任务栈,先进后出,存储ActivityRecord

  6. ActivityStack:用来管理TaskRecord,ActivityStack是由ActivityStackSupervisor创建的

  7. ActivityStackSupervisor:AMS通过ActivityStackSupervisor负责操作ActivityStack

  8. ApplicationThread:ActivityThread的内部类,是一个binder对象,是ActivityManagerService向ActivityThread通信的桥梁。

  9. ActivityThread:表示APP的主线程,有main函数,

  10. ClientLifecycleManager:调用ClientTransaction,让AMS切换到APP进程执行生命周期

从进程的角度分析,可以把Activity的启动流程分成三个阶段:
  1. LauncherActivity或原活动的Activity进程

  2. AMS进程,真正启动Activity

  3. .从AMS到ApplicationThread所在的目标Activity进程,可能跟原活动的Activity进程同一个或者不同进程

在这里插入图片描述

1. LauncherActivity或原活动的Activity进程

一般我们从Activity的startActivity()或者Context的startActivity(),之所以把他们分开看,是在Android 28有一些不一样,但最后的走向是一样的。

先看下Context.startActivity(),其中Context的实现是在ContextImpl;

// ContextImpl 
public void startActivity(Intent intent) {
    
    warnIfCallingFromSystemProcess(); 
    startActivity(intent, null); 
} 
 
public void startActivity(Intent intent, Bundle options) {
    
	... 
	mMainThread.getInstrumentation().execStartActivity( 
                getOuterContext(), mMainThread.getApplicationThread(), null, 
                (Activity) null, intent, -1, options); 
} 

其中mMainThread是ActivityThread,最后转化到Instrumentation.execStartActivity()来启动Activity。

再看一下Activity的startActivity(),其实都是走到了startActivityForResult(),其中requestCode是-1;

// Activity 
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, 
            @Nullable Bundle options) {
    
	if (mParent == null) {
   // mParent代表ActivityGroup,已经被废弃 
		 Instrumentation.ActivityResult ar = 
                mInstrumentation.execStartActivity( 
                    this, mMainThread.getApplicationThread(), mToken, this, 
                    intent, requestCode, options); 
		 ... 
	}  
	... 
} 

可见最后还是通过Instrumentation的execStartActivity()启动Activity。

mMainThread是ActivityThread,mMainThread.getApplicationThread()是ActivityThread的内部类ApplicationThread,他是一个IBinder。主要用于ActivityThread与AMS的通信。

// Instrumentation 
public ActivityResult execStartActivity( 
       Context who, IBinder contextThread, IBinder token, Activity target, 
       Intent intent, int requestCode, Bundle options) {
    
    ... 
	int result = ActivityManager.getService() 
                .startActivity(whoThread, who.getBasePackageName(), intent, 
                        intent.resolveTypeIfNeeded(who.getContentResolver()), 
                        token, target != null ? target.mEmbeddedID : null, 
                        requestCode, 0, null, options); 
	... 
} 
 
// ActivityManager 
public static IActivityManager getService() {
    
    return IActivityManagerSingleton.get(); 
} 
 
// ActivityManager 
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; 
            } 
        }; 

ActivityManager.getService() 获取得到的是IActivityManager的接口,这里涉及到ActivityManagerService(AMS),AMS运行在另外一个进程,继承了IBinder,是一个binder通信的Server端,而IActivityManagerSingleton实现了AMS Binder的client端,这样通过IActivityManagerSingleton就可以跟AMS通信。

2. AMS进程,真正启动Activity

最后ActivityManager.getService().startActivity()通过binder会走到AMS.startActivity();

// AMS 
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()); 
} 
 
// AMS 
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, 
     boolean validateIncomingUser) {
    
     // userId是调用者,检查权限 
     userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser, 
            Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser"); 
                 
	 return mActivityStartController.obtainStarter(intent, "startActivityAsUser") 
                .setCaller(caller) 
                .setCallingPackage(callingPackage) 
                .setResolvedType(resolvedType) 
                .setResultTo(resultTo) 
                .setResultWho(resultWho) 
                .setRequestCode(requestCode) 
                .setStartFlags(startFlags) 
                .setProfilerInfo(profilerInfo) 
                .setActivityOptions(bOptions) 
                .setMayWait(userId) 
                .execute(); 
} 

mActivityStartController.obtainStarter()获取得到的是ActivityStarter;

ActivityStarter主要负责处理intenth和flags、选择启动的task、复用Activity等逻辑。

// ActivityStarter 
 int execute() {
    
    try {
    
        if (mRequest.mayWait) {
    
            return startActivityMayWait(mRequest.caller, mRequest.callingUid, 
                    mRequest.callingPackage, mRequest.intent, mRequest.resolvedType, 
                    mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo, 
                    mRequest.resultWho, mRequest.requestCode, mRequest.startFlags, 
                    mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig, 
                    mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId, 
                    mRequest.inTask, mRequest.reason, 
                    mRequest.allowPendingRemoteAnimationRegistryLookup); 
        } else {
    
            return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent, 
                    mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo, 
                    mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo, 
                    mRequest.resultWho, mRequest.requestCode, mRequest.callingPid, 
                    mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid, 
                    mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions, 
                    mRequest.ignoreTargetSecurity, mRequest.componentSpecified, 
                    mRequest.outActivity, mRequest.inTask, mRequest.reason, 
                    mRequest.allowPendingRemoteAnimationRegistryLookup); 
        } 
    } finally {
    
        onExecutionComplete(); 
    } 
} 

上面调用了setMayWait(),所以mRequest.mayWait为true,执行startActivityMayWait()。
ActivityStarter.startActivityMayWait() 的参数mRequest.inTask是一个ActivityRecord,默认是null。

private 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, SafeActivityOptions options, boolean ignoreTargetSecurity, 
int userId, TaskRecord inTask, String reason, 
boolean allowPendingRemoteAnimationRegistryLookup) {
 
... 
int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo, 
voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid, 
callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options, 
ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason, 
allowPendingRemoteAnimationRegistryLookup); 
... 
} 
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, 
SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified, 
ActivityRecord[] outActivity, TaskRecord inTask, String reason, 
boolean allowPendingRemoteAnimationRegistryLookup) {
  
... 
mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType, 
aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode, 
callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, 
options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord, 
inTask, allowPendingRemoteAnimationRegistryLookup); 
} 
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, 
SafeActivityOptions options, 
boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity, 
TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {
 
// 构造当前的Actiivty的ActivityRecord 
ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid, 
callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(), 
resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null, 
mSupervisor, checkedOptions, sourceRecord); 
return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, 
true /* doResume */, checkedOptions, inTask, outActivity); 
} 
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord, 
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, 
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask, 
ActivityRecord[] outActivity) {
 
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, 
startFlags, doResume, options, inTask, outActivity); 
.... 
return result; 
} 

ActivityStarter 构造了ActivityRecord,选择ActivityStack等等

兜兜转转最终是会走到ActivityStarter.startActivityUnchecked()

startActivityUnchecked()做了很多工作,决定任务栈,根据启动模式,是否调用deliverNewIntent,复用Activity等等。

这里面涉及到三个概念 ActivityRecord、TaskRecord、ActivityStack

一个ActivityRecord对应一个Activity,保存了一个Activity的所有信息;
一个Activity可能会有多个ActivityRecord,因为Activity可以被多次启动,这个主要取决于其启动模式。
一个TaskRecord由一个或者多个ActivityRecord组成,就是任务栈,具有后进先出的特点。
ActivityStack则是用来管理TaskRecord的,包含了多个TaskRecord。
同一个TaskRecord的Activity可以分别处于不同的进程中,每个Activity所处的进程跟所处的Task没有关系

图片
参考:《ActivityRecord、TaskRecord、ActivityStack以及Activity启动模式详解》

// ActivityStarter 
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord, 
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, 
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask, 
ActivityRecord[] outActivity) {
 
... 
// 选择或者创建TaskRecord 
if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask 
&& (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
 
newTask = true; 
// 创建新的TaskRecord 
result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack); 
} else if (mSourceRecord != null) {
 
result = setTaskFromSourceRecord(); 
} else if (mInTask != null) {
 
result = setTaskFromInTask(); 
} else {
 
// 创建新的TaskRecord 
setTaskToCurrentTopOrCreateNewTask(); 
} 
// mStartActivity = r;mStartActivity表示准备启动的Activity 
if (mDoResume) {
 
final ActivityRecord topTaskActivity = 
mStartActivity.getTask().topRunningActivityLocked(); 
if (!mTargetStack.isFocusable() 
|| (topTaskActivity != null && topTaskActivity.mTaskOverlay 
&& mStartActivity != topTaskActivity)) {
 
mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS); 
mService.mWindowManager.executeAppTransition(); 
} else {
 
if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
 
//将目标栈移到前台 
mTargetStack.moveToFront("startActivityUnchecked"); 
} 
//mSupervisor 准备mStartAcitivity到栈顶, 
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity, mOptions); 
} 
} 
... 
} 

这里mLaunchFlags & FLAG_ACTIVITY_NEW_TASK 是true,会走setTaskFromReuseOrCreateNewTask()创建一个新的TaskRecord。

并且mTargetStack.moveToFront()将启动的Activity的栈移动到前台。

ActivityStarter构建了Activity的ActivityRecord和TaskRecord,做完了前期的准备工作了,下面就开始了对栈顶的Activity的停止和启动新的Activity。

mSupervisor是ActivityStackSupervisor,它负责管理ActivityStack。

// ActivityStackSupervisor 
boolean resumeFocusedStackTopActivityLocked() {
 
return resumeFocusedStackTopActivityLocked(null, null, null); 
} 
// ActivityStackSupervisor 
boolean resumeFocusedStackTopActivityLocked( 
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
 
if (!readyToResume()) {
 
return false; 
} 
// 如果目标targetStack在前台 
if (targetStack != null && isFocusedStack(targetStack)) {
 
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions); 
} 
... 
return false; 
} 

在ActivityStarter已经把目标栈移动到前台,所以会到ActivityStack的resumeTopActivityUncheckedLocked()

// ActivityStack 
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
 
mStackSupervisor.inResumeTopActivity = true; 
result = resumeTopActivityInnerLocked(prev, options); 
... 
} 

在这里有段注释,当我们启动一个Activtity的同时,可能需要暂停 top 活动的Activity。只有当前一个Activity进行Pause后,后面一个Activity才能进行resume。

resumeTopActivityInnerLocked有资料说会调用两次,第一次会暂停原来活动的Activity,第二次启动新的Activity?这部分还是有点云里雾里的。

// ActivityStack 
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
 
final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */); 
if (mResumedActivity != null) {
 
// 暂停之前的Activity 
pausing |= startPausingLocked(userLeaving, false, next, false); 
} 
if (next.app != null && next.app.thread != null) {
 
// activtiy存在,resume 
mStackSupervisor.scheduleResumeTopActivities(); 
} else {
 
//创建进程,冷启动Activity。或者已启动App,重新启动Activity 
StackSupervisor.startSpecificActivityLocked(next, true, false); 
} 
} 

resumeTopActivityInnerLocked这个方法好复杂,但是主要负责暂停之前活动的Activity和把要启动的Activity添加到栈顶。

这里有两个重要的方法:startPausingLocked() 停止原Activity、startSpecificActivityLocked()启动新Activity

// ActivityStack 
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, 
ActivityRecord resuming, boolean pauseImmediately) {
 
// mService是AMS,prev_app.thread是ApplicationThread 
mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken, 
PauseActivityItem.obtain(prev.finishing, userLeaving, 
prev.configChangeFlags, pauseImmediately)); 
} 

这里mService是AMS,因为ActivityStack已经在mService同一个进程,不需要binder跨进程通信。

mService.getLifecycleManager()获取到是ClientLifecycleManager,这个类负责执行ActivityLifecycleItem,就是生命周期的任务,如PauseActivityItem、ResumeActivtyItem,每次执行最后会跟ActivityThread交互。

往下看就会知道了。


3. 从AMS进程到目标Activity进程,

以下分析ClientLifecycleManager怎么走到ActivityThread,并切换到主线程,因为后续还是会使用到这个机制。

// ClientLifecycleManager 
void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken, 
ActivityLifecycleItem stateRequest) throws RemoteException {
 
final ClientTransaction clientTransaction = transactionWithState(client, activityToken, 
stateRequest); 
scheduleTransaction(clientTransaction); 
} 
// ClientLifecycleManager 
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
 
final IApplicationThread client = transaction.getClient(); 
transaction.schedule(); 
if (!(client instanceof Binder)) {
 // 如果是远程调用,因为若是同进程client会是Binder实体 
transaction.recycle(); 
} 
} 
//ClientTransaction 
public void schedule() throws RemoteException {
 
// mClient是IApplicationThread 
mClient.scheduleTransaction(this); 
} 

ActivityLifecycleItem会被包装在ClientTransaction里面,如如PauseActivityItem、ResumeActivtyItem。

这里走到了IApplicationThread,而IApplicationThread的实体是ActivityThread内部类ApplicationThread,它是一个binder对象,IApplicationThread是它远程接口。

// ActivityThread.ApplicationThread 
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
 
ActivityThread.this.scheduleTransaction(transaction); 
} 

可见,这里已经到达ActivityThread,但是并不在主线程。没错,接下来就是用Handler切换线程的时候。

但是在这里你搜不到ActivityThread的scheduleTransaction(),原因是在ActivityThread继承了ClientTransactionHandler,ClientTransactionHandler实现了schedueleTransaction()

// ClientTransactionHandler 
void scheduleTransaction(ClientTransaction transaction) {
 
transaction.preExecute(this); 
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); 
} 
abstract void sendMessage(int what, Object obj); 

噗呲,一口老血吐出来,怎么来回转。。。

再看下ActivityThread怎么实现sendMessage()

// ActivityThread 
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
 
Message msg = Message.obtain(); 
msg.what = what; 
msg.obj = obj; 
msg.arg1 = arg1; 
msg.arg2 = arg2; 
if (async) {
 
msg.setAsynchronous(true); 
} 
// mH是H,是Handler 
mH.sendMessage(msg); 
} 

ActivityThread的sendMessage都走到这里来,这里很熟悉了,把trascation封装到Message,而且设置为异步消息(这里涉及到MessageQueue的同步p屏障问题),最后Handler H发送消息EXECUTE_TRANSACTION。

看Handler H怎么处理EXECUTE_TRANSACTION

//ActivityThread H 
public void handleMessage(Message msg) {
 
case EXECUTE_TRANSACTION: 
final ClientTransaction transaction = (ClientTransaction) msg.obj; 
mTransactionExecutor.execute(transaction); 
break; 
} 
// TransactionExecutor 
public void execute(ClientTransaction transaction) {
 
final IBinder token = transaction.getActivityToken(); 
executeCallbacks(transaction); 
executeLifecycleState(transaction); 
mPendingActions.clear(); 
} 

上面说了ActivityLifecycleItem会被包装在ClientTransaction里面,executeCallbacks会解析出来ActivityLifecycleItem,依次执行内部的ActivityLifecycleItem.execute()。

executeLifecycleState()也是会执行ActivityLifecycleItem.execute(),这里只看executeLifecycleState().

// TransactionExecutor 
private void executeLifecycleState(ClientTransaction transaction) {
 
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); 
if (lifecycleItem == null) {
 
return; 
} 
final IBinder token = transaction.getActivityToken(); 
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token); 
if (r == null) {
 
return; 
} 
// Cycle to the state right before the final requested state. 
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */); 
// Execute the final transition with proper parameters. 
lifecycleItem.execute(mTransactionHandler, token, mPendingActions); 
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions); 
} 

这里LifecycleItem会走execute(),postExecute()等方法,也就是走PauseActivtyItem或者ResumeActivitItem的execute()。

至此,这一段讲了LifecycleItem通过ClientLifecycleManager怎么走到ActivityThread,并切换到主线程执行execute()。


接下来继续讲 ActivityStack.startPausingLocked()怎么pause,

//ActivityStack.startPausingLocked() 
mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken, 
PauseActivityItem.obtain(prev.finishing, userLeaving, 
prev.configChangeFlags, pauseImmediately)); 

我们看到PauseActivityItem被封装到transaction到达handler H。最后在主线程执行了PauseActivityItem().execute()

//PauseActivityItem 
public void execute(ClientTransactionHandler client, IBinder token, 
PendingTransactionActions pendingActions) {
 
// client就是ActivityThread 
client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions, 
"PAUSE_ACTIVITY_ITEM"); 
} 

最后走到了ActivityThread.handlePauseActivity(),这里不继续分析怎么走到onPause()。

至此,只是分析了startPausingLocked() 还有 startSpecificActivityLocked()

// ActivityStackSupervisor 
// andResume 为 true 
void startSpecificActivityLocked(ActivityRecord r, 
boolean andResume, boolean checkConfig) {
 
if (app != null && app.thread != null) {
 // app进程存在 
realStartActivityLocked(r, app, andResume, checkConfig); 
return; 
} 
// app不存在, 
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0, 
"activity", r.intent.getComponent(), false, false, true); 
} 

这里分成两部分,一个是app进程存在走到realeStartActivityLocked(),另一个是app进程不存在,AMS.startProcessLocked(),Zygote进程fork子进程,启动进程执行ActivityThread的main方法。


先看进程存在的情况

// ActivityStackSupervisor 
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, 
boolean andResume, boolean checkConfig) throws RemoteException {
 
... 
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread, 
r.appToken); 
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent), 
System.identityHashCode(r), r.info, 
mergedConfiguration.getGlobalConfiguration(), 
mergedConfiguration.getOverrideConfiguration(), r.compat, 
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle, 
r.persistentState, results, newIntents, mService.isNextTransitionForward(), 
profilerInfo)); 
final ActivityLifecycleItem lifecycleItem; 
if (andResume) {
 // andResume 为 true 
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward()); 
} else {
 
... 
} 
clientTransaction.setLifecycleStateRequest(lifecycleItem); 
mService.getLifecycleManager().scheduleTransaction(clientTransaction); 
} 

首先看clientTransaction.addCallback(LaunchActivityItem.obtain()),跟着上面的代码最后会先执行LaunchActivityItem.execute(),最后走到了ActivtiyThread主线程执行LaunchActivityItem的execute()

public void execute(ClientTransactionHandler client, IBinder token, 
PendingTransactionActions pendingActions) {
 
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo, 
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState, 
mPendingResults, mPendingNewIntents, mIsForward, 
mProfilerInfo, client); 
// client是ActivityThread 
client.handleLaunchActivity(r, pendingActions, null /* customIntent */); 
} 

最后在主线程ActivityThread.handleLaunchActivity()启动Actiivty,后续的流程不继续分析,简要画了个流程图:

在这里插入图片描述

再看这里的ResumeActivityItem运行机制跟上面的LaunchActivityItem一致,最后走到了ActivtiyThread主线程执行ResumeActivityItem的execute()。

//ResumeActivityItem 
public void execute(ClientTransactionHandler client, IBinder token, 
PendingTransactionActions pendingActions) {
 
// client是ActivityThread 
client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward, 
"RESUME_ACTIVITY"); 
} 

可见最后在ActivtiyThread主线程执行handleResumeActivity()。


现在讨论第二种情况,app进程不存在的情况:

AMS.startProcessLocked(),Zygote进程fork子进程,启动进程执行ActivityThread的main方法。

这里的知识点太多了,包括进程启动,ActivityThread的main()函数执行,looper启动等,不做分析。
在main()函数里面,会走

// ActivityThread 
public static void main(String[] args) {
 
Looper.prepareMainLooper(); 
ActivityThread thread = new ActivityThread(); 
thread.attach(false, startSeq); 
Looper.loop(); 
} 

ActivityThread.attach()做了非常多的初始化动作,包括创建application、ContextImpl,这里展开也是一个主题。(有机会要好好研究)

流程图

在这里插入图片描述

流程总结

(待补上)

参考

《Android 开发艺术探索》
云图网
云图网
云图网
云图网
云图网

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/6295.html

(0)
上一篇 2021年7月17日
下一篇 2021年7月17日

相关推荐

发表回复

登录后才能评论