ui绘制流程2

----->main(String[] args)

//ActivityThread.java

ActivityThread thread = new ActivityThread();
//ActivityThread实例化时其属性mAppThread也实例化
//final ApplicationThread mAppThread = new ApplicationThread();
thread.attach(false, startSeq);

------->attach(boolean system, long startSeq)

//ActivityThread.java

final IActivityManager mgr = ActivityManager.getService();
try {
    mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
    throw ex.rethrowFromSystemServer();
}
  1. ------->ActivityManager.getService()
    //ActivityManager.java

    public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }
    
    private static final Singleton<IActivityManager> IActivityManagerSingleton =
            new Singleton<IActivityManager>() {
                @Override
                protected IActivityManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
                    return am;
                }
            };
    
    • ------->ServiceManager.getService(Context.ACTIVITY_SERVICE)

    • ------->BinderInternal.getContextObject()最终调用native层方法获取的是ActivityManagerService的binder

      * Returns a reference to a service with the given name.
      * @param name the name of the service to get
       @return a reference to the service, or <code>null</code> if the service doesn't exist
       */
       @UnsupportedAppUsage
      public static IBinder getService(String name) {
          try {
              IBinder service = sCache.get(name);
              if (service != null) {
                  return service;
              } else {
                  return Binder.allowBlocking(rawGetService(name));
              }
          } catch (RemoteException e) {
              Log.e(TAG, "error in getService", e);
          }
              return null;
          }
      
        private static IBinder rawGetService(String name) throws RemoteException {
              final long start = sStatLogger.getTime();
      
              final IBinder binder = getIServiceManager().getService(name);
      
              final int time = (int) sStatLogger.logDurationStat(Stats.GET_SERVICE, start);
      
              final int myUid = Process.myUid();
              final boolean isCore = UserHandle.isCore(myUid);
      
              final long slowThreshold = isCore
                      ? GET_SERVICE_SLOW_THRESHOLD_US_CORE
                      : GET_SERVICE_SLOW_THRESHOLD_US_NON_CORE;
      
              synchronized (sLock) {
                  sGetServiceAccumulatedUs += time;
                  sGetServiceAccumulatedCallCount++;
      
                  final long nowUptime = SystemClock.uptimeMillis();
      
                  // Was a slow call?
                  if (time >= slowThreshold) {
                      // We do a slow log:
                      // - At most once in every SLOW_LOG_INTERVAL_MS
                      // - OR it was slower than the previously logged slow call.
                      if ((nowUptime > (sLastSlowLogUptime + SLOW_LOG_INTERVAL_MS))
                              || (sLastSlowLogActualTime < time)) {
                          EventLogTags.writeServiceManagerSlow(time / 1000, name);
      
                          sLastSlowLogUptime = nowUptime;
                          sLastSlowLogActualTime = time;
                      }
                  }
      
                  // Every GET_SERVICE_LOG_EVERY_CALLS calls, log the total time spent in getService().
      
                  final int logInterval = isCore
                          ? GET_SERVICE_LOG_EVERY_CALLS_CORE
                          : GET_SERVICE_LOG_EVERY_CALLS_NON_CORE;
      
                  if ((sGetServiceAccumulatedCallCount >= logInterval)
                          && (nowUptime >= (sLastStatsLogUptime + STATS_LOG_INTERVAL_MS))) {
      
                      EventLogTags.writeServiceManagerStats(
                              sGetServiceAccumulatedCallCount, // Total # of getService() calls.
                              sGetServiceAccumulatedUs / 1000, // Total time spent in getService() calls.
                              (int) (nowUptime - sLastStatsLogUptime)); // Uptime duration since last log.
                      sGetServiceAccumulatedCallCount = 0;
                      sGetServiceAccumulatedUs = 0;
                      sLastStatsLogUptime = nowUptime;
                  }
              }
              return binder;
          }
      
          @UnsupportedAppUsage
          private static IServiceManager getIServiceManager() {
              if (sServiceManager != null) {
                  return sServiceManager;
              }
      
              // Find the service manager
              sServiceManager = ServiceManagerNative
                      .asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
              return sServiceManager;
          }
      
    • 简单叙述AMS注册过程

      SystemServer的static void main(String[] args)

      ---->run()

----> mSystemServiceManager = new SystemServiceManager(mSystemContext);

---->startBootstrapServices()
----->1. mActivityManagerService = mSystemServiceManager.startService(
   ActivityManagerService.Lifecycle.class).getService();
