Posts app 启动流程分析-2
Post
Cancel

app 启动流程分析-2

源码 基于 android 8.0

从 ActivityThread 的 main() 方法执行到页面显示

开篇之前,先思考以下几个问题

  • Q1: Application 是如何创建的?
  • Q2: Application 的 attachBaseContext() 为什么会在 onCreate() 方法之前调用?
  • Q3: Activity 是如何被创建的?
  • Q4: Activity 的生命周期方法是如何被调用的?
  • Q5: PhoneWindow 是何时被创建的?
  • Q6: ContextImpl 是何时被创建的?
  • Q7: ViewRootImpl 是何时被创建的?
  • Q8: app 启动过程中,app 和 AMS 交互了多少次?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Launcher 中 app 图标的点击事件是由 ItemClickHandler 来处理的
ItemClickHandler#onClick() -> onClickAppShortcut() -> startAppShortcutOrInfoActivity() ->
Launcher 是 Activity 的子类
Launcher#startActivitySafely() -> startShortcutIntentSafely() -> 
Activity#startActivity() -> startActivityForResult() -> 
Instrumentation#execStartActivity() -> 
app 进程第一次与 AMS 交互:Launcher#startActivity()
AMS#startActivity() -> startActivityAsUser() -> 
ActivityStarter#execute() -> startActivityMayWait() -> startActivity() -> startActivity() ->
startActivity() -> startActivityUnchecked() -> startActivityLocked() 这里没有实质性地进展,看下面方法
ActivityStackSupervisor#resumeFocusedStackTopActivityLocked() ->
ActivityStack#resumeTopActivityUncheckedLocked() -> 
注意:这个方法会进入两次,第一次是 pause 上一个 activity,在 if (pausing && !resumeWhilePausing) 处返回 true,
第二次才是启动当前 activity,当然若 activity 所在进程未启动,则会先启动该进程然后启动 activity
resumeTopActivityInnerLocked() ->
注意这个方法:①若进程未启动会先启动进程,②进程启动后会调用 realStartActivityLocked() 方法启动 activity
这里以 ① 流程为例分析
ActivityStackSupervisor#startSpecificActivityLocked() ->
应用进程未启动时,先启动进程
AMS#startProcessLocked() -> startProcessLocked() -> newProcessRecordLocked() -> startProcessLocked() ->
在这里会设置启动类 entryPoint = android.app.ActivityThread
startProcessLocked() -> startProcessLocked() -> mProcStartHandler.post() -> 
Runnable#run() -> AMS#startProcess() -> 
Process#start() -> 
ZygoteProcess#start() -> startViaZygote() ->
这里会通过 socket 与 zygote 进程通信,将参数发送给 zygote 进程并读取返回结果
zygoteSendArgsAndGetResult() -> 返回到 AMS#startProcessLocked()
进程启动后,会执行到 ActivityThread#main() 方法中,在 main() 中执行 attach() 操作
ActivityThread#main() -> attach() -> mgr.attachApplication()
app 进程第二次与 AMS 交互:AMS#attachApplication()
AMS#attachApplication() -> attachApplicationLocked() -> thread.bindApplication()
  app 进程第三次与 AMS 交互:AppT#bindApplication()
  ActivityThread.ApplicationThread#bindApplication() -> mH.send(H.BIND_APPLICATION) ->
  handleBindApplication() -> 如果是 debug 模式:mgr.showWaitingForDebugger() 第四次与 AMS 交互
ActivityStackSupervisor#attachApplicationLocked() -> realStartActivityLocked() ->
接下来启动 Activity
LaunchActivityItem.obtain()/ResumeActivityItem.obtain()
app 进程第五次与 AMS 交互:启动 Activity
AMS#.getLifecycleManager().scheduleTransaction() -> AppT#scheduleTransaction() -> 分别执行
handleLaunchActivity() 和 handleResumeActivity()

首先来一张价值五千万(两包小江山)的时序图

uml

