赞
踩
参考文献:
startActivity启动过程分析
Activity启动流程(Android 12)
Activity启动发起后,是通过Binder最终交由system进程中的AMS来完成。
frameworks/base/core/java/android/app/Activity.java frameworks/base/core/java/android/app/Instrumentation.java frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java frameworks/base/services/core/java/com/android/server/wm/Task.java frameworks/base/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java frameworks/base/services/core/java/com/android/server/wm/ClientLifecycleManager.java frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java frameworks/base/core/java/android/app/ActivityThread.java frameworks/base/core/java/android/app/ClientTransactionHandler.java frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java frameworks/base/core/java/android/app/Instrumentation.java frameworks/base/core/java/android/app/Activity.java frameworks/base/core/java/android/app/servertransaction/TransactionExecutorHelper.java #Activity.java ├──startActivity(Intent intent) └──startActivity(Intent intent, @Nullable Bundle options) └──startActivityForResult(@RequiresPermission Intent intent, int requestCode,@Nullable Bundle options) └──mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); #Instrumentation.java ├──execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target,Intent intent, int requestCode, Bundle options) └──int result = ActivityTaskManager.getService().startActivity(whoThread,who.getOpPackageName(), who.getAttributionTag(), intent,intent.resolveTypeIfNeeded(who.getContentResolver()), token,target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); #ActivityTaskManagerService.java ├──startActivity(IApplicationThread caller, String callingPackage,String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,Bundle bOptions) └──startActivityAsUser(IApplicationThread caller, String callingPackage,@Nullable String callingFeatureId, Intent intent, String resolvedType,IBinder resultTo, String resultWho, int requestCode, int startFlags,ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) └──return getActivityStartController().obtainStarter(intent, "startActivityAsUser") | .setCaller(caller) | .setCallingPackage(callingPackage) | .setCallingFeatureId(callingFeatureId) | .setResolvedType(resolvedType) | .setResultTo(resultTo) | .setResultWho(resultWho) | .setRequestCode(requestCode) | .setStartFlags(startFlags) | .setProfilerInfo(profilerInfo) | .setActivityOptions(bOptions) | .setUserId(userId) | .execute(); #ActivityStarter.java ├──execute() └──res = executeRequest(mRequest); └──executeRequest(Request request) └──mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,restrictedBgActivity, intentGrants); └──result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants); └──mRootWindowContainer.resumeFocusedTasksTopActivities(mTargetRootTask, mStartActivity, mOptions, mTransientLaunch); #Task.java ├──resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options,boolean deferPause) └──someActivityResumed = resumeTopActivityInnerLocked(prev, options, deferPause); #ActivityTaskSupervisor.java ├──startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) └──realStartActivityLocked(r, wpc, andResume, checkConfig); └──mService.getLifecycleManager().scheduleTransaction(clientTransaction); #ClientLifecycleManager.java ├──scheduleTransaction(ClientTransaction transaction) throws RemoteException └──transaction.schedule(); #ClientTransaction.java ├──schedule() throws RemoteException └──mClient.scheduleTransaction(this); #ActivityThread.java ├──scheduleTransaction(ClientTransaction transaction) └──sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); └──handleMessage(Message msg) └──case EXECUTE_TRANSACTION: └──mTransactionExecutor.execute(transaction); #TransactionExecutor.java ├──execute(ClientTransaction transaction) └──executeCallbacks(transaction);//执行LaunchActivityItem | └──item.execute(mTransactionHandler, token, mPendingActions); | #LaunchActivityItem.java | ├──execute(ClientTransactionHandler client, IBinder token,PendingTransactionActions pendingActions) | └──client.handleLaunchActivity(r, pendingActions, null /* customIntent */); | #ActivityThread.java | ├──handleLaunchActivity(ActivityClientRecord r,PendingTransactionActions pendingActions, Intent customIntent) | └──final Activity a = performLaunchActivity(r, customIntent); | └──if (r.isPersistable())//通过Instrumentation调用onCreate方法 | mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); | └──ielse | mInstrumentation.callActivityOnCreate(activity, r.state); | #Instrumentation.java | ├──callActivityOnCreate(Activity activity, Bundle icicle) | └──activity.performCreate(icicle); | #Activity.java | ├──performCreate(Bundle icicle) | └──if (persistentState != null) | onCreate(icicle, persistentState); | └──else | onCreate(icicle); └──executeLifecycleState(transaction);//执行ResumeActivityItem └──cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction); | └──final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState); | └──performLifecycleSequence(r, path, transaction); └──lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
<-Activity.java>
public void startActivity(Intent intent) { this.startActivity(intent, null); } public void startActivity(Intent intent, @Nullable Bundle options) { ... if (options != null) { startActivityForResult(intent, -1, options); } else { startActivityForResult(intent, -1); } } 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,//mToken数据类型为IBinder intent, requestCode, options); if (ar != null) { mMainThread.sendActivityResult( mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData()); } if (requestCode >= 0) { mStartedActivity = true; } cancelInputsAndStartExitTransition(options); } else { if (options != null) { mParent.startActivityFromChild(this, intent, requestCode, options); } else { mParent.startActivityFromChild(this, intent, requestCode); } } }
<-Instrumentation.java>
public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { if (intent != null) { android.util.SeempLog.record_str(377, intent.toString()); } IApplicationThread whoThread = (IApplicationThread) contextThread; Uri referrer = target != null ? target.onProvideReferrer() : null; if (referrer != null) { intent.putExtra(Intent.EXTRA_REFERRER, referrer); } if (mActivityMonitors != null) { synchronized (mSync) { final int N = mActivityMonitors.size(); for (int i=0; i<N; i++) { final ActivityMonitor am = mActivityMonitors.get(i); ActivityResult result = null; if (am.ignoreMatchingSpecificIntents()) { result = am.onStartActivity(intent); } if (result != null) { am.mHits++; return result; } else if (am.match(who, null, intent)) { am.mHits++; if (am.isBlocking()) {//当该monitor阻塞activity启动,则直接返回 return requestCode >= 0 ? am.getResult() : null; } break; } } } } try { intent.migrateExtraStreamToClipData(who); intent.prepareToLeaveProcess(who); int result = ActivityTaskManager.getService().startActivity(whoThread, who.getOpPackageName(), who.getAttributionTag(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); checkStartActivityResult(result, intent);//检查activity是否启动成功 } catch (RemoteException e) { throw new RuntimeException("Failure from system", e); } return null; }
<-ActivityTaskManagerService.java>
public final int startActivity(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, UserHandle.getCallingUserId()); } private int startActivityAsUser(IApplicationThread caller, String callingPackage, @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) { assertPackageMatchesCallingUid(callingPackage); enforceNotIsolatedCaller("startActivityAsUser"); userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser, Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser"); // TODO: Switch to user app stacks here. return getActivityStartController().obtainStarter(intent, "startActivityAsUser") .setCaller(caller) .setCallingPackage(callingPackage) .setCallingFeatureId(callingFeatureId) .setResolvedType(resolvedType) .setResultTo(resultTo) .setResultWho(resultWho) .setRequestCode(requestCode) .setStartFlags(startFlags) .setProfilerInfo(profilerInfo) .setActivityOptions(bOptions) .setUserId(userId) .execute(); }
<-ActivityStarter.java>
int execute() { try { ... int res; synchronized (mService.mGlobalLock) { ... res = executeRequest(mRequest); ... return getExternalResult(res); } } finally { onExecutionComplete(); } } private int executeRequest(Request request) { ... WindowProcessController callerApp = null; if (caller != null) { callerApp = mService.getProcessController(caller); //获取调用者的进程,如果是点击桌面图标启动,则是Launcher进程,如果是在我们自己app启动,则是app所在进程,也就是ActivityA所在进程 if (callerApp != null) { callingPid = callerApp.getPid(); callingUid = callerApp.mInfo.uid; } else { Slog.w(TAG, "Unable to find app for caller " + caller + " (pid=" + callingPid + ") when starting: " + intent.toString()); err = ActivityManager.START_PERMISSION_DENIED; } } ... //检测调用者app是否有启动权限 boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho, requestCode, callingPid, callingUid, callingPackage, callingFeatureId, request.ignoreTargetSecurity, inTask != null, callerApp, resultRecord, resultRootTask); abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid, callingPid, resolvedType, aInfo.applicationInfo); abort |= !mService.getPermissionPolicyInternal().checkStartActivity(intent, callingUid, callingPackage); boolean restrictedBgActivity = false; if (!abort) { try { Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "shouldAbortBackgroundActivityStart"); restrictedBgActivity = shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, realCallingUid, realCallingPid, callerApp, request.originatingPendingIntent, request.allowBackgroundActivityStart, intent); } finally { Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER); } } .... if (aInfo != null) { if (mService.getPackageManagerInternalLocked().isPermissionsReviewRequired( aInfo.packageName, userId)) { final IIntentSender target = mService.getIntentSenderLocked( ActivityManager.INTENT_SENDER_ACTIVITY, callingPackage, callingFeatureId, callingUid, userId, null, null, 0, new Intent[]{intent}, new String[]{resolvedType}, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT, null); Intent newIntent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS); int flags = intent.getFlags(); flags |= Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS; if ((flags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_NEW_DOCUMENT)) != 0) { flags |= Intent.FLAG_ACTIVITY_MULTIPLE_TASK; } newIntent.setFlags(flags); newIntent.putExtra(Intent.EXTRA_PACKAGE_NAME, aInfo.packageName); newIntent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target)); if (resultRecord != null) { newIntent.putExtra(Intent.EXTRA_RESULT_NEEDED, true); } intent = newIntent; // The permissions review target shouldn't get any permission // grants intended for the original destination intentGrants = null; resolvedType = null; callingUid = realCallingUid; callingPid = realCallingPid; //内部会通过PackageManagerService查找要启动的Activity信息,如果有多个匹配的Activity,则会弹窗让用户选择启动哪个 rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId, 0, computeResolveFilterUid(callingUid, realCallingUid, request.filterCallingUid)); aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, null /*profilerInfo*/); } } //收集将要启动的Activity信息,封装为ActivityRecord对象 final ActivityRecord r = new ActivityRecord.Builder(mService) .setCaller(callerApp) .setLaunchedFromPid(callingPid) .setLaunchedFromUid(callingUid) .setLaunchedFromPackage(callingPackage) .setLaunchedFromFeature(callingFeatureId) .setIntent(intent) .setResolvedType(resolvedType) .setActivityInfo(aInfo) .setConfiguration(mService.getGlobalConfiguration()) .setResultTo(resultRecord) .setResultWho(resultWho) .setRequestCode(requestCode) .setComponentSpecified(request.componentSpecified) .setRootVoiceInteraction(voiceSession != null) .setActivityOptions(checkedOptions) .setSourceRecord(sourceRecord) .build(); ... mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession, request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask, restrictedBgActivity, intentGrants); return mLastStartActivityResult; } private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, Task inTask, boolean restrictedBgActivity, NeededUriGrants intentGrants) { ...... try { mService.deferWindowLayout(); result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor, startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants); } ...... postStartActivityProcessing(r, result, startedActivityRootTask); return result; } int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, Task inTask, boolean restrictedBgActivity, NeededUriGrants intentGrants) { setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession, voiceInteractor, restrictedBgActivity); //处理intent中所携带的flag,保存到mLaunchFlags中 computeLaunchingTaskFlags(); //获取源启动任务栈,获取到的就是ActivityA所在的任务栈 computeSourceRootTask(); mIntent.setFlags(mLaunchFlags); //查找是否存在已存在的可用的任务栈 final Task reusedTask = getReusableTask(); ..... //判断是否创建一个新的Task if (newTask) { final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null) ? mSourceRecord.getTask() : null; //在这里创建,并把ActivityB放入Task setNewTask(taskToAffiliate); } else if (mAddingToTask) { addOrReparentStartingActivity(targetTask, "adding to task"); } .... if (mDoResume) { final ActivityRecord topTaskActivity = mStartActivity.getTask().topRunningActivityLocked(); if (!mTargetRootTask.isTopActivityFocusable() || (topTaskActivity != null && topTaskActivity.isTaskOverlay() && mStartActivity != topTaskActivity)) { mTargetRootTask.ensureActivitiesVisible(null /* starting */, 0 /* configChanges */, !PRESERVE_WINDOWS); mTargetRootTask.mDisplayContent.executeAppTransition(); } else { if (mTargetRootTask.isTopActivityFocusable() && !mRootWindowContainer.isTopDisplayFocusedRootTask(mTargetRootTask)) { mTargetRootTask.moveToFront("startActivityInner"); } //最后走到这里 mRootWindowContainer.resumeFocusedTasksTopActivities( mTargetRootTask, mStartActivity, mOptions, mTransientLaunch); } } ..... return START_SUCCESS; }
<-RootWindowContainer.java>
boolean resumeFocusedTasksTopActivities(
Task targetRootTask, ActivityRecord target, ActivityOptions targetOptions,
boolean deferPause) {
....
if (targetRootTask != null && (targetRootTask.isTopRootTaskInDisplayArea()
|| getTopDisplayFocusedRootTask() == targetRootTask)) {
//跳转到这里
result = targetRootTask.resumeTopActivityUncheckedLocked(target, targetOptions,
deferPause);
}
....
return result;
}
<-Task.java>
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options, boolean deferPause) { .... try { // Protect against recursion. mInResumeTopActivity = true; if (isLeafTask()) { if (isFocusableAndVisible()) { //执行resumeTopActivityInnerLocked进行处理 someActivityResumed = resumeTopActivityInnerLocked(prev, options, deferPause); } } .... return someActivityResumed; } private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options, boolean deferPause) { if (!mAtmService.isBooting() && !mAtmService.isBooted()) { // Not ready yet! return false; } //拿到任务栈顶部resume状态的Activity ActivityRecord next = topRunningActivity(true /* focusableOnly */); .... //把处于resume状态的Activity暂停,会触发ActivityA生命周期的pause方法 boolean pausing = !deferPause && taskDisplayArea.pauseBackTasks(next); if (mResumedActivity != null) { pausing |= startPausingLocked(false /* uiSleeping */, next, "resumeTopActivityInnerLocked"); } .... //启动指定的Activity,第二个参数andResume = true mTaskSupervisor.startSpecificActivity(next, true, true);//--注释3-- } return true; }
<-ActivityTaskSupervisor.java>
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) { // Is this activity's application already running? final WindowProcessController wpc = mService.getProcessController(r.processName, r.info.applicationInfo.uid); boolean knownToBeDead = false; //如果要启动的Activity进程已经创建,执行realStartActivityLocked方法 if (wpc != null && wpc.hasThread()) { try { realStartActivityLocked(r, wpc, andResume, checkConfig); return; } catch (RemoteException e) { Slog.w(TAG, "Exception when starting activity " + r.intent.getComponent().flattenToShortString(), e); } // If a dead object exception was thrown -- fall through to // restart the application. knownToBeDead = true; } r.notifyUnknownVisibilityLaunchedForKeyguardTransition(); final boolean isTop = andResume && r.isTopRunningActivity(); //如果要启动的Activity所在进程没有创建,会在这里面创建 mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity"); } boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) throws RemoteException { .... // 创建一个事务,用来处理生命周期 final ClientTransaction clientTransaction = ClientTransaction.obtain( proc.getThread(), r.appToken); final boolean isTransitionForward = r.isTransitionForward(); //添加一个回调,用来调用ActivityB的onCreate方法 clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent), System.identityHashCode(r), r.info, mergedConfiguration.getGlobalConfiguration(), mergedConfiguration.getOverrideConfiguration(), r.compat, r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(), r.getSavedState(), r.getPersistentSavedState(), results, newIntents, r.takeOptions(), isTransitionForward, proc.createProfilerInfoIfNeeded(), r.assistToken, activityClientController, r.createFixedRotationAdjustmentsIfNeeded(), r.shareableActivityToken, r.getLaunchedFromBubble())); // Set desired final state. final ActivityLifecycleItem lifecycleItem; //andResume是从上面注释3处传下来的,可知为true if (andResume) { //用于执行ActivityB的onResume的回调 lifecycleItem = ResumeActivityItem.obtain(isTransitionForward); } else { lifecycleItem = PauseActivityItem.obtain(); } clientTransaction.setLifecycleStateRequest(lifecycleItem); mService.getLifecycleManager().scheduleTransaction(clientTransaction); .... return true; }
<-ClientLifecycleManager.java>
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {
// If client is not an instance of Binder - it's a remote call and at this point it is
// safe to recycle the object. All objects used for local calls will be recycled after
// the transaction is executed on client in ActivityThread.
transaction.recycle();
}
}
<-ClientTransaction.java>
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);//mClient是IApplicationThread类型的对象
}
<-ActivityThread.java>
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);//调用ActivityThread的父类ClientTransactionHandler中scheduleTransaction
}
<-ClientTransactionHandler.java>
void scheduleTransaction(ClientTransaction transaction) { transaction.preExecute(this); sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); } private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) { if (DEBUG_MESSAGES) { Slog.v(TAG, "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj); } Message msg = Message.obtain(); msg.what = what; msg.obj = obj; msg.arg1 = arg1; msg.arg2 = arg2; if (async) { msg.setAsynchronous(true); } mH.sendMessage(msg); }
<-ActivityThread.java>
public void handleMessage(Message msg) { if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what)); switch (msg.what) { ...... case EXECUTE_TRANSACTION: final ClientTransaction transaction = (ClientTransaction) msg.obj; mTransactionExecutor.execute(transaction); if (isSystem()) { // Client transactions inside system process are recycled on the client side // instead of ClientLifecycleManager to avoid being cleared before this // message is handled. transaction.recycle(); } // TODO(lifecycler): Recycle locally scheduled transactions. break; ...... } }
<-TransactionExecutor.java>
public void execute(ClientTransaction transaction) { .... //执行LaunchActivityItem executeCallbacks(transaction); //执行ResumeActivityItem executeLifecycleState(transaction); mPendingActions.clear(); if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction"); } public void executeCallbacks(ClientTransaction transaction) { //这个List里包含了前面注释4处的LaunchActivityItem final List<ClientTransactionItem> callbacks = transaction.getCallbacks(); if (callbacks == null || callbacks.isEmpty()) { // No callbacks to execute, return early. return; } final IBinder token = transaction.getActivityToken(); .... final int size = callbacks.size(); for (int i = 0; i < size; ++i) { final ClientTransactionItem item = callbacks.get(i); .... //调用item的execute item.execute(mTransactionHandler, token, mPendingActions); item.postExecute(mTransactionHandler, token, mPendingActions); .... } }
<-LaunchActivityItem.java>
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
ActivityClientRecord r = client.getLaunchingActivity(token);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);//调用ActivityThread的handleLaunchActivity方法
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
<-ActivityThread.java>
public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) { .... final Activity a = performLaunchActivity(r, customIntent); .... return a; } private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { ActivityInfo aInfo = r.activityInfo; if (r.packageInfo == null) { r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo, Context.CONTEXT_INCLUDE_CODE); } ComponentName component = r.intent.getComponent(); if (component == null) { component = r.intent.resolveActivity( mInitialApplication.getPackageManager()); r.intent.setComponent(component); } if (r.activityInfo.targetActivity != null) { component = new ComponentName(r.activityInfo.packageName, r.activityInfo.targetActivity); } //创建一个ContextImpl对象,每个Acitvity都会持用一个ContextImpl ContextImpl appContext = createBaseContextForActivity(r); Activity activity = null; try { java.lang.ClassLoader cl = appContext.getClassLoader(); //newActivity方法内部会通过反射创建一个Activity对象 activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent); StrictMode.incrementExpectedActivityCount(activity.getClass()); r.intent.setExtrasClassLoader(cl); r.intent.prepareToEnterProcess(isProtectedComponent(r.activityInfo), appContext.getAttributionSource()); if (r.state != null) { r.state.setClassLoader(cl); } } catch (Exception e) { if (!mInstrumentation.onException(activity, e)) { throw new RuntimeException( "Unable to instantiate activity " + component + ": " + e.toString(), e); } } try { //也是通过反射创建一个全局唯一的Application对象,如果已经创建过,则这缓存中拿。 Application app = r.packageInfo.makeApplication(false, mInstrumentation); if (localLOGV) Slog.v(TAG, "Performing launch of " + r); if (localLOGV) Slog.v( TAG, r + ": app=" + app + ", appName=" + app.getPackageName() + ", pkg=" + r.packageInfo.getPackageName() + ", comp=" + r.intent.getComponent().toShortString() + ", dir=" + r.packageInfo.getAppDir()); if (activity != null) { CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager()); Configuration config = new Configuration(mConfigurationController.getCompatConfiguration()); if (r.overrideConfig != null) { config.updateFrom(r.overrideConfig); } if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity " + r.activityInfo.name + " with config " + config); Window window = null; if (r.mPendingRemoveWindow != null && r.mPreserveWindow) { window = r.mPendingRemoveWindow; r.mPendingRemoveWindow = null; r.mPendingRemoveWindowManager = null; } // Activity resources must be initialized with the same loaders as the // application context. appContext.getResources().addLoaders( app.getResources().getLoaders().toArray(new ResourcesLoader[0])); appContext.setOuterContext(activity); //给Acitivity的一些参数进行初始化 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, r.assistToken, r.shareableActivityToken); if (customIntent != null) { activity.mIntent = customIntent; } r.lastNonConfigurationInstances = null; checkAndBlockForNetworkAccess(); activity.mStartedActivity = false; int theme = r.activityInfo.getThemeResource(); if (theme != 0) { activity.setTheme(theme); } if (r.mActivityOptions != null) { activity.mPendingOptions = r.mActivityOptions; r.mActivityOptions = null; } activity.mLaunchedFromBubble = r.mLaunchedFromBubble; activity.mCalled = false; if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { //通过Instrumentation调用onCreate方法 mInstrumentation.callActivityOnCreate(activity, r.state); } if (!activity.mCalled) { throw new SuperNotCalledException( "Activity " + r.intent.getComponent().toShortString() + " did not call through to super.onCreate()"); } r.activity = activity; mLastReportedWindowingMode.put(activity.getActivityToken(), config.windowConfiguration.getWindowingMode()); } r.setState(ON_CREATE); // updatePendingActivityConfiguration() reads from mActivities to update // ActivityClientRecord which runs in a different thread. Protect modifications to // mActivities to avoid race. synchronized (mResourcesManager) { mActivities.put(r.token, r); } } catch (SuperNotCalledException e) { throw e; } catch (Exception e) { if (!mInstrumentation.onException(activity, e)) { throw new RuntimeException( "Unable to start activity " + component + ": " + e.toString(), e); } } return activity; }
<-Instrumentation.java>
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
<-Activity.java>
final void performCreate(Bundle icicle) {
performCreate(icicle, null);
}
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
....
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
//熟悉的onCreate方法
onCreate(icicle);
}
....
}
<-TransactionExecutor.java>
private void executeLifecycleState(ClientTransaction transaction) { final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); .... cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction); // Execute the final transition with proper parameters. lifecycleItem.execute(mTransactionHandler, token, mPendingActions); lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions); } //生命周期对应的各个常量 public static final int UNDEFINED = -1; public static final int PRE_ON_CREATE = 0; public static final int ON_CREATE = 1; public static final int ON_START = 2; public static final int ON_RESUME = 3; public static final int ON_PAUSE = 4; public static final int ON_STOP = 5; public static final int ON_DESTROY = 6; public static final int ON_RESTART = 7; private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState, ClientTransaction transaction) { //由于前面已经执行了onCreate,所以现在获取到的状态是ON_CREATE //finish参数是前面注释6处通过lifecycleItem.getTargetState()拿到的,lifecycleItem是ResumeActivityItem类型,对应的是ON_RESUME final int start = r.getLifecycleState(); final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState); performLifecycleSequence(r, path, transaction); } private void performLifecycleSequence(ActivityClientRecord r, IntArray path, ClientTransaction transaction) { final int size = path.size(); for (int i = 0, state; i < size; i++) { state = path.get(i); if (DEBUG_RESOLVER) { Slog.d(TAG, tId(transaction) + "Transitioning activity: " + getShortActivityName(r.token, mTransactionHandler) + " to state: " + getStateName(state)); } switch (state) { case ON_CREATE: mTransactionHandler.handleLaunchActivity(r, mPendingActions, null /* customIntent */); break; case ON_START: mTransactionHandler.handleStartActivity(r, mPendingActions, null /* activityOptions */); break; case ON_RESUME: mTransactionHandler.handleResumeActivity(r, false /* finalStateRequest */, r.isForward, "LIFECYCLER_RESUME_ACTIVITY"); break; case ON_PAUSE: mTransactionHandler.handlePauseActivity(r, false /* finished */, false /* userLeaving */, 0 /* configChanges */, mPendingActions, "LIFECYCLER_PAUSE_ACTIVITY"); break; case ON_STOP: mTransactionHandler.handleStopActivity(r, 0 /* configChanges */, mPendingActions, false /* finalStateRequest */, "LIFECYCLER_STOP_ACTIVITY"); break; case ON_DESTROY: mTransactionHandler.handleDestroyActivity(r, false /* finishing */, 0 /* configChanges */, false /* getNonConfigInstance */, "performLifecycleSequence. cycling to:" + path.get(size - 1)); break; case ON_RESTART: mTransactionHandler.performRestartActivity(r, false /* start */); break; default: throw new IllegalArgumentException("Unexpected lifecycle state: " + state); } } }
<-TransactionExecutorHelper.java>
public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) { .... //有上文可知finish >= start是true if (finish >= start) { if (start == ON_START && finish == ON_STOP) { mLifecycleSequence.add(ON_STOP); } else { // 跳转到这里,这个循环的意思就是把ON_START、ON_RESUME加入到mLifecycleSequence集合里 for (int i = start + 1; i <= finish; i++) { mLifecycleSequence.add(i); } } } .... return mLifecycleSequence; }
<-ActivityThread.java>
@Override
public void handleStartActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, ActivityOptions activityOptions) {
final Activity activity = r.activity;
....
// 在里面会调用onStart方法
activity.performStart("handleStartActivity");
r.setState(ON_START);
....
}
<-ActivityThread.java>
@Override public void handleResumeActivity(ActivityClientRecord r, boolean finalStateRequest, boolean isForward, String reason) { unscheduleGcIdler(); mSomeActivitiesChanged = true; // 在这里面执行onResume方法 if (!performResumeActivity(r, finalStateRequest, reason)) { return; } .... if (r.window == null && !a.mFinished && willBeVisible) { r.window = r.activity.getWindow(); View decor = r.window.getDecorView(); decor.setVisibility(View.INVISIBLE); ViewManager wm = a.getWindowManager(); WindowManager.LayoutParams l = r.window.getAttributes(); a.mDecor = decor; l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION; l.softInputMode |= forwardBit; if (r.mPreserveWindow) { a.mWindowAdded = true; r.mPreserveWindow = false; ViewRootImpl impl = decor.getViewRootImpl(); if (impl != null) { impl.notifyChildRebuilt(); } } if (a.mVisibleFromClient) { if (!a.mWindowAdded) { a.mWindowAdded = true; //把DecorView添加到WindowManager上,简单理解就是把我们的布局文件的内容显示到屏幕上 //在这里最终会通过ViewRootImpl来遍历view树,执行view的测量,摆放,绘制 wm.addView(decor, l); } .... }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。