---->SystemServiceManager的startService(Class<T> serviceClass)
---->最终反射实例调用,因为ActivityManagerService.Lifecycle extends SystemService service.onStart()
---->ActivityManagerService.Lifecycle.onStart() 

---->因为构造Lifecycle时内部mService = new ActivityManagerService(context, sAtm);

----->ActivityManagerService.Lifecycle.getService()返回内部mService

----->2.mActivityManagerService.setSystemProcess();在startBootstrapServices()里面调用

----->注册自己ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                      DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
  1. ---->mgr.attachApplication(mAppThread, startSeq)

    // ActivityManagerService.java

    public class ActivityManagerService extends IActivityManager.Stub
            implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
        @Override
        public final void attachApplication(IApplicationThread thread, long startSeq) {
            synchronized (this) {
                int callingPid = Binder.getCallingPid();
                final int callingUid = Binder.getCallingUid();
                final long origId = Binder.clearCallingIdentity();
                attachApplicationLocked(thread, callingPid, callingUid, startSeq);
                Binder.restoreCallingIdentity(origId);
        }
    

}


-----> attachApplicationLocked(thread, callingPid, callingUid, startSeq)

// ActivityManagerService.java

//TO Do有空深究ProcessRecord创建

```java
    private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid, int callingUid, long startSeq) {
        ...
        ProcessRecord app;
        long startTime = SystemClock.uptimeMillis();
        if (pid != MY_PID && pid >= 0) {
            synchronized (mPidsSelfLocked) {
                app = mPidsSelfLocked.get(pid);
            }
        } else {
            app = null;
        }
        // It's possible that process called attachApplication before we got a chance to
        // update the internal state.
        if (app == null && startSeq > 0) {
            final ProcessRecord pending = mPendingStarts.get(startSeq);
            if (pending != null && pending.startUid == callingUid
                    && handleProcessStartedLocked(pending, pid, pending.usingWrapper,
                            startSeq, true)) {
                app = pending;
            }
        }
        ...
        try {
            
            if (app.isolatedEntryPoint != null) {
                // This is an isolated process which should just call an entry point instead of
                // being bound to an application.
                thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
            } else if (app.instr != null) {
                thread.bindApplication(processName, appInfo, providers,
                        app.instr.mClass,
                        profilerInfo, app.instr.mArguments,
                        app.instr.mWatcher,
                        app.instr.mUiAutomationConnection, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.persistent,
                        new Configuration(getGlobalConfiguration()), app.compat,
                        getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, isAutofillCompatEnabled);
            } else {
                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, isAutofillCompatEnabled);
            }
            ...
        } catch (Exception e) {
            // todo: Yikes!  What should we do?  For now we will try to
            // start another process, but that could easily get us in
            // an infinite loop of restarting processes...
            Slog.wtf(TAG, "Exception thrown during bind of " + app, e);

            app.resetPackageList(mProcessStats);
            app.unlinkDeathRecipient();
            startProcessLocked(app, "bind fail", processName);
            return false;
        }

        // Remove this record from the list of starting applications.
        mPersistentStartingProcesses.remove(app);
     if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES,
                "Attach application locked removing on hold: " + app);
        mProcessesOnHold.remove(app);

        boolean badApp = false;
        boolean didSomething = false;

        // See if the top visible activity is waiting to run in this process...
        if (normalMode) {
            try {
                if (mStackSupervisor.attachApplicationLocked(app)) {
                    didSomething = true;
                }
            } catch (Exception e) {
                Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                badApp = true;
            }
        }
        ...

        return true;
 }
  • ----->thread.bindApplication()
    这里的thread是最上面提到的ApplicationThread是ActivityThread的内部类是binder
    //TO DO以后细化

    public final class ActivityThread extends ClientTransactionHandler {
       private class ApplicationThread extends IApplicationThread.Stub {
          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, boolean autofillCompatibilityEnabled) {
         
            ....
             sendMessage(H.BIND_APPLICATION, data);
          }
       }
    }
    

    ----->sendMessage(H.BIND_APPLICATION, data);

    //ActivityThread.java

    void sendMessage(int what, Object obj) {
     sendMessage(what, obj, 0, 0, false);
    }
    
    private void sendMessage(int what, Object obj, int arg1) {
        sendMessage(what, obj, arg1, 0, false);
    }
    
    private void sendMessage(int what, Object obj, int arg1, int arg2) {
        sendMessage(what, obj, arg1, arg2, false);
    }
    
    private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        if (DEBUG_MESSAGES) Slog.v(
            TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
            + ": " + arg1 + " / " + obj);
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        mH.sendMessage(msg);
    }
    

    ----->最终走到H类的handleBindApplication(data)

    class H extends Handler {
        public static final int BIND_APPLICATION        = 110;
        ....
    
        String codeToString(int code) {
            if (DEBUG_MESSAGES) {
                switch (code) {
                    case BIND_APPLICATION: return "BIND_APPLICATION";
               .....
                }
         }
            return Integer.toString(code);
        }
        public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
                case BIND_APPLICATION:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
                    AppBindData data = (AppBindData)msg.obj;
                    handleBindApplication(data);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
              ...
            }
            Object obj = msg.obj;
            if (obj instanceof SomeArgs) {
                ((SomeArgs) obj).recycle();
            }
            if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
        }
    }
    
    • InstrumentationInfo ii = new ApplicationPackageManager(null, getPackageManager())
      .getInstrumentationInfo(data.instrumentationName, 0)
      IF----data.instrumentationName == null, ii = null

    • IF---- ii!=null ----

      ​ final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
      ​ appContext.getClassLoader(), false, true, false);
      ​ final ContextImpl instrContext = ContextImpl.createAppContext(this, pi)

      ELSE ----
      mInstrumentation = new Instrumentation();

      END IF;

    • instrApp.initForUser(UserHandle.myUserId());
      final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
      appContext.getClassLoader(), false, true, false);

    • final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);

    • Application app = data.info.makeApplication(data.restrictedBackupMode, null)

      IF--------如果LoadedApk的mApplication中不为空就返回mApplication,
      ELSE ---如果为空就

      先得到String appClass = mApplicationInfo.className;
      再获取java.lang.ClassLoader cl = getClassLoader();
      再创建ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this)
      最终通过app = mActivityThread.mInstrumentation.newApplication(
      cl, appClass, appContext)创建,
      END IF-----

    • mInstrumentation.callApplicationOnCreate(app

      app.onCreate()

    • 最后我们返回ActivityManagerService.attachApplicationLocked()

    private void handleBindApplication(AppBindData data) {
        // Register the UI Thread as a sensitive thread to the runtime.
        VMRuntime.registerSensitiveThread();
        if (data.trackAllocation) {
            DdmVmInternal.enableRecentAllocations(true);
        }
        // Note when this process has started.
        Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
     //设置一些信息
        mBoundApplication = data;
        mConfiguration = new Configuration(data.config);
        mCompatConfiguration = new Configuration(data.config);
    
        mProfiler = new Profiler();//设置一些信息
        ...
        final InstrumentationInfo ii;
        if (data.instrumentationName != null) {
            try {
                ii = new ApplicationPackageManager(null, getPackageManager())
                        .getInstrumentationInfo(data.instrumentationName, 0);
            } catch (PackageManager.NameNotFoundException e) {
                throw new RuntimeException(
                        "Unable to find instrumentation info for: " + data.instrumentationName);
            }
    
            // Warn of potential ABI mismatches.
            if (!Objects.equals(data.appInfo.primaryCpuAbi, ii.primaryCpuAbi)
                    || !Objects.equals(data.appInfo.secondaryCpuAbi, ii.secondaryCpuAbi)) {
                Slog.w(TAG, "Package uses different ABI(s) than its instrumentation: "
                        + "package[" + data.appInfo.packageName + "]: "
                        + data.appInfo.primaryCpuAbi + ", " + data.appInfo.secondaryCpuAbi
                        + " instrumentation[" + ii.packageName + "]: "
                        + ii.primaryCpuAbi + ", " + ii.secondaryCpuAbi);
            }
    
            mInstrumentationPackageName = ii.packageName;
            mInstrumentationAppDir = ii.sourceDir;
            mInstrumentationSplitAppDirs = ii.splitSourceDirs;
            mInstrumentationLibDir = getInstrumentationLibrary(data.appInfo, ii);
            mInstrumentedAppDir = data.info.getAppDir();
            mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
            mInstrumentedLibDir = data.info.getLibDir();
        } else {
            ii = null;
        }
    
        final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
        updateLocaleListFromAppContext(appContext,
                mResourcesManager.getConfiguration().getLocales());
    
        if (!Process.isIsolated()) {
            final int oldMask = StrictMode.allowThreadDiskWritesMask();
            try {
                setupGraphicsSupport(appContext);
            } finally {
                StrictMode.setThreadPolicyMask(oldMask);
            }
        } else {
            ThreadedRenderer.setIsolatedProcess(true);
        }
    
        ...
        NetworkSecurityConfigProvider.install(appContext);
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    
        // Continue loading instrumentation.
        if (ii != null) {
            ApplicationInfo instrApp;
            try {
                instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
                        UserHandle.myUserId());
            } catch (RemoteException e) {
                instrApp = null;
            }
            if (instrApp == null) {
                instrApp = new ApplicationInfo();
            }
            ii.copyTo(instrApp);
            instrApp.initForUser(UserHandle.myUserId());
            final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
                    appContext.getClassLoader(), false, true, false);
            final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
    
            try {
                final ClassLoader cl = instrContext.getClassLoader();
                mInstrumentation = (Instrumentation)
                    cl.loadClass(data.instrumentationName.getClassName()).newInstance();
            } catch (Exception e) {
                throw new RuntimeException(
                    "Unable to instantiate instrumentation "
                    + data.instrumentationName + ": " + e.toString(), e);
            }
    
            final ComponentName component = new ComponentName(ii.packageName, ii.name);
            mInstrumentation.init(this, instrContext, appContext, component,
                    data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
    
            if (mProfiler.profileFile != null && !ii.handleProfiling
                    && mProfiler.profileFd == null) {
                mProfiler.handlingProfiling = true;
                final File file = new File(mProfiler.profileFile);
                file.getParentFile().mkdirs();
                Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
            }
        } else {
            mInstrumentation = new Instrumentation();
            mInstrumentation.basicInit(this);
        }
    
        if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
            dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
        } else {
            // Small heap, clamp to the current growth limit and let the heap release
            // pages after the growth limit to the non growth limit capacity. b/18387825
            dalvik.system.VMRuntime.getRuntime().clampGrowthLimit();
        }
    
        // Allow disk access during application and provider setup. This could
        // block processing ordered broadcasts, but later processing would
        // probably end up doing the same disk access.
        Application app;
        final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
        final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
        try {
            // If the app is being launched for full backup or restore, bring it up in
            // a restricted environment with the base application class.
            app = data.info.makeApplication(data.restrictedBackupMode, null);
    
            // Propagate autofill compat state
            app.setAutofillCompatibilityEnabled(data.autofillCompatibilityEnabled);
    
            mInitialApplication = app;
    
            // don't bring up providers in restricted mode; they may depend on the
            // app's custom Application class
            if (!data.restrictedBackupMode) {
                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);
                }
            }
    
            // Do this after providers, since instrumentation tests generally start their
            // test thread at this point, and we don't want that racing.
            try {
                mInstrumentation.onCreate(data.instrumentationArgs);
            }
            catch (Exception e) {
                throw new RuntimeException(
                    "Exception thrown in onCreate() of "
                    + data.instrumentationName + ": " + e.toString(), e);
            }
            try {
                mInstrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                if (!mInstrumentation.onException(app, e)) {
                    throw new RuntimeException(
                      "Unable to create application " + app.getClass().getName()
                      + ": " + e.toString(), e);
                }
         }
        } finally {
            // If the app targets < O-MR1, or doesn't change the thread policy
            // during startup, clobber the policy to maintain behavior of b/36951662
            if (data.appInfo.targetSdkVersion < Build.VERSION_CODES.O_MR1
                    || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
                StrictMode.setThreadPolicy(savedPolicy);
            }
        }
    
        // Preload fonts resources
        FontsContract.setApplicationContextForResources(appContext);
        if (!Process.isIsolated()) {
            try {
             final ApplicationInfo info =
                        getPackageManager().getApplicationInfo(
                                data.appInfo.packageName,
                                PackageManager.GET_META_DATA /*flags*/,
                                UserHandle.myUserId());
                if (info.metaData != null) {
                    final int preloadedFontsResource = info.metaData.getInt(
                            ApplicationInfo.METADATA_PRELOADED_FONTS, 0);
                    if (preloadedFontsResource != 0) {
                        data.info.getResources().preloadFonts(preloadedFontsResource);
                    }
                }
            } catch (RemoteException e) {
                throw e.rethrowFromSystemServer();
            }
        }
    }
    
    • -----> mStackSupervisor.attachApplicationLocked(app)
      // //ActivityStackSupervisor.java
      // 来自ActivityManagerService.attachApplicationLocked(thread, callingPid, callingUid, startSeq)

      // ActivityManagerService.java
      mStackSupervisor = createStackSupervisor();
      protected ActivityStackSupervisor createStackSupervisor() {
          final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mHandler.getLooper());
          supervisor.initialize();
          return supervisor;
      }
      

    ​ //ActivityStackSupervisor.java

      ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener,
              RecentTasks.Callbacks{
                  ...
          boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
              final String processName = app.processName;
              boolean didSomething = false;
              for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
                 final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
                  for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
                   final ActivityStack stack = display.getChildAt(stackNdx);
                      if (!isFocusedStack(stack)) {
                          continue;
                      }
                      stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
                      final ActivityRecord top = stack.topRunningActivityLocked();
                      final int size = mTmpActivityList.size();
                      for (int i = 0; i < size; i++) {
                          final ActivityRecord activity = mTmpActivityList.get(i);
                          if (activity.app == null && app.uid == activity.info.applicationInfo.uid
                         && processName.equals(activity.processName)) {
                              try {
                                  if (realStartActivityLocked(activity, app,
                                 top == activity /* andResume */, true /* checkConfig */)) {
                                    didSomething = true;
                                  }
                              } catch (RemoteException e) {
                               Slog.w(TAG, "Exception in new application when starting activity "
                               + top.intent.getComponent().flattenToShortString(), e);
                                 throw e;
                            }
                        }
                     }
                  }
              }
              if (!didSomething) {
                  ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
              }
              return didSomething;
          }
      }
    

    ---->realStartActivityLocked(activity, app, top == activity /* andResume /, true / checkConfig */)

    //ActivityStackSupervisor.java

    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
                boolean andResume, boolean checkConfig) throws RemoteException {
    
            ...
    
            final TaskRecord task = r.getTask();
            final ActivityStack stack = task.getStack();
    
            beginDeferResume();
    
            try {
                r.startFreezingScreenLocked(app, 0);
                // schedule launch ticks to collect information about slow apps.
                r.startLaunchTickingLocked();
                r.setProcess(app);
                ...
                mService.updateLruProcessLocked(app, true, null);
                mService.updateOomAdjLocked();
    
                try {
                    ...
                    mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
                            PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY);
                    ...
                    // Create activity launch transaction.
                    final ClientTransaction clientTransaction 
                        = ClientTransaction.obtain(app.thread,
                            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, 
                            app.repProcState, r.icicle,
                            r.persistentState, results, 
                            newIntents, mService.isNextTransitionForward(),
                            profilerInfo));
    
                    // Set desired final state.
                    final ActivityLifecycleItem lifecycleItem;
                    if (andResume) {
                        lifecycleItem = 
                        ResumeActivityItem.obtain(mService.isNextTransitionForward());
                    } else {
                        lifecycleItem = PauseActivityItem.obtain();
                    }
                    clientTransaction.setLifecycleStateRequest(lifecycleItem);
    
                    // Schedule transaction.
                    mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    
                    if ((app.info.privateFlags &
                         ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0
                            && mService.mHasHeavyWeightFeature) {
                        // This may be a heavy-weight process!  Note that the package
                        // manager will ensure that only activity can run in the main
                        // process of the .apk, which is the only thing that will be
                        // considered heavy-weight.
                        if (app.processName.equals(app.info.packageName)) {
                            if (mService.mHeavyWeightProcess != null
                                    && mService.mHeavyWeightProcess != app) {
                                Slog.w(TAG, "Starting new heavy weight process " + app
                                        + " when already running "
                                        + mService.mHeavyWeightProcess);
                            }
                            mService.mHeavyWeightProcess = app;
                         Message msg = mService.mHandler.obtainMessage(
                                    ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
                            msg.obj = r;
                            mService.mHandler.sendMessage(msg);
                        }
                    }
    
                } catch (RemoteException e) {
                    ...
                }
            } finally {
             endDeferResume();
            }
    
            ...
            // Launch the new version setup screen if needed.  We do this -after-
            // launching the initial activity (that is, home), so that it can have
            // a chance to initialize itself while in the background, making the
            // switch back to it faster and look better.
            if (isFocusedStack(stack)) {
                mService.getActivityStartController().startSetupActivity();
            }
    
            // 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;
        }
    

    ---->mService.getLifecycleManager().scheduleTransaction(clientTransaction)

    // ActivityManagerService.java --- mService

    // ClientLifecycleManager.java --- mService.getLifecycleManager()

    // final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread, r.appToken); ActivityStackSupervisor.realStartActivityLocked()方法内部构造

    // ClientLifecycleManager.scheduleTransaction(ClientTransaction transaction)

    //  ActivityManagerService.java   
    ClientLifecycleManager getLifecycleManager() {
        return mLifecycleManager;
    }
    //ActivityManagerService构造方法内构造mLifecycleManager = new ClientLifecycleManager()
    
    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();
            }
        }
    }
    
    public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
        ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
        if (instance == null) {
            instance = new ClientTransaction();
        }
        instance.mClient = client;
        instance.mActivityToken = activityToken;
    
        return instance;
    }
    

    ---->mLifecycleManager.scheduleTransaction(ClientTransaction transaction)

    // ClientLifecycleManager.java

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

    ---->transaction.schedule()

    // ClientTransaction.java

    public class ClientTransaction implements Parcelable, ObjectPoolItem {
        public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
            ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
            if (instance == null) {
                instance = new ClientTransaction();
            }
            instance.mClient = client;
            instance.mActivityToken = activityToken;
    
            return instance;
        }
        
        public void schedule() throws RemoteException {
            mClient.scheduleTransaction(this);
        }
    }
    

    ---->mClient.scheduleTransaction(this)
    //ApplicationThread.java

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

    ---->ActivityThread.this.scheduleTransaction(transaction);
    ---->ClientTransactionHandler.scheduleTransaction(transaction)

    // ActivityThread extends ClientTransactionHandler

    public abstract class ClientTransactionHandler {
        void scheduleTransaction(ClientTransaction transaction) {
            transaction.preExecute(this);
            sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
        }
    }
    
    private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
    
    class H extends Handler {
        public static final int EXECUTE_TRANSACTION = 159;
    
        String codeToString(int code) {
                if (DEBUG_MESSAGES) {
                    switch (code) {
                        case EXECUTE_TRANSACTION: return "EXECUTE_TRANSACTION";
                    }
                }
                return Integer.toString(code);
            }
            
        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()) {
                            // Client transactions inside system process are recycled on the client side
                            // instead of ClientLifecycleManager to avoid being cleared before this
                            // message is handled.
                            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);

    // TransactionExecutor.java

    public class TransactionExecutor {
        public void execute(ClientTransaction transaction) {
            final IBinder token = transaction.getActivityToken();
            log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
    
            executeCallbacks(transaction);
    
            executeLifecycleState(transaction);
            mPendingActions.clear();
            log("End resolving transaction");
        }
    }
    

    ----> executeCallbacks(transaction);

    // TransactionExecutor.java

    //在ActivityStackSupervisor的realStartActivityLocked()方法构造后作为sendMessage传递过来

    @VisibleForTesting
    public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
        ...
        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            log("Resolving callback: " + item);
            final int postExecutionState = item.getPostExecutionState();
            final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
                    item.getPostExecutionState());
            if (closestPreExecutionState != UNDEFINED) {
                cycleToPath(r, closestPreExecutionState);
            }
    
            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);
            }
        }
    }
    

    ----->final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
    //在ActivityStackSupervisor的realStartActivityLocked()方法构造transaction

    //构造clientTransaction后将LaunchActivityItem添加入Callbacks

    //最后作为sendMessage参数传递过来

    //在handleMessage方法中做了转换

    public void addCallback(ClientTransactionItem activityCallback) {
        if (mActivityCallbacks == null) {
            mActivityCallbacks = new ArrayList<>();
        }
        mActivityCallbacks.add(activityCallback);
    }
    
    /** Get the list of callbacks. */
    @Nullable
    List<ClientTransactionItem> getCallbacks() {
        return mActivityCallbacks;
    }
    
    //ActivityStackSupervisor.realStartActivityLocked()内
    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, 
                              app.repProcState, r.icicle,
                              r.persistentState, results, 
                              newIntents, mService.isNextTransitionForward(),
                              profilerInfo));
    

    ----->item.execute(mTransactionHandler, token, mPendingActions);

    //LaunchActivityItem.java

    public class LaunchActivityItem extends ClientTransactionItem {
        @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);
            client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
            Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
        }
    }    
    

    ------->client.handleLaunchActivity(r, pendingActions, null /* customIntent */);

    因为ActivityThread extends ClientTransactionHandler且ActivityThread 覆写了此方法

    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();
        mSomeActivitiesChanged = true;
    
        if (r.profilerInfo != null) {
            mProfiler.setProfiler(r.profilerInfo);
            mProfiler.startProfiling();
        }
    
        // Make sure we are running with the most recent config.
        handleConfigurationChanged(null, null);
    
        if (localLOGV) Slog.v(
            TAG, "Handling launch of " + r);
    
        // Initialize before creating the activity
        if (!ThreadedRenderer.sRendererDisabled) {
            GraphicsEnvironment.earlyInitEGL();
        }
        WindowManagerGlobal.initialize();
    
        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 {
            // If there was an error, for any reason, tell the activity manager to stop us.
            try {
                ActivityManager.getService()
                        .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                                Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        }
    
        return a;
    }
    

    ----->final Activity a = performLaunchActivity(r, customIntent)
    // ActivityThread.Java

    • ComponentName component = r.intent.getComponent()

    • 新建ContextImpl appContext = createBaseContextForActivity(r)

    • 通过 mInstrumentation.newActivity(cl, component.getClassName(), r.intent)创建 Activity

      /frameworks/base/java/android/app/Instrumentation.java

      getFactory(pkg).instantiateActivity(cl, className, intent)

      1. getFactory(pkg)

      ​ LoadedApk apk = mThread.peekPackageInfo(pkg, true); apk.getAppFactory()

      ​ LoadedApk构造时创建了AppComponentFactory

      1. AppComponentFactory.instantiateActivity(cl, className, intent)

      ​ 最终通过classloader加载类,然后newInstance()

    • Application app = r.packageInfo.makeApplication(false, mInstrumentation)

      IF--------如果LoadedApk的mApplication中不为空就返回mApplication,
      ELSE ---如果为空就

      先得到String appClass = mApplicationInfo.className;
      再获取java.lang.ClassLoader cl = getClassLoader();
      再创建ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this)
      最终通过app = mActivityThread.mInstrumentation.newApplication(
      cl, appClass, appContext)创建,
      END IF-----

    • 调用Acitivity的attach方法
      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);
      Activity extends ContextThemeWrapper
      ContextThemeWrapper extends ContextWrapper
      ContextWrapper extends Context
      Activity的attach()方法通过attachBaseContext一层一层往上调用传递

    • mInstrumentation.callActivityOnCreate(activity....)传入activity最终调用acitivity的onCreate方法

      r.isPersistable()是否持久模式重启
      IF--true---ImInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
      ELSE------mInstrumentation.callActivityOnCreate(activity, r.state);

      正常我们走else

      END IF----activity.performCreate(icicle, persistentState)

      最终都会activity.performCreate(Bundle icicle, PersistableBundle persistentState),只是最后一个参数有可能空
      activity.onCreate(icicle)
      我们在activity中setContentView(R.layout.activity_main);加载我们的布局

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ActivityInfo aInfo = r.activityInfo;
        if (r.packageInfo == null) {
            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                    Context.CONTEXT_INCLUDE_CODE);
        }
    
        ComponentName component = r.intent.getComponent();
        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 = 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);
    
            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);
    
                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);
                } 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);
    
            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;
    }
    
    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);
        }
    
        private AppComponentFactory getFactory(String pkg) {
            if (pkg == null) {
                Log.e(TAG, "No pkg specified, disabling AppComponentFactory");
                return AppComponentFactory.DEFAULT;
            }
            if (mThread == null) {
                Log.e(TAG, "Uninitialized ActivityThread, likely app-created Instrumentation,"
                        + " disabling AppComponentFactory", new Throwable());
                return AppComponentFactory.DEFAULT;
            }
            LoadedApk apk = mThread.peekPackageInfo(pkg, true);
            // This is in the case of starting up "android".
            if (apk == null) apk = mThread.getSystemContext().mPackageInfo;
            return apk.getAppFactory();
        }
    }
    
        public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
            synchronized (mResourcesManager) {
                WeakReference<LoadedApk> ref;
                if (includeCode) {
                    ref = mPackages.get(packageName);
                } else {
                    ref = mResourcePackages.get(packageName);
                }
                return ref != null ? ref.get() : null;
            }
        }
    
    public final class LoadedApk {
        public LoadedApk(ActivityThread activityThread, ApplicationInfo aInfo,
            CompatibilityInfo compatInfo, ClassLoader baseLoader,
            boolean securityViolation, boolean includeCode, boolean registerPackage) {
    
            mActivityThread = activityThread;
            setApplicationInfo(aInfo);
            mPackageName = aInfo.packageName;
            mBaseClassLoader = baseLoader;
            mSecurityViolation = securityViolation;
            mIncludeCode = includeCode;
            mRegisterPackage = registerPackage;
            mDisplayAdjustments.setCompatibilityInfo(compatInfo);
            mAppComponentFactory = createAppFactory(mApplicationInfo, mBaseClassLoader);
        }
    
        LoadedApk(ActivityThread activityThread) {
            mActivityThread = activityThread;
            mApplicationInfo = new ApplicationInfo();
            mApplicationInfo.packageName = "android";
            mPackageName = "android";
            mAppDir = null;
            mResDir = null;
            mSplitAppDirs = null;
            mSplitResDirs = null;
            mSplitClassLoaderNames = null;
            mOverlayDirs = null;
            mDataDir = null;
            mDataDirFile = null;
            mDeviceProtectedDataDirFile = null;
            mCredentialProtectedDataDirFile = null;
            mLibDir = null;
            mBaseClassLoader = null;
            mSecurityViolation = false;
            mIncludeCode = true;
            mRegisterPackage = false;
            mClassLoader = ClassLoader.getSystemClassLoader();
            mResources = Resources.getSystem();
            mAppComponentFactory = createAppFactory(mApplicationInfo, mClassLoader);
        }
    
        private AppComponentFactory createAppFactory(ApplicationInfo appInfo, ClassLoader cl) {
            if (appInfo.appComponentFactory != null && cl != null) {
                try {
                    return (AppComponentFactory) cl.loadClass(appInfo.appComponentFactory)
                            .newInstance();
                } catch (InstantiationException | IllegalAccessException
                         | ClassNotFoundException e) {
                    Slog.e(TAG, "Unable to instantiate appComponentFactory", e);
                }
            }
            return AppComponentFactory.DEFAULT;
        }
    }
    
    public class AppComponentFactory extends android.app.AppComponentFactory {
            @Override
        public final Activity instantiateActivity(ClassLoader cl, String className, Intent intent)
                throws InstantiationException, IllegalAccessException, ClassNotFoundException {
            return checkCompatWrapper(instantiateActivityCompat(cl, className, intent));
        }
        
        public @NonNull Activity instantiateActivityCompat(@NonNull ClassLoader cl,
                @NonNull String className, @Nullable Intent intent)
                throws InstantiationException, IllegalAccessException, ClassNotFoundException {
            try {
                return (Activity) cl.loadClass(className).getDeclaredConstructor().newInstance();
            } catch (InvocationTargetException | NoSuchMethodException e) {
                throw new RuntimeException("Couldn't call constructor", e);
            }
        }
    }
    
// ActivityThread.Java
if (r.isPersistable()) {
    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
    mInstrumentation.callActivityOnCreate(activity, r.state);
}
// Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle) {
    prePerformCreate(activity);
    activity.performCreate(icicle);
    postPerformCreate(activity);
}

/**
 * Perform calling of an activity's {@link Activity#onCreate}
 * method.  The default implementation simply calls through to that method.
 *  @param activity The activity being created.
 * @param icicle The previously frozen state (or null) to pass through to
 * @param persistentState The previously persisted state (or null)
 */
public void callActivityOnCreate(Activity activity, Bundle icicle,
        PersistableBundle persistentState) {
    prePerformCreate(activity);
    activity.performCreate(icicle, persistentState);
    postPerformCreate(activity);
}

private void postPerformCreate(Activity activity) {
        if (mActivityMonitors != null) {
            synchronized (mSync) {
                final int N = mActivityMonitors.size();
                for (int i=0; i<N; i++) {
                    final ActivityMonitor am = mActivityMonitors.get(i);
                    am.match(activity, activity, activity.getIntent());
                }
            }
    }
}
public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback,
        OnCreateContextMenuListener, ComponentCallbacks2,
        Window.OnWindowDismissedCallback, WindowControllerCallback,
        AutofillManager.AutofillClient {
    final void performCreate(Bundle icicle) {
        performCreate(icicle, null);
    }

    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        mCanEnterPictureInPicture = true;
        restoreHasCurrentPermissionRequest(icicle);
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
        writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
        mActivityTransitionState.readState(icicle);

        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
            com.android.internal.R.styleable.Window_windowNoDisplay, false);
        mFragments.dispatchActivityCreated();
        mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
    }
    
    final void performCreate(Bundle icicle) {
        performCreate(icicle, null);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,189评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,577评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,857评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,703评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,705评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,620评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,995评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,656评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,898评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,639评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,720评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,395评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,982评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,953评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,195评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,907评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,472评论 2 342

推荐阅读更多精彩内容