深入理解Activity(一) ----- Activity启动流程

一、前言

本篇文章主要整理Activity相关原理的知识点整理。我们平时业务开发基本都离不开Activity,那么我们又对它有多少了解呢,这里不仅会有阶段性的总结还会通过图解和一些必要的信息让你能更好的吸收这块只是和更好的理解整个Activity相关的逻辑与流程,读懂Activity所涉及到知识点,不仅对日常业务开发遇到问题有更全面的分析思路 ,而且如果面试遇到了相关问题,能回答的完善且有脉络。

在阅读本系列前可以先思考以下几个问题

  • 是否熟悉Activity启动流程中与AMS的交互过程
  • Activity所在进程是怎么启动的
  • 是否了解Activity的onCreate和onAttach的执行顺序(即应用Activity生命周期回调原理)
  • 是否熟悉Binder通信机制
  • 是否了解插件化框架如何 Hook Activity启动
  • 是否了解过Activity转场动画的实现原理
  • 是否了解Activity的窗口显示流程

注 Activity 系列framework 源码使用 android10 release 分支

本篇涉及相关代码

frameworks/base/services/core/java/com/android/server/wm/
  - ActivityStackSupervisor.java
  - ActivityStack.java
  - RootActivityContainer.java
  - WindowProcessController.java
  - ActivityStarter.java
  
frameworks/base/core/java/android/app/
  - Activity.java
  - TransactionExecutor.java 
  - ActivityManager.java
  - IApplicationThread.java
  - ClientTransactionHandler.java  
  - ActivityThread.java (内含ApplicationThread)
  - Instrumentation.java
  - ClientTransaction.java
  - ClientTransactionItem.java
  - LaunchActivityItem.java

在Android10 源码发现当中,以前放置在am里面的 ActivityManagerService.java相关类现在都被归到wm文件夹下

  • 1 增加RootActivityContainer,作为root activity的容器类
  • 2 增加WindowProcessController,用来和AMS同步进程状态
  • 3.在Android10中,Activity中的跨进程通信采用的是AIDL

相关类简介

  • ActivityTaskManagerService(ATMS):Android10中负责管理activity (ActivityManagerService是之前管理Activity启动流程的类)
  • ActivityStarter:处理intent和flags
  • ClientTransactionItem: LaunchActivityItem继承他,实现了parcel接口,用于system server和应用进程通信
  • ActivityStack:负责管理单独栈activity和其状态,

二、Activity的启动过程

  • 场景一:我们在Android里,点击一个图标,Android就为我们新建了一个进程,并唤醒我们在AndroidManifest中设置的 Launch Activity
  • 场景二:我们的闪屏页在跳到我们的主页App。

这两个场景对应着Activity启动有两种方式,一种是根Activity启动,即Activity跨进程启动。还有一种是普通Activity的启动过程,即Activity进程内启动。
在启动过程中我们启动Acitivty要向ATMS发起binder调用。

Activity跨进程启动

Activity跨进程启动有三个部分,分别是目标进程请求ATMS过程、ATMS到ApplicationThread的调用过程、ActivityThread启动Activity。(在老的系统版本中,AMS是system server提供 启动Activity的服务)

在这里插入图片描述

启动流程:

  1. 目标进程(点击App图标即为Launcher进程 或者 原App进程)采用Binder IPC向system_server进程发起startActivity请求
  2. system_server进程接收到请求后,向zygote进程发送创建进程的请求
  3. Zygote进程fork出新的子进程,即新的App进程
  4. App进程,通过Binder IPC 向system_server进程发起attachApplication请求
  5. system_server进程在收到请求后,进行一些列准备工作后,再通过binder IPC向App进程发送scheduleLaunchActivity请求
  6. App进程的binder线程(ApplicationThread)在收到请求后,通过handler向主线程发送LAUNCH_ACTIVITY消息
  7. 主线程在收到Message后,通过反射机制创建目标Activity,并回调Activity.onCreate()等方法。

接下来我们细讲整个Activity的启动流程源码

2.1目标进程请求AMS过程

2.1.1 Activity::startActivity
   @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else { // Note we want to go through this call for compatibility with // applications that may have overridden the method. startActivityForResult(intent, -1); } }
        }
    }
 @Override
     public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            if (ar != null) {
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
          //..
        } else {
         /..
        }
    }
