当前位置:   article > 正文

Android Activity 的启动流程_android startactivity

android startactivity

Activity 的启动流程

这里我们以API 28 版本为例。源码太长,文中的代码片段都为截取重要部分。

首先我们从Activity 的startActivity()开始,

  1. //Activity.java
  2. public void startActivity(Intent intent) {
  3.     this.startActivity(intent, null);
  4. }

这里调用了一个重载方法,statActivity(Intent intent,Bundle options)

  1. @Override
  2. public void startActivity(Intent intent, @Nullable Bundle options) {
  3.    ......
  4.         startActivityForResult(intent, -1);
  5.        ......
  6. }

接着我们来到了startActivityForResult() 方法

  1. public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
  2.         @Nullable Bundle options) {
  3.     ......
  4.         Instrumentation.ActivityResult ar =
  5.             mInstrumentation.execStartActivity(
  6.                 this, mMainThread.getApplicationThread(), mToken, this,
  7.                 intent, requestCode, options);
  8.      ......
  9.  }

可以看到最终走到了Instrumentation 的execStartActivity() 方法里。

  1. //Instrumentation.java
  2. public ActivityResult execStartActivity(
  3. Context who, IBinder contextThread, IBinder token, Activity target,
  4. Intent intent, int requestCode, Bundle options) {
  5. IApplicationThread whoThread = (IApplicationThread) contextThread;
  6. ......
  7. int result = ActivityManager.getService()
  8. .startActivity(whoThread, who.getBasePackageName(), intent,
  9. intent.resolveTypeIfNeeded(who.getContentResolver()),
  10. token, target != null ? target.mEmbeddedID : null,
  11. requestCode, 0, null, options);
  12. ......
  13. }

这里有个参数我们需要注意一下,IBinder contexThread, 可以看到这里是个IBinder对象是用来进程间通信的,可以看到传入的参数是mMainThread.getApplicationThread(),

mMainThread 是AcitivityThread的实例,AcitivityThread维护着main()方法,是应用程序的入口,它管理着应用程序的主线程,内部封装着Acitivity、BroadcastRecevier、Service的启动、切换等操作,但是它不是独立完成这份工作的,以上行为的调度都需要通过系统服务ActivityManagerService来进行。

MainThread的内部类ApplicationThread继承了IApplicationThread.Stub,可以用来进程间通信,实际上应用程序同系统服务ActivityManagerService 的交互正是通过ApplicationThread来进行的,我们应用页面的启动、广播的发送、服务的启动都要通过ApplicationThread 和ActivityMamangerService的通信来进行。

介绍下Instrumentation, Instrumentation 译名为仪表盘,它早于应用Application 初始化,所以可以用来监控系统同应用的交互。我们来看它的类结构

发现它的大部分方法都和应用Application 的创建和生命周期回调、Activity 创建以及生命周期回调有关,后面我们也会看到它在Activity 启动流程中的作用。

我们继续往下走,这里代码来到了ActivityManager.getService().startActivity(),

  1. //ActivityManager.java
  2. public static IActivityManager getService() {
  3.     return IActivityManagerSingleton.get();
  4. }
  5. private static final Singleton<IActivityManager> IActivityManagerSingleton =
  6.         new Singleton<IActivityManager>() {
  7.             @Override
  8.             protected IActivityManager create() {
  9.                 final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
  10.                 final IActivityManager am = IActivityManager.Stub.asInterface(b);
  11.                 return am;
  12.             }
  13.         };

 ActivityManager.getService() 这里获取的是一个IActivityManager的单例对象,从单例对象创建的方法中我们可以看到获取了ActivityService系统服务IBinder对象,然后将其转为了IActivityManager, 那么获取的这个系统服务对象到底是谁呢?

其实这个系统服务对象就是我们上文提到的ActivityManagerService(AMS)

  1. public class ActivityManagerService extends IActivityManager.Stub
  2.         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {}

ActivityManagerService 系统服务是android 系统最重要的服务之一,负责着四大组件的启动、切换、调度以及应用程序的管理和调度,可以说没有它,我们应用的正常运行就无从谈起,回归正题,代码调用来到了ActivityManagerService 的startActivity() 方法,

从这里我们就从我们的应用程序进程通过IPC 通信来到了ActivityManagerSerice所在的进程

  1. //ActivityManagerService.java
  2. public final int startActivity(IApplicationThread caller, String callingPackage,
  3.             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
  4.             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
  5.         return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
  6.                 resultWho, requestCode, startFlags, profilerInfo, bOptions,
  7.                 UserHandle.getCallingUserId());
  8. }

