Android 10 StartActivity 源码流程分析分析

分析从Activity页面的startActivity(Intent)开始

public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2...{

   public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
      Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                     intent, requestCode, options);
  }
   
}

在Activity内最终调到startActvityForResult方法,后续调用Instrumentation的execStartActivity,需要注意第二个参数时ActivityThread的内部类ApplicationThread,用于跨进程通讯的

public class Instrumentation {

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

 public static void checkStartActivityResult(int res, Object intent) {
        if (!ActivityManager.isStartResultFatalError(res)) {
            return;
        }

        switch (res) {
            case ActivityManager.START_INTENT_NOT_RESOLVED:
            case ActivityManager.START_CLASS_NOT_FOUND:
                if (intent instanceof Intent && ((Intent)intent).getComponent() != null)
                    throw new ActivityNotFoundException(
                            "Unable to find explicit activity class "
                            + ((Intent)intent).getComponent().toShortString()
                            + "; have you declared this activity in your AndroidManifest.xml?");
                throw new ActivityNotFoundException(
                        "No Activity found to handle " + intent);
          ...

            default:
                throw new AndroidRuntimeException("Unknown error code "
                        + res + " when starting " + intent);
        }
    }

}
public class ActivityTaskManager {
   
  public static IActivityTaskManager getService() {
        return IActivityTaskManagerSingleton.get();
    }

    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);
                }
            };
}
  1. 在Instrumentation中获取到system_server进程的IActivityTaskManager服务,实例是ActivityTaskManagerService
  2. 调用ActivityTaskManagerSerivce的startActivity方法,开始跨进程调用,传递参数IApplicationThread
  3. checkStartActivityResult方法检查跳转结果,常见的是错误如没有在清单文件注册Activity,跳转错误Unable to find explicit activity class ...; have you declared this activity in your AndroidManifest.xml?
/**
 * System service for managing activities and their containers (task, stacks, displays,... ).
 *
 * {@hide}
 */
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {

  private ActivityStartController mActivityStartController;

 ActivityStartController getActivityStartController() {
        return mActivityStartController;
    }
  
      @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) {

        // TODO: Switch to user app stacks here.
        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();
    }
}

public class ActivityStartController {

   ActivityStarter obtainStarter(Intent intent, String reason) {
        return mFactory.obtain().setIntent(intent).setReason(reason);
    }

}

最终调用到ActivityStarter的execute()方法,其中设置各种参数时需要注意setMayWait()方法中设置了mRequest.mayWait=true

/**
 * Controller for interpreting how and then launching an activity.
 *
 * This class collects all the logic for determining how an intent and flags should be turned into
 * an activity and associated task and stack.
 */
class ActivityStarter {

   private final RootActivityContainer mRootActivityContainer;

 /**
     * Starts an activity based on the request parameters provided earlier.
     * @return The starter result.
     */
    int execute() {
        try {
            // TODO(b/64750076): Look into passing request directly to these methods to allow
            // for transactional diffs and preprocessing.
            if (mRequest.mayWait) {
                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 {
               ...
            }
        } finally {
            onExecutionComplete();
        }
    }

 private int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, int requestRealCallingPid, int requestRealCallingUid,
            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,
            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
     ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
                0 /* matchFlags */,
                        computeResolveFilterUid(
                                callingUid, realCallingUid, mRequest.filterCallingUid));

 ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);

 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, originatingPendingIntent,
                    allowBackgroundActivityStart);
}

  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,
            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {

    ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
                callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
                resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
                mSupervisor, checkedOptions, sourceRecord);

}

  private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity, boolean restrictedBgActivity) {
    final ActivityStack topStack = mRootActivityContainer.getTopDisplayFocusedStack();
       mRootActivityContainer.resumeFocusedStacksTopActivities();
}

 ActivityStarter setMayWait(int userId) {
        mRequest.mayWait = true;
        mRequest.userId = userId;

        return this;
    }

}
  1. 在system_server进程,首先解析出ResolveInfo,主要时从清单文件收集相关信息,包括由ActivityInfo、ServiceInfo、ProviderInfo等
  2. 创建ActivityRecord对象,历史堆栈中的一个条目,即表示一个Activity
  3. 创建ActivityStack对象,单个Activity堆栈的状态和管理
  4. 完成相关解析和堆栈处理,调用RootActivityContainer的resumeFocusedStacksTopActivities