2.1.2 Instrumentation:: execStartActivity
  public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, String target, Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread; //... 
        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess(who);
            int result = ActivityTaskManager.getService().startActivity(whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target, requestCode, 0, null, options);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }
2.1.3 ActivityTaskManager::getService()
    @TestApi
        @SystemService(Context.ACTIVITY_TASK_SERVICE)
        public class ActivityTaskManager { //...
            public static IActivityTaskManager getService() {
                return IActivityTaskManagerSingleton.get();
            }

            @UnsupportedAppUsage(trackingBug = 129726065)
            private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton = new Singleton<IActivityTaskManager>() {
                @Override
                protected IActivityTaskManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                    return IActivityTaskManager.Stub.asInterface(b);
                }
            };
        }

在这里插入图片描述

小结:我们可以看到这里采用了AIDL来作为跨进程通信,底层是用binder机制来实现, 这边获取到 服务端 ActivityTaskManagerService在客户端的代理对象。那么我们可以定位到 服务端 ActivityTaskManagerService的 startActivity方法。从这一部分我们可以看到启动一个新的Activity是一个跨进程的操作,我们每次启动Activity是由 system_server的 ActivityTaskManagerService来为我们实现此功能

2.2 AMS到ApplicationThread的调用过程

这边startActivity实际由 ActivityTaskManagerService来执行,所以我们在将代码定位到 ActivityTaskManagerService.java里,ActivityTaskManagerService是系统进程的服务,能提供给各个应用使用其功能

2.2.1 ActivityTaskManagerService

调用startActivity,最终执行到 startActivityAsUser方法

    @Override
   public final int startActivity(IApplicationThread caller...) {
       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) {
       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)
               .setResolvedType(resolvedType)
               .setResultTo(resultTo)
               .setResultWho(resultWho)
               .setRequestCode(requestCode)
               .setStartFlags(startFlags)
               .setProfilerInfo(profilerInfo)
               .setActivityOptions(bOptions)
               .setMayWait(userId)
               .execute();

   }

我们可以看到 caller是IApplicationThread类型,这个caller一路传过来,指向的是Launcher所在的应用程序的进程的ApplicationThread对象
在这里,进入 getActivityStartController().obtainStarter() 返回的是 ActivityStarter 对象

2.2.2 ActivityStarter:: execute() :: startActivity();

ActivityStarter 是加载Activity的控制类,会收集所有的逻辑来决定如何将Intent和Flags转换为Activity,并将Activity和Task以及Stack相关联。

  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...);
            } else {
                return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent...); //可以先这部分
            }
        } finally {
            onExecutionComplete();
        }
    }
    
       private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity, boolean restrictedBgActivity) {
        int result = START_CANCELED;
        final ActivityStack startedActivityStack;
        try {
            mService.mWindowManager.deferSurfaceLayout();
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
        } finally {
          // ...
        }

        postStartActivityProcessing(r, result, startedActivityStack);

        return result;
    }

最终都会走 startActivityUnchecked

2.2.3 ActivityStarter::startActivityUnchecked()

startActivityUnchecked 方法主要处理与栈管理相关的逻辑

    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity, boolean restrictedBgActivity) {
        setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
                voiceInteractor, restrictedBgActivity);

        final int preferredWindowingMode = mLaunchParams.mWindowingMode;

        computeLaunchingTaskFlags(); //TAG 1

        computeSourceStack();  

        mIntent.setFlags(mLaunchFlags);
        //... TAG2
           if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0
                    || isDocumentLaunchesIntoExisting(mLaunchFlags)
                    || isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
                final TaskRecord task = reusedActivity.getTaskRecord();

                // In this situation we want to remove all activities from the task up to the one
                // being started. In most cases this means we are resetting the task to its initial
                // state.
                final ActivityRecord top = task.performClearTaskForReuseLocked(mStartActivity,
                        mLaunchFlags);
        }
        
        //...
                if (mDoResume) {
            final ActivityRecord topTaskActivity =
                    mStartActivity.getTaskRecord().topRunningActivityLocked();
            if (!mTargetStack.isFocusable()
                    || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                    && mStartActivity != topTaskActivity)) {
                mTargetStack.ensureActivitiesVisibleLocked(mStartActivity, 0, !PRESERVE_WINDOWS);
                mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
            } else {
             
                if (mTargetStack.isFocusable()
                        && !mRootActivityContainer.isTopDisplayFocusedStack(mTargetStack)) {
                    mTargetStack.moveToFront("startActivityUnchecked");
                }
                mRootActivityContainer.resumeFocusedStacksTopActivities(
                        mTargetStack, mStartActivity, mOptions);
            }
        } else if (mStartActivity != null) {
            mSupervisor.mRecentTasks.add(mStartActivity.getTaskRecord());
        }
        mRootActivityContainer.updateUserStack(mStartActivity.mUserId, mTargetStack);

        mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTaskRecord(),
                preferredWindowingMode, mPreferredDisplayId, mTargetStack);

        return START_SUCCESS;
        }

  • TAG1 computeLaunchingTaskFlags()
    这个函数作用:如果调用者不是Activity( ContextImpl等),但是给了一个显式调用要来唤起这个Activity,来根据不同情形配置Intent.FLAGs

  • TAG2
    当找到复用的activity,且启动模式为SingleInstance或SinleTask是,且非栈顶Activity时,先清除该Activity之上的Activity。