这里调用了startActivityAsUser()方法,然后又调用了一个重载方法来到了

  1. //ActivityManagerService.java
  2. public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
  3.             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
  4.             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
  5.             boolean validateIncomingUser) {
  6.     ......
  7.         return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
  8.                 .setCaller(caller)
  9.                 .setCallingPackage(callingPackage)
  10.                 .setResolvedType(resolvedType)
  11.                 .setResultTo(resultTo)
  12.                 .setResultWho(resultWho)
  13.                 .setRequestCode(requestCode)
  14.                 .setStartFlags(startFlags)
  15.                 .setProfilerInfo(profilerInfo)
  16.                 .setActivityOptions(bOptions)
  17.                 .setMayWait(userId)
  18.                 .execute();
  19.     }

可以看到通过mActivityStartController 对象获取了一个ActivityStarter 对象,ActivityStartController 是个用来代理Activity 启动的控制器,ActivtyStarter 也是一个控制器用来解释一个Activity 要如何被启动, 我们看下execute()方法

  1. //ActivityStarter.java
  2. int execute() {
  3.         try {
  4.             // TODO(b/64750076): Look into passing request directly to these methods to allow
  5.             // for transactional diffs and preprocessing.
  6.             if (mRequest.mayWait) {
  7.                 return startActivityMayWait(mRequest.caller, mRequest.callingUid,
  8.                         mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
  9.                         mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
  10.                         mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
  11.                         mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
  12.                         mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
  13.                         mRequest.inTask, mRequest.reason,
  14.                         mRequest.allowPendingRemoteAnimationRegistryLookup);
  15.             } else {
  16.                 return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
  17.                         mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
  18.                         mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
  19.                         mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
  20.                         mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
  21.                         mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
  22.                         mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
  23.                         mRequest.outActivity, mRequest.inTask, mRequest.reason,
  24.                         mRequest.allowPendingRemoteAnimationRegistryLookup);
  25.             }
  26.         } finally {
  27.             onExecutionComplete();
  28.         }
  29.     }

可以看到有个判断,如果mRequest.mayWait为true, 则执行startActivityMayWait(),否则执行startActivity(),  这里我们只需要关注startActivityMayWait(), 因为在我们获取ActivityStarter 对象时调用了setMayWait()方法,mayWait 字段则被设为了true.

  1. //ActivityStarter.java
  2. private int startActivityMayWait(IApplicationThread caller, int callingUid,
  3.         String callingPackage, Intent intent, String resolvedType,
  4.         IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
  5.         IBinder resultTo, String resultWho, int requestCode, int startFlags,
  6.         ProfilerInfo profilerInfo, WaitResult outResult,
  7.         Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
  8.         int userId, TaskRecord inTask, String reason,
  9.         boolean allowPendingRemoteAnimationRegistryLookup) {
  10.     // Refuse possible leaked file descriptors
  11.    ......
  12.         final ActivityRecord[] outRecord = new ActivityRecord[1];
  13.         int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
  14.                 voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
  15.                 callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
  16.                 ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
  17.                 allowPendingRemoteAnimationRegistryLookup);
  18.         ......
  19.         return res;
  20.     }
  21. }

接着调用了startActivity()重载方法,创建了目标活动Activity 的ActivitRcord对象,

  1. //ActivityStarter.java
  2.   private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
  3.             String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
  4.             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
  5.             IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
  6.             String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
  7.             SafeActivityOptions options,
  8.             boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
  9.             TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {
  10.       ......
  11.         ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
  12.                 callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
  13.                 resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
  14.                 mSupervisor, checkedOptions, sourceRecord);
  15.        
  16.         return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
  17.                 true /* doResume */, checkedOptions, inTask, outActivity);
  18.     }

最终来到了startActivityUnChekced()方法,

  1. //AcitivityStarter.java
  2. private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
  3.             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
  4.             int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
  5.             ActivityRecord[] outActivity) {
  6.        ......
  7.         computeLaunchingTaskFlags();
  8.         computeSourceStack();
  9.         if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
  10.                 && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
  11.             newTask = true;
  12.             result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack);
  13.         } else if (mSourceRecord != null) {
  14.             result = setTaskFromSourceRecord();
  15.         } else if (mInTask != null) {
  16.             result = setTaskFromInTask();
  17.         } else {
  18.             setTaskToCurrentTopOrCreateNewTask();
  19.         }
  20.         mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
  21.                 mOptions);
  22.            ......
  23.         mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
  24.                         mOptions);
  25.         return START_SUCCESS;
  26.     }

