ui繪制流程2

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

//ActivityThread.java

ActivityThread thread = new ActivityThread();
//ActivityThread實(shí)例化時(shí)其屬性mAppThread也實(shí)例化
//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()最終調(diào)用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;
          }
      
    • 簡(jiǎn)單敘述AMS注冊(cè)過(guò)程

      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)
---->最終反射實(shí)例調(diào)用宛逗,因?yàn)锳ctivityManagerService.Lifecycle extends SystemService service.onStart()
---->ActivityManagerService.Lifecycle.onStart() 

---->因?yàn)闃?gòu)造Lifecycle時(shí)內(nèi)部mService = new ActivityManagerService(context, sAtm);

----->ActivityManagerService.Lifecycle.getService()返回內(nèi)部mService

----->2.mActivityManagerService.setSystemProcess();在startBootstrapServices()里面調(diào)用

----->注冊(cè)自己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創(chuàng)建

```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的內(nèi)部類是binder
    //TO DO以后細(xì)化

    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();
      再創(chuàng)建ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this)
      最終通過(guò)app = mActivityThread.mInstrumentation.newApplication(
      cl, appClass, appContext)創(chuàng)建,
      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());
     //設(shè)置一些信息
        mBoundApplication = data;
        mConfiguration = new Configuration(data.config);
        mCompatConfiguration = new Configuration(data.config);
    
        mProfiler = new Profiler();//設(shè)置一些信息
        ...
        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
      // 來(lái)自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()方法內(nèi)部構(gòu)造

    // ClientLifecycleManager.scheduleTransaction(ClientTransaction transaction)

    //  ActivityManagerService.java   
    ClientLifecycleManager getLifecycleManager() {
        return mLifecycleManager;
    }
    //ActivityManagerService構(gòu)造方法內(nèi)構(gòu)造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()方法構(gòu)造后作為sendMessage傳遞過(guò)來(lái)

    @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()方法構(gòu)造transaction

    //構(gòu)造clientTransaction后將LaunchActivityItem添加入Callbacks

    //最后作為sendMessage參數(shù)傳遞過(guò)來(lái)

    //在handleMessage方法中做了轉(zhuǎn)換

    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()內(nèi)
    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 */);

    因?yàn)锳ctivityThread 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)

    • 通過(guò) mInstrumentation.newActivity(cl, component.getClassName(), r.intent)創(chuàng)建 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構(gòu)造時(shí)創(chuàng)建了AppComponentFactory

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

      ? 最終通過(guò)classloader加載類舶赔,然后newInstance()

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

      IF--------如果LoadedApk的mApplication中不為空就返回mApplication梨树,
      ELSE ---如果為空就

      先得到String appClass = mApplicationInfo.className;
      再獲取java.lang.ClassLoader cl = getClassLoader();
      再創(chuàng)建ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this)
      最終通過(guò)app = mActivityThread.mInstrumentation.newApplication(
      cl, appClass, appContext)創(chuàng)建,
      END IF-----

    • 調(diào)用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()方法通過(guò)attachBaseContext一層一層往上調(diào)用傳遞

    • mInstrumentation.callActivityOnCreate(activity....)傳入activity最終調(diào)用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)

      最終都會(huì)activity.performCreate(Bundle icicle, PersistableBundle persistentState),只是最后一個(gè)參數(shù)有可能空
      activity.onCreate(icicle)
      我們?cè)赼ctivity中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);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末敬矩,一起剝皮案震驚了整個(gè)濱河市逮光,隨后出現(xiàn)的幾起案子话瞧,更是在濱河造成了極大的恐慌,老刑警劉巖蜂桶,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件儡毕,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡屎飘,警方通過(guò)查閱死者的電腦和手機(jī)妥曲,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)钦购,“玉大人檐盟,你說(shuō)我怎么就攤上這事⊙禾遥” “怎么了葵萎?”我有些...
    開封第一講書人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)唱凯。 經(jīng)常有香客問(wèn)我羡忘,道長(zhǎng),這世上最難降的妖魔是什么磕昼? 我笑而不...
    開封第一講書人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任卷雕,我火速辦了婚禮,結(jié)果婚禮上票从,老公的妹妹穿的比我還像新娘漫雕。我一直安慰自己滨嘱,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開白布浸间。 她就那樣靜靜地躺著太雨,像睡著了一般。 火紅的嫁衣襯著肌膚如雪魁蒜。 梳的紋絲不亂的頭發(fā)上囊扳,一...
    開封第一講書人閱讀 51,125評(píng)論 1 297
  • 那天,我揣著相機(jī)與錄音兜看,去河邊找鬼锥咸。 笑死,一個(gè)胖子當(dāng)著我的面吹牛细移,可吹牛的內(nèi)容都是我干的她君。 我是一名探鬼主播,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼葫哗,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼缔刹!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起劣针,我...
    開封第一講書人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤校镐,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后捺典,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體鸟廓,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年襟己,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了引谜。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡擎浴,死狀恐怖员咽,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情贮预,我是刑警寧澤贝室,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站仿吞,受9級(jí)特大地震影響滑频,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜唤冈,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一峡迷、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧你虹,春花似錦绘搞、人聲如沸枣申。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至挟伙,卻和暖如春楼雹,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背尖阔。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來(lái)泰國(guó)打工贮缅, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人介却。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓谴供,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親齿坷。 傳聞我的和親對(duì)象是個(gè)殘疾皇子桂肌,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容