接下来分析具体流程

  • 1, ActivityThread#main()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    public static void main(String[] args) {
      // ... 省略部分代码
      // 设置进程名
      Process.setArgV0("<pre-initialized>");
      // 2, 准备主线程的 Looper, 也就是我们常说的 Looper.getMainLooper()
      Looper.prepareMainLooper();
    
      // 实例化主线程,在构造器里会初始化 ResourceManager
      ActivityThread thread = new ActivityThread();
      // 执行绑定操作
      thread.attach(false /*system*/);
    
      // 初始化主线程 handler
      if (sMainThreadHandler == null) {
          sMainThreadHandler = thread.getHandler();
      }
      if (false) {
          // 设置主线程 Looper 的 Printer 可以用来监控 Handler.dispatchMessage() 方法执行
          Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));
      }
      // 开启主线程消息循环
      Looper.loop();
      throw new RuntimeException("Main thread loop unexpectedly exited");
    }
    
  • 4, attach()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    
    private void attach(boolean system) {
      sCurrentActivityThread = this;
      mSystemThread = system;
      if (!system) {
          // 对 ViewRootImpl 进行一些配置
          ViewRootImpl.addFirstDrawHandler(new Runnable() {
              @Override
              public void run() {
                  ensureJitEnabled();
              }
          });
          android.ddm.DdmHandleAppName.setAppName("<pre-initialized>", UserHandle.myUserId());
          RuntimeInit.setApplicationObject(mAppThread.asBinder());
          final IActivityManager mgr = ActivityManager.getService();
          try {
              // AMS 绑定当前 thread,用于进程间通信,mAppThread 是 ApplicationThread 的一个实例
              // 具体实现里面有对 Activity 的各种操作: create//start/resume...
              mgr.attachApplication(mAppThread);
          } catch (RemoteException ex) {
              throw ex.rethrowFromSystemServer();
          }
          // Watch for getting close to heap limit.
          BinderInternal.addGcWatcher(new Runnable() {
              @Override public void run() {
                  if (!mSomeActivitiesChanged) {
                      return;
                  }
                  Runtime runtime = Runtime.getRuntime();
                  long dalvikMax = runtime.maxMemory();
                  long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
                  // 当前 app 的使用内存如果超出分配内存的 75% 会对部分 Activity 进行释放操作
                  if (dalvikUsed > ((3*dalvikMax)/4)) {
                      mSomeActivitiesChanged = false;
                      try {
                          // 当内存过低时会释放一部分 activity
                          mgr.releaseSomeActivities(mAppThread);
                      } catch (RemoteException e) {
                          throw e.rethrowFromSystemServer();
                      }
                  }
              }
          });
      } else {
          // ... 猜测 system = true 是跟系统有关的逻辑,现在只关心跟用户有关的逻辑
      }
      // 当全局配置发生改变时会先回调到这里来,再由 handler 发消息通知 Activity
      // 比如系统语言、时区改变,横竖屏切换等
      ViewRootImpl.ConfigChangedCallback configChangedCallback = (Configuration globalConfig) -> {
          synchronized (mResourcesManager) {
              // We need to apply this change to the resources immediately, because upon returning
              // the view hierarchy will be informed about it.
              if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig, null /* compat */)) {
                  updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
                          mResourcesManager.getConfiguration().getLocales());
                  // This actually changed the resources! Tell everyone about it.
                  if (mPendingConfiguration == null || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
                      mPendingConfiguration = globalConfig;
                      // 发消息通知 activity 配置发生变化了,activity 收到消息后会再通过 FragmentManager 
                      // 通知 Fragment, 再由 Fragment 向子 Fragment 传递
                      sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
                  }
              }
          }
      };
      ViewRootImpl.addConfigCallback(configChangedCallback);
    }
    
  • 5, AMS#attachApplication(IApplicationThread thread) -> 6, AMS#attachApplicationLocked(IApplicationThread thread, int pid)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    
    private final boolean attachApplicationLocked(IApplicationThread thread, int pid) {
      ProcessRecord app;
      // ... 记录 app 各种状态及属性赋值
      try {
          // 非 debug 模式,后面会用到
          int testMode = ApplicationThreadConstants.DEBUG_OFF;
          // ...
          if (app.instr != null) {
              // debug 模式下也调用 thread.bindApplication() 方法,传参不同
          } else {
              // 非 debug 模式
              // 7, thread.bindApplicaiion()
              thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
                      null, null, null, testMode, mBinderTransactionTrackingEnabled, 
                      enableTrackAllocation, isRestrictedBackupMode || !normalMode, 
                      app.persistent, new Configuration(getGlobalConfiguration()), 
                      app.compat, getCommonServicesLocked(app.isolated), 
                      mCoreSettingsObserver.getCoreSettingsLocked(), buildSerial);
          }
      } catch (Exception e) {
          // 
      }
      boolean badApp = false;
      boolean didSomething = false;
      // See if the top visible activity is waiting to run in this process...
      if (normalMode) {
          try {
              // 29, 启动 activity 的后续操作
              if (mStackSupervisor.attachApplicationLocked(app)) {
                  didSomething = true;
              }
          } catch (Exception e) {
              // ...
          }
      }
      // Find any services that should be running in this process...
      if (!badApp) {
          try {
              // service 相关
              didSomething |= mServices.attachApplicationLocked(app, processName);
          } catch (Exception e) {
              // ...
          }
      }
      // Check if a next-broadcast receiver is in this process...
      if (!badApp && isPendingBroadcastProcessLocked(pid)) {
          try {
              // BroadCastReceiver 相关
              didSomething |= sendPendingBroadcastsLocked(app);
          } catch (Exception e) {
              // ...
          }
      }
      return true;
    }
    
  • 8, ActivityThread.ApplicationThread#bindApplication()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    public final void bindApplication(String processName, ApplicationInfo appInfo,
          List<ProviderInfo> providers, ComponentName instrumentationName,
          ProfilerInfo profilerInfo, Bundle instrumentationArgs,
          IInstrumentationWatcher instrumentationWatcher,
          IUiAutomationConnection instrumentationUiConnection, int debugMode,
          boolean enableBinderTracking, boolean trackAllocation,
          boolean isRestrictedBackupMode, boolean persistent, Configuration config,
          CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
          String buildSerial) {
      AppBindData data = new AppBindData();
      // 封装参数到 data 中
      // mH 发送消息分发处理
      // private final Handler mH = new H();
      sendMessage(H.BIND_APPLICATION, data);
    }
    
  • 9, ActivityThread.mH#sendMessage(H.BIND_APPLICATION, data)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    private class H extends Handler {
      @Override
      public void handleMessage(Message msg) {
          switch(msg.what) {
              case: H.BIND_APPLICATION: 
                  AppBindData data = (AppBindData)msg.obj;
                  // 跳到 ActivityThread 中处理
                  handleBindApplication(data);
                  break;
          }
      }
    }
    
  • 10, ActivityThread#handleBindApplication(AppBindData data)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    
    private void handleBindApplication(AppBindData data) {
      mBoundApplication = data;
      // ...
      if (data.persistent) {
          // 设置硬件加速
          if (!ActivityManager.isHighEndGfx()) {
              ThreadedRenderer.disable(false);
          }
      }
      if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
          // 设置 AsyncTask 执行任务线程池
          AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
      }
      // ... 各种设置
      // 12,return LoadedApk instance
      data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
      if (data.debugMode != ApplicationThreadConstants.DEBUG_OFF) {
          // ... 调试模式下会通过 AMS 弹出等待调试 dialog
      }
      // Instrumentation info affects the class loader, so load it before
      // setting up the app context.
      final InstrumentationInfo ii;
      if (ii != null) {
          // 首次启动 app ii 为 null 略过这里的逻辑
      } else {
          // 13, 实例化 Instrumentation
          mInstrumentation = new Instrumentation();
      }
      try {
          // If the app is being launched for full backup or restore, bring it up in
          // a restricted environment with the base application class.
          // 14, 生成 Application 实例,
          // 第一个参数跟备份和恢复有关,一般都是 false, 第二个参数是 Instrumentation 对象
          Application app = data.info.makeApplication(data.restrictedBackupMode, null);
          mInitialApplication = app;
          if (!data.restrictedBackupMode) {
              // 安装 ContentProvider 
              if (!ArrayUtils.isEmpty(data.providers)) {
                  installContentProviders(app, data.providers);
                  // For process that contains content providers, we want to
                  // ensure that the JIT is enabled "at some point".
                  mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
              }
          }
          // 由此可见,ContentProvider#onCreate() 方法先于 Application#onCreate() 方法执行
          try {
              // 25,调用 application.onCreate()
              mInstrumentation.callApplicationOnCreate(app);
          } catch (Exception e) {
          }
      }
      // ... Preload fonts resources
    }
    
  • 15, LoadedApk#makeApplication()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    
    public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {
      if (mApplication != null) {
          // 首次启动 mApplication 为 null
          return mApplication;
      }
      Application app = null;
      // 这里的 appClass 就是配置在 AndroidManifest.xml 文件中 applicatoin 
      // 节点的 android:name="xxx" 属性,是由 PackageManager 解析并存储的
      String appClass = mApplicationInfo.className;
      if (forceDefaultAppClass || (appClass == null)) {
          // 如果是备份后恢复数据或者没有配置自定义 application 的话就用系统默认的
          appClass = "android.app.Application";
      }
      try {
          // 关于 ClassLoader 的问题我也不清楚,之后要专门花时间研究下(先略过)
          java.lang.ClassLoader cl = getClassLoader();
          if (!mPackageName.equals("android")) {
              initializeJavaContextClassLoader();
          }
          // 17, 创建 application 类型的 context 并返回
          ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
          // 20, 具体的逻辑还是交给 mInstrumentation 来处理
          app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);
          appContext.setOuterContext(app);
      } catch (Exception e) {
      }
      mActivityThread.mAllApplications.add(app);
      mApplication = app;
      if (instrumentation != null) {
          // 上面传进来的 instrumentation 对象为 null,略过
      }
      // Rewrite the R 'constants' for all library apks.
      SparseArray<String> packageIdentifiers = getAssets().getAssignedPackageIdentifiers();
      final int N = packageIdentifiers.size();
      for (int i = 0; i < N; i++) {
          final int id = packageIdentifiers.keyAt(i);
          if (id == 0x01 || id == 0x7f) {
              continue;
          }
          // 把所有的 lib 里 R.string.app_name 通过反射修改为 app 中的 app_name
          rewriteRValues(getClassLoader(), packageIdentifiers.valueAt(i), id);
      }
      return app;
    }
    
  • 21, Instrumentation#newApplication(cl, clsName, context) -> #newApplication(clazz, context)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    static public Application newApplication(Class<?> clazz, Context context)
          throws InstantiationException, IllegalAccessException, ClassNotFoundException {
      // 通过反射生成 application 对象
      Application app = (Application)clazz.newInstance();
      // 22, 绑定 baseContext
      app.attach(context);
      // 24,返回 application
      return app;
    }
    
  • 22,Application#attach()
    1
    2
    3
    4
    5
    
    final void attach(Context context) {
      // 23,调用 attachBaseContext() 也就是我们常在 Application 中重写的 attachBaseContext() 方法
      attachBaseContext(context);
      mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
    }
    
  • 25,Instrumentation#callApplicationOnCreate(app)
    1
    2
    3
    4
    
    public void callApplicationOnCreate(Application app) {
      // 27, 这里调用 Application 的 onCreate() 方法
      app.onCreate();
    }
    
  • 29, StackSupervisor#attachApplicationLocked() 启动 activity 的后续操作,见 AMS#attachApplication
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    
    boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
      final String processName = app.processName;
      boolean didSomething = false;
      for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
          ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
          for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
              final ActivityStack stack = stacks.get(stackNdx);
              if (!isFocusedStack(stack)) {
                  continue;
              }
              ActivityRecord hr = stack.topRunningActivityLocked();
              if (hr != null) {
                  if (hr.app == null && app.uid == hr.info.applicationInfo.uid
                          && processName.equals(hr.processName)) {
                      try {
                          // 31, 调用 realStartActivityLocked() 方法
                          if (realStartActivityLocked(hr, app, true, true)) {
                              didSomething = true;
                          }
                      } catch (RemoteException e) {
                      }
                  }
              }
          }
      }
      // ...
      return didSomething;
    }
    
  • 31, StackSupervisior#realStartActivityLocked()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    
    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
          boolean andResume, boolean checkConfig) throws RemoteException {
      // ...
      r.app = app;
      app.waitingToKill = null;
      r.launchCount++;
      r.lastLaunchTime = SystemClock.uptimeMillis();
      int idx = app.activities.indexOf(r);
      if (idx < 0) {
          app.activities.add(r);
      }
      mService.updateLruProcessLocked(app, true, null);
      mService.updateOomAdjLocked();
      // ...
      try {
          // ... 32, 调用回到 IApplicationThread.scheculeLaunchActivity()
          app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                  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, app.repProcState, r.icicle,
                  r.persistentState, results, newIntents, !andResume,
                  mService.isNextTransitionForward(), profilerInfo);
          // ...
      } catch (RemoteException e) {
      }
      // ...
      // Update any services we are bound to that might care about whether
      // their client may have activities.
      if (r.app != null) {
          mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
      }
      return true;
    }
    
  • 32, IApplicationThread#scheduleLaunchActivity()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
          ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
          CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
          int procState, Bundle state, PersistableBundle persistentState,
          List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
          boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
      ActivityClientRecord r = new ActivityClientRecord();
      // ... 封装参数到 r 对象中
      // 34, mH.sendMessage()
      sendMessage(H.LAUNCH_ACTIVITY, r);
    }
    
  • 34, mH.sendMessage(H.LAUNCHER_ACTIVITY, r)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    private class H extends Handler {
      @Override
      public void handleMessage(Message msg) {
          switch(msg.what) {
              case: H.LAUNCH_ACTIVITY: 
                  final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
                  r.packageInfo = getPackageInfoNoCheck(r.activityInfo.applicationInfo, r.compatInfo);
                  // 35, 跳到 ActivityThread 中处理
                  handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
                  break;
          }
      }
    }
    
  • 35, ActivityThread#handleLaunchActivity()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
      //... 初始化 WindowManagerGlobal 为后续的界面显示做准备
      // Initialize before creating the activity
      WindowManagerGlobal.initialize();
      // 37, 创建 activity,第二个参数为 null
      Activity a = performLaunchActivity(r, customIntent);
      if (a != null) {
          // 54, 处理 activity 的 resume 逻辑
          handleResumeActivity(r.token, false, r.isForward, 
              !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
      } else {/* ...*/ }
    }
    
  • 37, ActivityThread#performLaunchActivity(r, customIntent)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
      // ...
      ContextImpl appContext = createBaseContextForActivity(r);
      Activity activity = null;
      try {
          java.lang.ClassLoader cl = appContext.getClassLoader();
          // 38 生成 activity 实例(同样和 application 一样是通过反射的方式生成的,不再跟进)
          activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
          // ...
      } catch (Exception e) {
      }
      try {
          // 此时调用 makeApplication 方法会直接返回已之前已创建完成的 mApplication
          Application app = r.packageInfo.makeApplication(false, mInstrumentation);
          if (activity != null) {
              // ...
              // 41, 绑定的逻辑,activity 中 Window 等对象会在此方法中实例化
              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);
              if (r.isPersistable()) {
                  // 对应 public Activity.onCreate(三个参数) 生命周期方法
                  mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
              } else {
                  // 对应 protected Activity#onCreate(两个参数) 生命周期方法
                  // 对于一个首次启动的 activity 来说,r.state 参数为 null
                  // 43~47 步骤 最终调用到 activit.onCreate() 生命周期方法
                  mInstrumentation.callActivityOnCreate(activity, r.state);
              }
              r.activity = activity;
              r.stopped = true;
              if (!r.activity.mFinished) {
                  // 48~53 步骤,最终会调用到 activity.onStart() 生命周期方法
                  activity.performStart();
                  r.stopped = false;
              }
              if (!r.activity.mFinished) {
                  // mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state, r.persistentState);
              }
          }
          r.paused = true;
          mActivities.put(r.token, r);
      } catch (SuperNotCalledException | Exception e) {
      }
      return activity;
    }
    
  • 54, ActivityThread#handleResumeActivity()
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    
    final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward, 
          boolean reallyResume, int seq, String reason) {
      ActivityClientRecord r = mActivities.get(token);
      // 55~61 步骤,最终会由 Instrumentation#callActivityOnResume() 调用到 activity.onResume() 生命周期方法
      // 至此我们有足够的事实证明:activity 的生命周期方法是由 Instrumentation 管理的
      r = performResumeActivity(token, clearHide, reason);
      if (r != null) {
          final Activity a = r.activity;
          final int forwardBit = isForward ?
                  WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
          // If the window hasn't yet been added to the window manager,
          // and this guy didn't finish itself or start another activity,
          // then go ahead and add the window.
          boolean willBeVisible = !a.mStartedActivity;
          if (!willBeVisible) {
              try {
                  willBeVisible = ActivityManager.getService()
                          .willActivityBeVisible(a.getActivityToken());
              } catch (RemoteException e) {}
          }
          if (r.window == null && !a.mFinished && willBeVisible) {
              // r.window 被赋值有两处,一处置 null,另一处就是这里
              // 这里 getWindow() 得到的就是之前 activity.attach() 中实例化的 PhoneWindow
              r.window = r.activity.getWindow();
              // window.getDecorView() 是个抽象方法,具体实现在 PhoneWindow 中
              // 如果 window.mDecor 为 null, 会执行 window.installDecor() 方法实例化 mDecor 对象
              // 我们明平时调用的 activity.findViewById() 实际是调用的 mDecor.findViewById()
              View decor = r.window.getDecorView();
              // ...
              if (a.mVisibleFromClient) {
                  if (!a.mWindowAdded) {
                      a.mWindowAdded = true;
                      // 向 WindowManager 中添加 DecorView
                      // addView() 是个接口方法,这里的 wm 具体实现是 WindowManagerImpl
                      // 在 wm.addView() 中又会调用 mGlobal.addView() 
                      // mGlobal 是 WindowManagerGlobal 的实例
                      // 在 mGlobal.addView() 中会创建 ViewRootImpl 的实例,
                      // ViewRootImpl 里会执行 View 的 measure/layout/draw 三大流程,这里不在详述
                      wm.addView(decor, l);
                  } else { /* ... */}
              }
          }
          // ...
      }
      // ...
    }
    

    涉及到的源文件及所在位置

  • ActivityThread.java
    • frameworks/base/core/java/android/app/ActivityThread.java
  • ActivityThread.H (ActivityThread 内部类)
  • ActivityThread.ApplicationThread (ActivityThread 内部类)
  • Application.java
    • frameworks/base/core/java/android/app/Application.java
  • LoadedApk.java
    • frameworks/base/core/java/android/app/LoadedApk.java
  • ContextImpl.java
    • frameworks/base/core/java/android/app/ContextImpl.java
  • Instrumentation.java
    • frameworks/base/core/java/android/app/Instrumentation.java
  • ActivityStackSupervisor.java
    • frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
  • Activity.java
    • frameworks/base/core/java/android/app/Activity.java

