基于 Android Q 10.0 系统 Activity启动流程探索

基于 Android Q 10.0 系统 Activity启动流程探索
推荐一个看Android源码的地址: Android Code Search

【基于 Android Q 10.0 系统 Activity启动流程探索】
文章目录

      • 1 MainActivity.java
      • 2 Activity.java
      • 3 Instrumentation.java
      • 4 ActivityTaskManager.java
      • 5 ActivityTaskManagerService.java
      • 6 ActivityStarter.java
      • 7 RootActivityContainer.java
      • 8 ActivityStack.java
      • 9 ActivityStackSupervisor.java
      • Back to 5 ActivityTaskManagerService.java
      • 10 ClientLifecycleManager.java
      • 11 ClientTransaction.java
      • 12 ActivityThread.java
      • 13 ClientTransactionHandler.java
      • Back to 12 ActivityThread.java
      • 14 TransactionExecutor.java
      • 15 LaunchActivityItem.java
      • Back to 12 ActivityThread.java
      • Back to 3 Instrumentation.java
      • Back to 2 Activity.java

1 MainActivity.java
startActivity(new Intent(this, MainActivity.class));

2 Activity.java
@Override public void startActivity(Intent intent) { this.startActivity(intent, null); }...里面重载函数就不贴了....public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) { ... Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); ... }

3 Instrumentation.java
public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { ... int result = ActivityTaskManager.getService() .startActivity(whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); ... }

4 ActivityTaskManager.java
public static IActivityTaskManager getService() { return IActivityTaskManagerSingleton.get(); }@UnsupportedAppUsage(trackingBug = 129726065) private static final Singleton IActivityTaskManagerSingleton = new Singleton() { @Override protected IActivityTaskManager create() { final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE); return IActivityTaskManager.Stub.asInterface(b); } }; //IActivityTaskManagerSingleton.get()获取的就是ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE); //通过IBinder跨进程方式调用系统服务——IActivityTaskManager是ActivityTaskManagerService代理类 public abstract class Singleton { @UnsupportedAppUsage private T mInstance; protected abstract T create(); @UnsupportedAppUsage public final T get() { synchronized (this) { if (mInstance == null) { mInstance = create(); } return mInstance; } } }

5 ActivityTaskManagerService.java
@Override public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, UserHandle.getCallingUserId()); } .... //最终会走到下面这个方法中 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) { //getActivityStartController().obtainStarte得到的是ActivityStarter,通过构造者模式填入各种属性,最终执行excute方法 return getActivityStartController().obtainStarter(intent, "startActivityAsUser") .setCaller(caller) .setCallingPackage(callingPackage) .setResolvedType(resolvedType) .setResultTo(resultTo) .setResultWho(resultWho) .setRequestCode(requestCode) .setStartFlags(startFlags) .setProfilerInfo(profilerInfo) .setActivityOptions(bOptions) .setMayWait(userId) .execute(); }

6 ActivityStarter.java
ActivityStarter setMayWait(int userId) { mRequest.mayWait = true; mRequest.userId = userId; return this; } //注意这里mRequest.mayWait因为被5执行了setMayWait(userId),到此已经为true了 int execute() { try { if (mRequest.mayWait) { //mRequest.mayWait=true,进入到这里 return startActivityMayWait(mRequest.caller, mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid, 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, mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart); } 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, mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart); } } finally { onExecutionComplete(); }//这个方法里面的代码太多了,我们只看最关键的 private int startActivityMayWait(...){ ... int res = startActivity(...); ... }...层层找,这里找resumeFocusedStacksTopActivities是关键点startActivity()-->startActivityUnchecked()--> //找到下面这段代码是至关重要的,这是整个过程最难的部分 mRootActivityContainer.resumeFocusedStacksTopActivities( mTargetStack, mStartActivity, mOptions);

7 RootActivityContainer.java
boolean resumeFocusedStacksTopActivities() { return resumeFocusedStacksTopActivities(null, null, null); } ... focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);