class RootActivityContainer extends ConfigurationContainer
        implements DisplayManager.DisplayListener {

  boolean resumeFocusedStacksTopActivities() {
        return resumeFocusedStacksTopActivities(null, null, null);
    }

   boolean resumeFocusedStacksTopActivities(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

    // In cases when there are no valid activities (e.g. device just booted or launcher
                // crashed) it's possible that nothing was resumed on a display. Requesting resume
                // of top activity in focused stack explicitly will make sure that at least home
                // activity is started and resumed, and no recursion occurs.
                final ActivityStack focusedStack = display.getFocusedStack();
                if (focusedStack != null) {
                    focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
                }
}

}

RootActivityContainer是Activity容器的根节点,流程是针对新建的Activity;最终跳到ActivityStack类中

/**
 * State and management of a single stack of activities.
 */
class ActivityStack extends ConfigurationContainer {

 
  /** Run all ActivityStacks through this */
    protected final ActivityStackSupervisor mStackSupervisor;

 boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {

      boolean result = false;
     result = resumeTopActivityInnerLocked(prev, options);
}

 private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
   
//暂停上一个Activity,执行OnPause()方法
 if (mResumedActivity != null) {
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Pausing " + mResumedActivity);
            pausing |= startPausingLocked(userLeaving, false, next, false);
        }

   //开启一个新的Activity,执行到onResume()方法
    mStackSupervisor.startSpecificActivityLocked(next, true, true);
    
}

}
  1. 创建ClientTransaction,该类是一个容器,包含了一系列可以发送到客户端的消息,消息包括回调列表和最终生命周期状态
  2. 核心代码分支,一个是暂停前一个Activity的方法startPausingLocked()方法,一个开启新的Activity方法mStackSupervisor.startSpecificActivityLocked

  1. 暂停Activity的方法onPause

class ActivityStack extends ConfigurationContainer {

    final ActivityTaskManagerService mService;

    final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
            ActivityRecord resuming, boolean pauseImmediately) {

          mService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
                        prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,
                                prev.configChangeFlags, pauseImmediately));

    }
}
  1. 创建Activity的pause周期状态类PauseActivityItem
  2. mService.getLifecycleManager()获取的是ClientLifecycleManager,最终执行ClientLifecycleManager的scheduleTransaction
class ClientLifecycleManager {

 void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
            @NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
        final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
                stateRequest);
        scheduleTransaction(clientTransaction);
    }

    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();
    }

 private static ClientTransaction transactionWithState(@NonNull IApplicationThread client,
            @NonNull IBinder activityToken, @NonNull ActivityLifecycleItem stateRequest) {
        final ClientTransaction clientTransaction = ClientTransaction.obtain(client, activityToken);
        clientTransaction.setLifecycleStateRequest(stateRequest);
        return clientTransaction;
    }
}

最终执行ClientTransaction的schedule()

public class ClientTransaction implements Parcelable, ObjectPoolItem {

 /** Target client. */
    private IApplicationThread mClient;

     /**
     * Schedule the transaction after it was initialized. It will be send to client and all its
     * individual parts will be applied in the following sequence:
     * 1. The client calls {@link #preExecute(ClientTransactionHandler)}, which triggers all work
     *    that needs to be done before actually scheduling the transaction for callbacks and
     *    lifecycle state request.
     * 2. The transaction message is scheduled.
     * 3. The client calls {@link TransactionExecutor#execute(ClientTransaction)}, which executes
     *    all callbacks and necessary lifecycle transitions.
     */
    public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }
}

从system_server进程使用IApplicationThread跳转到App进程,且调用ApplicationThread的scheduleTransaction

public final class ActivityThread extends ClientTransactionHandler {

   private class ApplicationThread extends IApplicationThread.Stub {
        @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            ActivityThread.this.scheduleTransaction(transaction);
        }
  }
}

最终执行ActivityThread的scheduleTransaction,但是在ActivityThread类中没有找到,在父类ClientTransactionHandler查找到

public abstract class ClientTransactionHandler {

     /** Prepare and schedule transaction for execution. */
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

     abstract void sendMessage(int what, Object obj);

}

跳转到ActivityThread的内部类H中发送消息

public final class ActivityThread extends ClientTransactionHandler {

    private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);

     class H extends Handler {
        public static final int EXECUTE_TRANSACTION = 159;
          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);
                
                    break;
            }
     }
}

最终执行TranaactionExecutor的execute方法

/**
 * Class that manages transaction execution in the correct order.
 * @hide
 */
public class TransactionExecutor {
    public void execute(ClientTransaction transaction) {

        executeCallbacks(transaction);

        executeLifecycleState(transaction);
     }