这里我们要理解几个相关类,ActivityStackSupervisor,ActivityStack,TaskRecord,ActivityRecord。

我们从小往大的开始说,ActivityRecord : 当我们启动Actitivity 或者关闭Activity 时,我们经常说这个活动入栈或者出栈了,那到底是什么入栈出栈了呢?就是ActivityRecord对象,Android 系统中用ActivityReocrd来表示Activity, 每一个正在运行的Activity 都对应着一个ActivityReocrd 对象,它存储着Activity 的状态信息包括标识符、所属任务栈、进程信息、启动模式、可见性等。

TaskRecord 任务栈,他是用来表示任务的类,主要用于存储和管理任务的状态信息,帮助系统进行任务的管理和调度,他有几个属性我们可以关注下,affinity  就是我们在清单文件里指定的taskAffinity, ArrayList<ActitivityRecord> mActivities 就是运行在当前任务的所有活动集合,mStack 指的是当前任务所在的活动堆栈。在任务中的Activity是按照入栈出栈的方式管理的。

ActivityStack 活动堆栈, 顾名思义,他是真正用来管理活动入栈出栈的类,他是TaskRecord 和ActivityRecord 的统一上司,管理着一个或多个任务栈,也负责着活动的创建、启动、移除、切换的等调度,ActivityStack 维护着TaskRecord列表同时也记录着当前同用户交互的活动和正在暂停的活动ActivityRecord。

ActivityStackSupervisor, 活动堆栈的管理者,他维护着设备中存在的活动堆栈的信息,譬如 mHomeStack 桌面应用的活动堆栈、mFocusedStack 当前同用户交互的活动堆栈等。

在没有开启多任务的应用程序中,他们的对应关系大致如下:

接着说回startActivityUnChekced() 方法,

这个方法主要做了几件事:

1. computeLaunchingTaskFlag(), 主要是为了计算启动活动的启动标记位launchFlags,不同的标记位决定了目标ActivitRecord最终会放在哪一个TaskRecord中,这里分几种步骤:

  •       如果来源ActivityReocrd 为null,即并不是从Activity 启动的,但是指定了目标ActivityRecord 的入栈mInTask,这时如果目标ActivityRecord 的意图指定了FLAG_ACTIVITY_NEW_TASK,说明目标活动要在一个新的任务栈中,那么确定任务栈标记mAddingToTask 为false 否则为true, 同时将指定入栈mInTask 赋值给mReuseTask
  •     如果来源ActivityReocrd不为null, 将指定入栈mInTask置为null并且将是否加入栈标记mAddingToTask 设置为true ;
  •       如果目标ActivityRecord 的指定入栈不存在并且来源ActivityRecord 为null, 说明目标Activity 的启动并不是由另外一个Activity 启动的,所以标记位需要设置为FLAG_ACTIVITY_NEW_TASK,也就是新创建一个Task, 
  •       如果启动目标Activity的Activity 存在并且其启动模式是SingleInstance,则目标Actiivty的启动标记位同样要设置为FLAG_ACTIVITY_NEW_TASK;
  •      如果目标Activity 的入栈不存在并且目标Activity 的启动模式是SingleInstance 或者SingleTask, 则目标Actiivty的启动标记位同样要设置为FLAG_ACTIVITY_NEW_TASK;

2.创建新的TaskRecord 或者复用来源Activity 指定的TaskRecord:

  •       如果来源Activity 为空、指定的入栈为空、确定任务栈标记mAddingToTask为false并且目标Activity的启动标记位是FLAG_ACTIVITY_NEW_TASK,调用setTaskFromReuseOrCreateNewTask(), 这里需要看computeLaunchingTaskFlag() 中是否指定了mReuseTask,如果未指定,则新创建TaskRecord, 然后将TaskRecord加入到栈中,最后将目标ActivityRecord 加入到TaskRecord顶部;
  •      如果来源ActivityReocrd 不为空,则将目标ActivityRecord 加入来源ActivityRecord 的TaskReocrd的顶部;
  •        指定入栈不为null , 将目标ActivityRecord 加入指定的TaskReocrd的顶部;

3. 调用目标ActivityReocrd 所在的ActivityStack 中方法 startActivityLocked(),这里主要是通过调用insertTaskAtTop()方法将目标ActivityReocrd 所在TaskRecord 移动到栈顶。

  1.    //AcitivityStack.java
  2.   void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,
  3.             boolean newTask, boolean keepCurTransition, ActivityOptions options) {
  4. ......
  5.             insertTaskAtTop(rTask, r);
  6. ......
  7.         }
  8.     }