Launch Mode

在ActivityInfo 里配置了4类LaunchMode

  • LAUNCH_MULTIPLE(standard):每次启动新Activity,都会创建新的Activity,这是最常见标准情形;
  • LAUNCH_SINGLE_TOP: 当启动新Acitity,在栈顶存在相同Activity,则不会创建新Activity;其余情况同上;
  • LAUNCH_SINGLE_TASK:当启动新Acitity,在栈中存在相同Activity(可以是不在栈顶),则不会创建新Activity,而是移除该Activity之上的所有Activity;其余情况同上;
  • LAUNCH_SINGLE_INSTANCE:每个Task栈只有一个Activity,其余情况同上。

说说几个常见的flag含义:

  • FLAG_ACTIVITY_NEW_TASK:将Activity放入一个新启动的Task;
  • FLAG_ACTIVITY_CLEAR_TASK:启动Activity时,将目标Activity关联的Task清除,再启动新Task,将该Activity放入该Task。该flags跟FLAG_ACTIVITY_NEW_TASK配合使用。
  • FLAG_ACTIVITY_CLEAR_TOP:启动非栈顶Activity时,先清除该Activity之上的Activity。例如Task已有A、B、C3个Activity,启动A,则清除B,C。类似于SingleTop。

对Activity的各种状态判断最终会调用 mRootActivityContainer.resumeFocusedStacksTopActivities();

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

        if (!mStackSupervisor.readyToResume()) {
            return false;
        }

        boolean result = false;
        if (targetStack != null && (targetStack.isTopStackOnDisplay()
                || getTopDisplayFocusedStack() == targetStack)) {
            result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
        //...

        return result;
    }
    

再回到 ActivityStack 的resumeTopActivityUncheckedLocked方法中

2.2.5 ActivityStack.resumeTopActivityUncheckedLocked

这个函数作用是确保当前栈顶最上方的Activity是 resumed状态

    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;
    }
2.2.6 ActivityStack.resumeTopActivityInnerLocked
   private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        if (!mService.isBooting() && !mService.isBooted()) {
            // Not ready yet!
            return false;
        }
        //..
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
        
        }
  • 当找不到需要resume的Activity,则直接回到桌面;
  • 否则,当mResumedActivity不为空,则执行startPausingLocked()暂停该activity;
  • 然后再进入startSpecificActivityLocked环节,接下来从这里继续往下说。

这部分代码非常多,我们只要关注 startSpecificActivityLocked

2.2.7 ActivityStackSupervisor::startSpecificActivityLocked
    void startSpecificActivityLocked(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;
        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;
        }
 
        if (getKeyguardController().isKeyguardLocked()) {
            r.notifyUnknownVisibilityLaunched();
        }

       //..
    }

判断当前的Activity所在的应用程序进程是否已经运行了。针对这段代码if (wpc != null && wpc.hasThread()), 大家可以思考下 Acitivty的所在进程是在什么时候被创建的呢 。
如果进程创建完毕,则继续执行下方代码。

2.2.8 ActivityStackSupervisor::realStartActivityLocked
    boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {
            
                  ...
                        // 创建Activity启动事务
                final ClientTransaction clientTransaction = ClientTransaction.obtain(
                        proc.getThread(), r.appToken);

                final DisplayContent dc = r.getDisplay().mDisplayContent;
                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);
                ..
            }