 /** Cycle through all states requested by callbacks and execute them at proper times. */
    @VisibleForTesting
    public void executeCallbacks(ClientTransaction transaction) {
      final List callbacks = transaction.getCallbacks();
        if (callbacks == null || callbacks.isEmpty()) {
            // No callbacks to execute, return early.
            return;
        }
      for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
                 item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
       }
     }

   /** Transition to the final state if requested by the transaction. */
    private void executeLifecycleState(ClientTransaction transaction) {
          final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        if (lifecycleItem == null) {
            // No lifecycle request, return early.
            return;
        }
       // Execute the final transition with proper parameters.
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
   }
}

前面传递过来的我们知道是PauseActivityItem,属于ActivityLifecycleItem,执行对应的execute和postExecute方法

/**
 * Request to move an activity to paused state.
 * @hide
 */
public class PauseActivityItem extends ActivityLifecycleItem {
  
    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
     
        client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
                "PAUSE_ACTIVITY_ITEM");
      
    }

  @Override
    public void postExecute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        if (mDontReport) {
            return;
        }
        try {
            // TODO(lifecycler): Use interface callback instead of AMS.
            ActivityTaskManager.getService().activityPaused(token);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }
 }

我们只需要关注execute方法,执行handlerPauseActivity

public abstract class ClientTransactionHandler {

      Instrumentation mInstrumentation;

     /** Pause the activity. */
    public abstract void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
            int configChanges, PendingTransactionActions pendingActions, String reason);

}

public final class ActivityThread extends ClientTransactionHandler {
    @Override
    public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
            int configChanges, PendingTransactionActions pendingActions, String reason) {
         performPauseActivity(r, finished, reason, pendingActions);
   }


    /**
     * Pause the activity.
     * @return Saved instance state for pre-Honeycomb apps if it was saved, {@code null} otherwise.
     */
    private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
            PendingTransactionActions pendingActions) {
        performPauseActivityIfNeeded(r, reason);
    }

    private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
           mInstrumentation.callActivityOnPause(r.activity);
   }

}

  最后跟到调用Instrumentation的callActivityOnPause方法

public class Instrumentation {
    public void callActivityOnPause(Activity activity) {
        activity.performPause();
    }
 }


public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback,
        OnCreateContextMenuListener, ComponentCallbacks2,
        Window.OnWindowDismissedCallback, WindowControllerCallback,
        AutofillManager.AutofillClient, ContentCaptureManager.ContentCaptureClient {

       final void performPause() {
            onPause();
       }

        @CallSuper
    protected void onPause() {
      }
}

 走到了Activity的生命周期方法onPause方法

新建Activity并调用onResume方法

调用ActivityStackSupervisor的startSpecificActivityLocked

public class ActivityStackSupervisor implements RecentTasks.Callbacks {

     void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
         realStartActivityLocked(r, wpc, andResume, checkConfig);
 }

       boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {

        // Create activity launch transaction.
                final ClientTransaction clientTransaction = ClientTransaction.obtain(
                        proc.getThread(), r.appToken);
       clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                        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, proc.getReportedProcState(),
                        r.icicle, r.persistentState, results, newIntents,
                        dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                                r.assistToken));

                // Set desired final state.
                final ActivityLifecycleItem lifecycleItem;
                if (andResume) {
                    lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                clientTransaction.setLifecycleStateRequest(lifecycleItem);

                // Schedule transaction.
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);
   }
}
  1. 最终调用 realStartActivityLocked方法
  2. 创建ClientTransaction,并增加一个Callback,是LaunchActivityItem;设置一个生命周期状态请求ResumeActivityItem
  3. 最终调用ClientLifecycleManager的scheduleTransaction
/**
 * Class that is able to combine multiple client lifecycle transition requests and/or callbacks,
 * and execute them as a single transaction.
 *
 * @see ClientTransaction
 */
class ClientLifecycleManager {
      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的schedule

/**
 * A container that holds a sequence of messages, which may be sent to a client.
 * This includes a list of callbacks and a final lifecycle state.
 *
 * @see com.android.server.am.ClientLifecycleManager
 * @see ClientTransactionItem
 * @see ActivityLifecycleItem
 * @hide
 */
public class ClientTransaction implements Parcelable, ObjectPoolItem {

 private IApplicationThread mClient;

     /**
     * Schedule the transaction after it was initialized. It will be send to client and all its
     * individual parts will be applied in the following sequence:
     * 1. The client calls {@link #preExecute(ClientTransactionHandler)}, which triggers all work
     *    that needs to be done before actually scheduling the transaction for callbacks and
     *    lifecycle state request.
     * 2. The transaction message is scheduled.
     * 3. The client calls {@link TransactionExecutor#execute(ClientTransaction)}, which executes
     *    all callbacks and necessary lifecycle transitions.
     */
    public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }
}