4. 调用ActivityStackSupervisor 的 resumeFocusedStackTopActivityLocked() 方法

  1.   //AcitivityStackSupervisor.java
  2.     boolean resumeFocusedStackTopActivityLocked(
  3.             ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
  4. ......
  5.             mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
  6.        ......
  7.         return false;
  8. }

上面我们来到了ActivityStack 的 resumeTopActivityUncheckedLocked() 方法,里面调用了resumeTopActivityInnerLocked()方法,

  1.   //AcitivityStack.java
  2.   private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
  3.       ......
  4. if (mResumedActivity != null) {
  5.             if (DEBUG_STATES) Slog.d(TAG_STATES,
  6.                     "resumeTopActivityLocked: Pausing " + mResumedActivity);
  7.             pausing |= startPausingLocked(userLeaving, false, next, false);
  8.         }
  9.          mStackSupervisor.startSpecificActivityLocked(next, true, true);
  10.         return true;
  11.     }

这里有一点要注意的是这里我们调用了一个startPausingLocked ()方法, 如果当前获取焦点的Activity不为null, 我们还要暂停它,最终调用了当前活动的onPause()  方法,也就是说在开启新的Activity之前要先暂停当前Activity,所以为了使新启动的Activity 更快的启动,我们不要在onPause()  方法中做过多的操作。

最终我们又回到了ActivityStackSupervisor中,我们看下startSpecificActivityLocked( )方法

  1. //AcitivityStackSupervisor.java
  2.   void startSpecificActivityLocked(ActivityRecord r,
  3.             boolean andResume, boolean checkConfig) {
  4.         // Is this activity's application already running?
  5.         ProcessRecord app = mService.getProcessRecordLocked(r.processName,
  6.                 r.info.applicationInfo.uid, true);
  7.         if (app != null && app.thread != null) {
  8.             try {
  9.                 if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
  10.                         || !"android".equals(r.info.packageName)) {
  11.              ......
  12.                 realStartActivityLocked(r, app, andResume, checkConfig);
  13.                 return;
  14.             } catch (RemoteException e) {
  15.                 Slog.w(TAG, "Exception when starting activity "
  16.                         + r.intent.getComponent().flattenToShortString(), e);
  17.             }
  18.         }
  19.         mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
  20.                 "activity", r.intent.getComponent(), false, false, true);
  21.     }

这个 方法中判断了我们目标ActivityReocrd 所在进程是否存在,如果不存在,则需要ActivityManagerService创建进程,如果存在则调用 realStartActivityLocked(), 这里我们先假设应用进程已经存在,然后我们看下realStartActivityLocked() 方法。

  1.   //AcitivityStackSupervisor.java
  2.   final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
  3.             boolean andResume, boolean checkConfig) throws RemoteException {
  4.        ......
  5.                 // Create activity launch transaction.
  6.                 final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread, r.appToken);
  7.                 clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),...));
  8.                mService.getLifecycleManager().scheduleTransaction(clientTransaction);
  9.                ......
  10.         return true;
  11.     }

这里我们创建了一个事务,可以看到创建事务的时候需要将目标应用的ApplicationThread 作为参数

  1. //ClientTransaction.java
  2. public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
  3.         ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
  4.         if (instance == null) {
  5.             instance = new ClientTransaction();
  6.         }
  7.         instance.mClient = client;
  8.         instance.mActivityToken = activityToken;
  9.         return instance;
  10.     }

并且给了事务一个LaunchActivtyItem 的回调callBack,然后调用AMS 中的ClientLifecycleManager 执行了该事务。

  1. //ClientLifecyleManager.java
  2. void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
  3.         final IApplicationThread client = transaction.getClient();
  4.         transaction.schedule();
  5.         ……
  6.     }

这里调用了事务的schedule()方法,

  1. //ClientTransaction.java
  2. public void schedule() throws RemoteException {
  3.         mClient.scheduleTransaction(this);
  4.     }

这里的mClient 是我们创建事务的时候传入的app.thread,它是目标进程的ApplicationThread对象, 这时候我们终于从ActivityManagerService 来到了目标进程的ApplicationThread。

  1. //ApplicationThread.java
  2. public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
  3.             ActivityThread.this.scheduleTransaction(transaction);
  4. }