总结

  • Q1: Application 是如何创建的?
    • Instrumentation.newApplication() 方法通过反射创建 application 对象。
  • Q2: Application 的 attachBaseContext() 为什么会在 onCreate() 方法之前调用?
    • application 对象通过 LoadedApk.makeApplication() 创建完毕后会立即调用 attach() 方法,在 attach() 方法中调用 attachBaseContext() 方法,而 onCreate() 方法是在 makeApplication() 方法执行完毕之后调用的。
  • Q3: Activity 是如何被创建的?
    • 同 Application 的创建一样,是 Instrumentation 通过反射创建。
  • Q4: Activity 的生命周期方法是如何被调用的?
    • 由 Instrumentation 调用生命周期方法。
  • Q5: PhoneWindow 是何时被创建的?
    • 在 activity 创建完成调用 activity.attach() 方法时在 attach() 方法中创建。
  • Q6: ContextImpl 是何时被创建的?
    • 目前来看,ContextImpl 有多次被创建的记录:
      • 创建 Application 对象时被创建过;
      • 创建 Activity 对象时也被创建过;
      • 后续的不知道创建 Service/BroadcastReceiver/ContentProvider 时会不会被创建
  • Q7: ViewRootImpl 是何时被创建的?
    • ViewRootImpl 是在 activity.onResume() 方法之后向 WindowManager 中添加 DecorView 时创建的。
  • Q8: app 启动过程中,app 和 AMS 交互了几次?
    • bindApplication() startActivity()

结语

终于完事儿了,长出一口气点根烟休息一下,从此眼中看到的 android 世界开始逐渐跟别人不一样了!
还有几个疑问:
1, AndroidManifest.xml 文件是何时被解析的?
2, 关于 ClassLoader? 一脸懵逼啊!
3, WindowManager/ViewRootImpl/WindowManagerGlobal 之间有什么关联?
4, Service/BroadcastReceiver/ContentProvider 是什么时候初始化的?
5, JIT 是什么?见了好多次了!
道阻且长!

参考资料

This post is licensed under CC BY 4.0 by the author.