最终调用回调到App进程内ApplicationThread的scheduleTransaction

public final class ActivityThread extends ClientTransactionHandler {

   private class ApplicationThread extends IApplicationThread.Stub {

 @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            ActivityThread.this.scheduleTransaction(transaction);
        }
     
   }
}

最终调用ActivityThread的父类ClientTransactionHandler的scheduleTransaction

public abstract class ClientTransactionHandler {
    /** Prepare and schedule transaction for execution. */
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
}

发送消息给ActivityThread.H处理

public final class ActivityThread extends ClientTransactionHandler {

// An executor that performs multi-step transactions.
    private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);

 class H extends Handler {
       public static final int EXECUTE_TRANSACTION = 159;

    public void handleMessage(Message msg) {
         switch (msg.what) {
            case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    mTransactionExecutor.execute(transaction);
              break;
         }
    }
 }

}

调用TransactionExecutor的execute()方法

/**
 * Class that manages transaction execution in the correct order.
 * @hide
 */
public class TransactionExecutor {
   
 /**
     * Resolve transaction.
     * First all callbacks will be executed in the order they appear in the list. If a callback
     * requires a certain pre- or post-execution state, the client will be transitioned accordingly.
     * Then the client will cycle to the final lifecycle state if provided. Otherwise, it will
     * either remain in the initial state, or last state needed by a callback.
     */
    public void execute(ClientTransaction transaction) {
       executeCallbacks(transaction);

     executeLifecycleState(transaction);
   }

   /** Transition to the final state if requested by the transaction. */
    private void executeLifecycleState(ClientTransaction transaction) {
 final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
  lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }

/** Cycle through all states requested by callbacks and execute them at proper times. */
    @VisibleForTesting
    public void executeCallbacks(ClientTransaction transaction) {
       final List callbacks = transaction.getCallbacks();
 final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
           item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
        }
   }
    
}

首先执行ClientTransactionItem的相关内容,即LaunchActivityItem的execute

再执行ActivityLifecycleItem的相关内容,即ResumeActivityItem的execute()


首先执行ClientTransactionItem的相关内容,即LaunchActivityItem的execute()

/**
 * Request to launch an activity.
 * @hide
 */
public class LaunchActivityItem extends ClientTransactionItem {
   @Override
    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, mAssistToken);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
      
    }
}

最终调用ActivityThread的handleLaunchActivity

public final class ActivityThread extends ClientTransactionHandler {
    @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
         final Activity a = performLaunchActivity(r, customIntent);
    }

    /**  Core implementation of activity launch. */
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
       ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
   }
}

 创建Activity,通过Instrumentation的newActivity

public class Instrumentation {
     public Activity newActivity(ClassLoader cl, String className,
            Intent intent)
            throws InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        String pkg = intent != null && intent.getComponent() != null
                ? intent.getComponent().getPackageName() : null;
        return getFactory(pkg).instantiateActivity(cl, className, intent);
    }

   
}

最终调用了AppComponentFactory的instantiateActivity

public class AppComponentFactory {
     public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,
            @Nullable Intent intent)
            throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return (Activity) cl.loadClass(className).newInstance();
    }
}

 创建新的Activity

再执行ActivityLifecycleItem的相关内容,即ResumeActivityItem的execute()

/**
 * Request to move an activity to resumed state.
 * @hide
 */
public class ResumeActivityItem extends ActivityLifecycleItem {

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

最终调用ActivityThread的handleResumeActivity

public final class ActivityThread extends ClientTransactionHandler {

 @Override
    public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
            String reason) {

       final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
        
       
 }

   public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
            String reason) {
       final ActivityClientRecord r = mActivities.get(token);
      r.activity.performResume(r.startsNotResumed, reason);
  }
}

获取当前Activity,并执行Activity的performResume

public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback,
        OnCreateContextMenuListener, ComponentCallbacks2,
        Window.OnWindowDismissedCallback, WindowControllerCallback,
        AutofillManager.AutofillClient, ContentCaptureManager.ContentCaptureClient {

    private Instrumentation mInstrumentation;

 final void performResume(boolean followedByPause, String reason) {
      // mResumed is set by the instrumentation
        mInstrumentation.callActivityOnResume(this);
 }
   
}

Activity调用Instrumentation的callActivityOnResume方法

public class Instrumentation {
  
  public void callActivityOnResume(Activity activity) {
      activity.onResume();
  }
}

调用Activity的生命周期方法onResume

你可能感兴趣的:(架构师,移动开发)