ApplicationThread 是ActivityThread 的内部类,它直接调用了ActivityThread 的scheduleTransaction() 方法, 有没有在ActivityThread 找这个方法没有找到的童鞋呢,其实这个方法是定义在抽象类ClientTransactionHandler 中的,ActivityThread 继承了这个类,我们看下这个方法

  1. //ActivityThread.java
  2. void scheduleTransaction(ClientTransaction transaction) {
  3.         transaction.preExecute(this);
  4.         sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
  5. }

来到了ActivityThread 的sendMessage() 方法,通过ActivityThread 维护的Handler mH 发送了 标记 为ActivityThread.H.EXECUTE_TRANSACTION 的消息,接着我们来到Handler 的handleMessage方法中,

  1. void handleMessage(Message msg){
  2.   
  3. case EXECUTE_TRANSACTION:
  4.                     final ClientTransaction transaction = (ClientTransaction) msg.obj;
  5.                     mTransactionExecutor.execute(transaction)
  6.                     break;
  7. }

可以看到这里用TransactionExecutor 对象调用了execute 执行了启动Activity的事务,TransactionExecutor 是ActivityThread 的一个属性,TransactionExecutor mTransactionExecutor = new TransactionExecutor(this), 可以看到它的构造函数中需要ClientTransactionHandler 作为参数,而ActivityThread 正好继承了ClientTransactionHandler. 接着往下走,

  1. // TransactionExecutor.java
  2. public void execute(ClientTransaction transaction) {
  3. ……
  4.  executeCallbacks(transaction);
  5. }

  1. public void executeCallbacks(ClientTransaction transaction) {
  2.         final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
  3.         if (callbacks == null) {
  4.             // No callbacks to execute, return early.
  5.             return;
  6.         }
  7.         final int size = callbacks.size();
  8.         for (int i = 0; i < size; ++i) {
  9.             final ClientTransactionItem item = callbacks.get(i);
  10.             ......
  11.             item.execute(mTransactionHandler, token, mPendingActions);
  12.             item.postExecute(mTransactionHandler, token, mPendingActions);
  13.             ......
  14.         }
  15.     }

还记得我们创建事务的时候传入的callBack LaunchActivityItem 吗? 这里饶了一大圈就是调用了它的execute() 方法

  1. //LaunchActivityItem.java
  2.    public void execute(ClientTransactionHandler client, IBinder token,
  3.             PendingTransactionActions pendingActions) {
  4.         ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
  5.                 mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
  6.                 mPendingResults, mPendingNewIntents, mIsForward,
  7.                 mProfilerInfo, client);
  8.         client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
  9. }

可以看到这里调用了ClientTransactionHandler 的handleLaunchActivity() 方法,我们上文提到过ActivityThead 继承了ClicentTransactionHandler,所以这里来到了ActivityThread 的handleLaunchActivity() 方法

  1. //ActivityThread.java
  2. public Activity handleLaunchActivity(ActivityClientRecord r,
  3.             PendingTransactionActions pendingActions, Intent customIntent) {
  4.         ......
  5.         final Activity a = performLaunchActivity(r, customIntent);
  6.         ......
  7.         return a;
  8. }

这里来到了performLauncherActivity()方法

  1. //ActivityThread.java
  2.    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
  3. //创建上下文
  4.         ContextImpl appContext = createBaseContextForActivity(r);
  5.         Activity activity = null;
  6. java.lang.ClassLoader cl = appContext.getClassLoader();
  7. //创建Activity
  8.             activity = mInstrumentation.newActivity(
  9.                     cl, component.getClassName(), r.intent);
  10.         try {
  11.             Application app = r.packageInfo.makeApplication(false, mInstrumentation);
  12. //绑定上下文,创建PhoneWindow
  13.                 activity.attach(appContext, this, getInstrumentation(), r.token,
  14.                         r.ident, app, r.intent, r.activityInfo, title, r.parent,
  15.                         r.embeddedID, r.lastNonConfigurationInstances, config,
  16.                         r.referrer, r.voiceInteractor, window, r.configCallback);
  17. //调用Activity onCreate()
  18.                     mInstrumentation.callActivityOnCreate(activity, r.state);
  19.                 r.activity = activity;
  20.             }
  21.           ......
  22.         return activity;
  23.     }

这个方法中给目标Activity创建上下文Context, 通过Instrumentation.newActivity()创建目标Activity实例, 通过目标Activity attach() 方法和上下文绑定并且创建PhoneWindow,通过Instumentation.callActivityOnCreate() 调用目标Activity 的生命周期onCreate()方法,至此 一个Activity 的算是被启动了。

整理的启动流程图如下,以作参考 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/680197
推荐阅读
相关标签
  

闽ICP备14008679号