这个 ClientTransaction保存一系列事务的容器,这些事务可能被发送到客户端。这包括一个回调列表和一个最终的生命周期状态,然后最终我们可以看到由 mService.getLifecycleManager() 来发送这个事务,
这里有 LaunchActivityItemResumeActivityItemPauseActivityItem. 这些要注意一下,实际上就是客户端的消息体,客户端根据这些item来完成不同的事务

2.2.9 ClientLifecycleManager::scheduleTransaction

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();
        }
    }
    

IApplicationThread 实际上就是目标进程的ApplicationThread在ATMS中的代理对象,由于是跨进程通信,我们知道binder中通过代理对象来完成,这里也是如此,实际上走的是 ApplicationThread 的scheduleTransaction方法。
ApplicationThread是ActivityThread中的一个内部类,

public final class ActivityThread extends ClientTransactionHandler {
  ...
 private class ApplicationThread extends IApplicationThread.Stub {
 ...
 }
 }

大家看到这个 ActivityThread 不要被名字迷惑到,它管理应用程序进程中主线程的执行、调度和执行Activity、广播以及Activity相关请求的一些操作。

到目前为止我们已经走完了Activty启动在ATMS的整个流程,我们从目标进程(launcher进程或者一个应用程序) 到systemServer进程转了一圈,现在要到应用程序中了。
来我们继续往下看

2.3 ActivityThread启动Activity的过程

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

这里调用的是ActivityThread父类ClientTransactionHandler的方法

2.3.2 ClientTransactionHandler:: scheduleTransaction

准备和计划事务的执行

    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
    
2.3.3 ActivityThread.H::handleMessage()

H 是ActivityThread的内部类,继承Handler,用来处理消息

 class H extends Handler {
      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()) {
                    //在客户端回收系统进程中的客户端事务,而不是ClientLifecycleManager,以避免在处理此消息之前被清除。
                        transaction.recycle();
                    }
                    // TODO(lifecycler): Recycle locally scheduled transactions.
                    break;    
          
            }
            Object obj = msg.obj;
            if (obj instanceof SomeArgs) {
                ((SomeArgs) obj).recycle();
            }
            if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
        }
    }
    ... }
    

继续看mTransactionExecutor.execute(transaction);

2.3.4 TransactionExecutor::execute

解决事务。首先,所有回调将按照它们在列表中出现的顺序执行。如果回调需要某种执行前或执行后的状态,客户端将相应地转换。

   public void execute(ClientTransaction transaction) {
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Start resolving transaction");

        final IBinder token = transaction.getActivityToken();
        if (token != null) {
            final Map<IBinder, ClientTransactionItem> activitiesToBeDestroyed =
                    mTransactionHandler.getActivitiesToBeDestroyed();
            final ClientTransactionItem destroyItem = activitiesToBeDestroyed.get(token);
            if (destroyItem != null) {
                if (transaction.getLifecycleStateRequest() == destroyItem) {
                    // It is going to execute the transaction that will destroy activity with the
                    // token, so the corresponding to-be-destroyed record can be removed.
                    activitiesToBeDestroyed.remove(token);
                }
                if (mTransactionHandler.getActivityClient(token) == null) {
                    // The activity has not been created but has been requested to destroy, so all
                    // transactions for the token are just like being cancelled.
                    Slog.w(TAG, tId(transaction) + "Skip pre-destroyed transaction:\n"
                            + transactionToString(transaction, mTransactionHandler));
                    return;
                }
            }
        }

        if (DEBUG_RESOLVER) Slog.d(TAG, transactionToString(transaction, mTransactionHandler));

        executeCallbacks(transaction);

        executeLifecycleState(transaction);
        mPendingActions.clear();
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
    }
    

executeCallbacks(transaction); 循环通过回调请求的所有状态,并在适当的时间执行它们。