8 ActivityStack.java
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) { if (mInResumeTopActivity) { // Don't even start recursing. return false; }boolean result = false; try { // Protect against recursion. mInResumeTopActivity = true; result = resumeTopActivityInnerLocked(prev, options); } finally { mInResumeTopActivity = false; }return result; } private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) { ... //这里判断是否之前的Activity已经处于Resume状态,如果有的话要执行onStop方法 if (mResumedActivity != null) { if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Pausing " + mResumedActivity); pausing |= startPausingLocked(userLeaving, false, next, false); } .... //这里是要打开新的Activity了 mStackSupervisor.startSpecificActivityLocked(next, true, true); }

9 ActivityStackSupervisor.java
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) { try { realStartActivityLocked(r, wpc, andResume, checkConfig); return; } catch (RemoteException e) { Slog.w(TAG, "Exception when starting activity " + r.intent.getComponent().flattenToShortString(), e); } } boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) throws RemoteException { ... // Create activity launch transaction. //1 构造一个信使 final ClientTransaction clientTransaction = ClientTransaction.obtain( proc.getThread(), r.appToken); //2 封装一个消息,消息体是LaunchActivityItem final DisplayContent dc = r.getDisplay().mDisplayContent; 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.icicle, r.persistentState, results, newIntents, dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(), r.assistToken)); //3发送这个消息,沿着这条路走下去 mService.getLifecycleManager().scheduleTransaction(clientTransaction); ... }

Back to 5 ActivityTaskManagerService.java
ClientLifecycleManager getLifecycleManager() { return mLifecycleManager; }

10 ClientLifecycleManager.java
void scheduleTransaction(ClientTransaction transaction) throws RemoteException { final IApplicationThread client = transaction.getClient(); //这里的IApplicationThread是ApplicationThread的远程代理,ApplicationThread是ActivityThread的内部类 transaction.schedule(); }

11 ClientTransaction.java
public void schedule() throws RemoteException { //mClient就是上文说的ApplicationThread mClient.scheduleTransaction(this); }

12 ActivityThread.java
@Override public void scheduleTransaction(ClientTransaction transaction) throws RemoteException { //ActivityThread中并没有这个方法,而是他的父类中的方法 ActivityThread.this.scheduleTransaction(transaction); }

13 ClientTransactionHandler.java
void scheduleTransaction(ClientTransaction transaction) { transaction.preExecute(this); //既然是发送消息就必然有人接收消息 sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); }

Back to 12 ActivityThread.java
case EXECUTE_TRANSACTION ... final ClientTransaction transaction = (ClientTransaction) msg.obj; mTransactionExecutor.execute(transaction); ... break;

14 TransactionExecutor.java
public void execute(ClientTransaction transaction) { ... executeCallbacks(transaction); executeLifecycleState(transaction); ... }public void executeCallbacks(ClientTransaction transaction) { for (int i = 0; i < size; ++i) { ... //这里的Item就是9中的LaunchActivityItem final ClientTransactionItem item = callbacks.get(i); item.execute(mTransactionHandler, token, mPendingActions); item.postExecute(mTransactionHandler, token, mPendingActions); ... } }

15 LaunchActivityItem.java
@Override public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) { ... client.handleLaunchActivity(r, pendingActions, null /* customIntent */); ... }

Back to 12 ActivityThread.java
handleLaunchActivity()-->final Activity a = performLaunchActivity(r, customIntent)-->performLaunchActivity() if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); }

Back to 3 Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle, PersistableBundle persistentState) { prePerformCreate(activity); activity.performCreate(icicle, persistentState); postPerformCreate(activity); }

Back to 2 Activity.java
final void performCreate(Bundle icicle) { performCreate(icicle, null); } final void performCreate(Bundle icicle, PersistableBundle persistentState) { if (persistentState != null) { onCreate(icicle, persistentState); } else { onCreate(icicle); } }

    推荐阅读