2.3.5 TransactionExecutor:: executeCallbacks
    @VisibleForTesting
    public void executeCallbacks(ClientTransaction transaction) {
    ...
      final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Resolving callback: " + item);
            final int postExecutionState = item.getPostExecutionState();
            final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
                    item.getPostExecutionState());
            if (closestPreExecutionState != UNDEFINED) {
                cycleToPath(r, closestPreExecutionState, transaction);
            }

            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            if (r == null) {
                // Launch activity request will create an activity record.
                r = mTransactionHandler.getActivityClient(token);
            }

            if (postExecutionState != UNDEFINED && r != null) {
                // Skip the very last transition and perform it by explicit state request instead.
                final boolean shouldExcludeLastTransition =
                        i == lastCallbackRequestingState && finalState == postExecutionState;
                cycleToPath(r, postExecutionState, shouldExcludeLastTransition, transaction);
            }
        }
    }

在这里取出每一个 ClientTransactionItem 的对象,

2.3.6 LaunchActivityItem:: execute
   @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
        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 */); //1
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }

LaunchActivityItem实现了Parcelable ,实际上是一个 Parcelable对象,才能让它在进程间传递

注释1处ActivityClientRecord是ActivityThread的一个内部类 ,实际调用的是 ActivityThread 的handleLaunchActivity

2.3.7 ActivityThread::handleLaunchActivity
    @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        //如果在后台处理gc,会跳过此Activity,保证Activity被创建
        unscheduleGcIdler();
        mSomeActivitiesChanged = true;
        if (r.profilerInfo != null) {
            mProfiler.setProfiler(r.profilerInfo);
            mProfiler.startProfiling();
        }
        handleConfigurationChanged(null, null);
        if (localLOGV) Slog.v(
            TAG, "Handling launch of " + r);
        // 初始化硬件加速渲染器
        if (!ThreadedRenderer.sRendererDisabled
                && (r.activityInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
            HardwareRenderer.preload();
        }
        //初始化wms
        WindowManagerGlobal.initialize();
        // Hint the GraphicsEnvironment that an activity is launching on the process.
        GraphicsEnvironment.hintActivityLaunch();
        //最终回调目标Activity的onCreate
        final Activity a = performLaunchActivity(r, customIntent);

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            reportSizeConfigurations(r);
            if (!r.activity.mFinished && pendingActions != null) {
                pendingActions.setOldState(r.state);
                pendingActions.setRestoreInstanceState(true);
                pendingActions.setCallOnPostCreate(true);
            }
        } else {
        //存在error则停止该Activity
            try {
                ActivityTaskManager.getService()
                        .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                                Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        }
        return a;
    }
    

handleLaunchActivity 这个方法是提供给服务端需要启动或者重启Activity的时候使用,

2.3.8 ActivityThread::performLaunchActivity

这是Activity启动的核心部分了

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ActivityInfo aInfo = r.activityInfo; //获取AcitivityInfo对象
        if (r.packageInfo == null) { //获取APK文件的描述类LoadeApk
            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                    Context.CONTEXT_INCLUDE_CODE);
        }

        ComponentName component = r.intent.getComponent(); //创建要启动Activity的上下文环境
        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 appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader(); //用类加载器来创建该Activity的实例
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            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 app = r.packageInfo.makeApplication(false, mInstrumentation);//创建Application

            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(mCompatConfiguration);
                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;
                }
                appContext.setOuterContext(activity); 
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback,
                        r.assistToken); //初始化Activity

                if (customIntent != null) {
                    activity.mIntent = customIntent;
                }
                r.lastNonConfigurationInstances = null;
                checkAndBlockForNetworkAccess();
                activity.mStartedActivity = false;
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    activity.setTheme(theme);
                }

                activity.mCalled = false;
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); //调用Activity的onCreate
                } else {
                    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;
            }
            r.setState(ON_CREATE);
            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;
    }
    

到此,正式进入了Activity的onCreate, onStart, onResume这些生命周期的过程。

Activity进程内启动

在这里插入图片描述

Activity进程内启动只涉及到两个进程的通信。理解了Activity跨进程的启动,自然而然进程内部启动也就了解了,这里就不细讲了。

三、总结

本文详细的介绍了Activity的跨进程启动的整个流程,对于题目一开始提出的问题是不是能回答上一些了呢,如果面试中或者业务中遇到类似的问题,是不是能想出更有充分的解决方案呢。对于Activity窗口的问题还有插件化相关如何hook Activity将在后续的文章进行讲解,敬请期待。

对于AIDL和Android Binder机制还不是很了解的小伙伴可以看看以下文章

跨进程通信以及AIDL的使用
ServiceManager启动
获取ServiceManager

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值