王學崗高級UI一———UI繪製流程(上)

簡書資料地址
https://www.jianshu.com/p/f55467033146
https://www.jianshu.com/p/fc717b47b322

第一app的啓動之Application的創建

程序的啓動就是應用進程(app)和系統進程(SystemServer)的通信。主要是跟系統進程中的AMS通信。應用進程中的四大組件(以Activity爲例),系統進程(主要是AMS)會不斷的調度Activity以及管理Activity的每個狀態。
附:activity的狀態
在這裏插入圖片描述
在這裏插入圖片描述
當APP啓動的時候,應用進程會主動的向系統進程發送消息,當系統進程允許Activity的創建,系統進程會發送消息到應用進程。
Activity的創建會涉及到跨進程的調用。
Android 程序啓動的入口是ActivityThread的main方法。注意ActivityThread不是一個線程

public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
       AndroidOs.install(); 
         CloseGuard.setEnabled(false);
        Environment.initForCurrentUser();
       final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);
        Process.setArgV0("<pre-initialized>");
        Looper.prepareMainLooper();
        long startSeq = 0;
        if (args != null) {
            for (int i = args.length - 1; i >= 0; --i) {
                if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                    startSeq = Long.parseLong(
                            args[i].substring(PROC_START_SEQ_IDENT.length()));
                }
            }
        }
        //自己new了自己,
        ActivityThread thread = new ActivityThread();
        //當前應用綁定了AMS
        thread.attach(false, startSeq);
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
       Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

在孵化器進程會調用main()方法,main()方法的調用標誌着app進程的啓動。
我們看下attach方法

 @UnsupportedAppUsage
    private void attach(boolean system, long startSeq) {
        sCurrentActivityThread = this;
        mSystemThread = system;
        if (!system) {
            android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                    UserHandle.myUserId());
            RuntimeInit.setApplicationObject(mAppThread.asBinder());
            //獲取IActivityManager,IActivityManager是AMS的代理對象。
            //AMS是系統進程,當前應用進程要與AMS進程通信,因爲是兩個不同的進程,所以要用到binder機制
            //IActivityManager就是AMS的一個代理類。
            final IActivityManager mgr = ActivityManager.getService();
            try {
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
            BinderInternal.addGcWatcher(new Runnable() {
                @Override public void run() {
                    if (!mSomeActivitiesChanged) {
                        return;
                    }
                    Runtime runtime = Runtime.getRuntime();
                    long dalvikMax = runtime.maxMemory();
                    long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
                    if (dalvikUsed > ((3*dalvikMax)/4)) {
                        if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
                                + " total=" + (runtime.totalMemory()/1024)
                                + " used=" + (dalvikUsed/1024));
                        mSomeActivitiesChanged = false;
                        try {
                            ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
                        } catch (RemoteException e) {
                            throw e.rethrowFromSystemServer();
                        }
                    }
                }
            });
        } else {
            android.ddm.DdmHandleAppName.setAppName("system_process",
                    UserHandle.myUserId());
            try {
                mInstrumentation = new Instrumentation();
                mInstrumentation.basicInit(this);
                ContextImpl context = ContextImpl.createAppContext(
                        this, getSystemContext().mPackageInfo);
                mInitialApplication = context.mPackageInfo.makeApplication(true, null);
                mInitialApplication.onCreate();
            } catch (Exception e) {
                throw new RuntimeException(
                        "Unable to instantiate Application():" + e.toString(), e);
            }
        }
        ViewRootImpl.ConfigChangedCallback configChangedCallback
                = (Configuration globalConfig) -> {
            synchronized (mResourcesManager) {
                if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
                        null /* compat */)) {
                    updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
                            mResourcesManager.getConfiguration().getLocales());
                    if (mPendingConfiguration == null
                            || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
                        mPendingConfiguration = globalConfig;
                        sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
                    }
                }
            }
        };
        ViewRootImpl.addConfigCallback(configChangedCallback);
    }

我們點擊final IActivityManager mgr = ActivityManager.getService();的getService方法。
進入ActivityManager的getService()方法。

public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }
 @UnsupportedAppUsage
    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);
                    //拿到AMS的代理
                    return am;
                }
            };

我們回到ActivityThread類
mgr.attachApplication(mAppThread, startSeq);
這個方法是跳到ActivityManagerService類,進入這個方法

   @Override
    public final void attachApplication(IApplicationThread thread) {
        synchronized (this) {
        //獲取PID
            int callingPid = Binder.getCallingPid();
            final long origId = Binder.clearCallingIdentity();
            attachApplicationLocked(thread, callingPid);
            Binder.restoreCallingIdentity(origId);
        }
    }

這個方法獲取到一大堆ID,這些ID的作用就是應用的唯一標識。這些ID是由系統生成並且分配的。
attachApplicationLocked(thread, callingPid);標識綁定了Application。點擊 attachApplicationLocked(thread, callingPid);這個方法進入到下面代碼

  private final boolean attachApplicationLocked(IApplicationThread thread,
                                                  int pid) {
        ProcessRecord app;
        if (pid != MY_PID && pid >= 0) {
            synchronized (mPidsSelfLocked) {
                app = mPidsSelfLocked.get(pid);
            }
        } else {
            app = null;
        }

通過pid拿到ProcessRecord對象,ProcessRecord是來維護進程運行時的狀態信息,需要將應用進程綁定到ProcessRecord才能開始一個Application的構建。
繼續往下看源碼,看到下面這些代碼

thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
                    profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
                    app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
                    isRestrictedBackupMode || !normalMode, app.persistent,
                    new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
                    mCoreSettingsObserver.getCoreSettingsLocked());

這些代碼開始綁定App了。這裏的thread就是IApplicationThread,IApplicationThread是在系統進程嚮應用進程發起通信時候用到的。
我們看下IApplicationThread,它是ActivityThread內部類

private class ApplicationThread extends IApplicationThread.Stub {}

我們可以發現,該內部類就是一個AIDL;該內部類有一個方法

 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, AutofillOptions autofillOptions,
                ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges) {
                }

該方法是綁定Application,綁定Application的時候會向Application傳入各種信息。
注意下,我們源碼現在從系統服務進程又回到我們應用進程了。
看下該方法的方法體

  AppBindData data = new AppBindData();
            data.processName = processName;
            data.appInfo = appInfo;
            data.providers = providers;
            data.instrumentationName = instrumentationName;
            data.instrumentationArgs = instrumentationArgs;
            data.instrumentationWatcher = instrumentationWatcher;
            data.instrumentationUiAutomationConnection = instrumentationUiConnection;
            data.debugMode = debugMode;
            data.enableBinderTracking = enableBinderTracking;
            data.trackAllocation = trackAllocation;
            data.restrictedBackupMode = isRestrictedBackupMode;
            data.persistent = persistent;
            data.config = config;
            data.compatInfo = compatInfo;
            data.initProfilerInfo = profilerInfo;
            data.buildSerial = buildSerial;
            data.autofillOptions = autofillOptions;
            data.contentCaptureOptions = contentCaptureOptions;
            data.disabledCompatChanges = disabledCompatChanges;
            sendMessage(H.BIND_APPLICATION, data);

該方法體是把傳進來的信息保存在了AppBindData裏面。最後發送一條消息,我們看下處理該消息的地方。

  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;

handleBindApplication(data);就是處理消息的綁定。我們看下 handleBindApplication(data)方法。在該方法體中有這句代碼 dapp = data.info.makeApplication(data.restrictedBackupMode, null);這句代碼就是創建Application。我們進入makeApplication()中查詢該方法。makeApplication()方法在LoadedAPK類裏面,我們打開該類。看下該方法方法體

  String appClass = mApplicationInfo.className;//獲取類名,該類名就是我們自己定義的Application,
        if (forceDefaultAppClass || (appClass == null)) {
            appClass = "android.app.Application";//如果我們自己沒有自定義Application,那麼久自動獲取系統的類名。
        }

接着看makeApplication()源碼

  try {
  //獲取類加載器
            java.lang.ClassLoader cl = getClassLoader();
            if (!mPackageName.equals("android")) {
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
                        "initializeJavaContextClassLoader");
                initializeJavaContextClassLoader();
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            }
            //獲取上下文
            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
            //反射創建Application
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
            appContext.setOuterContext(app);
        } catch (Exception e) {
            if (!mActivityThread.mInstrumentation.onException(app, e)) {
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                throw new RuntimeException(
                    "Unable to instantiate application " + appClass
                    + ": " + e.toString(), e);
            }
        }

通過類加載器,加載文件。加載完後反射。
接着往下看makeApplication()源碼

instrumentation.callApplicationOnCreate(app);

這個方法就是Application的onCreate()的創建。
我們看下Instrumentation類的callApplicationOnCreate方法

public void callApplicationOnCreate(Application app){
  app.onCreate();
}

我去,找了那麼多代碼,Application終於創建了。

第二創建Activity

我們現在再回到ActivityManagerService中。

 // 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;
            }
        }
        // Find any services that should be running in this process...
        if (!badApp) {
            try {
                didSomething |= mServices.attachApplicationLocked(app, processName);
            } catch (Exception e) {
                Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
                badApp = true;
            }
        }

查找是否有可用的Activity、Service、廣播等。我們主要看Activity。這句代碼(mStackSupervisor.attachApplicationLocked(app))就是創建Activity。我們進入ActivityStackSupervisor類的attachApplicationLocked();
我們看下attachApplicationLocked方法體這句代碼
ActivityRecord hr = stack.topRunningActivityLocked(null);
ActivityRecord來維護Activity運行時的狀態信息,需要將Activity綁定到AMS中,ActivityRecord才能開始Activity的生命週期。
接着看attachApplicationLocked的方法體
realStartActivityLocked(hr, app, true, true)這句代碼是真正的解鎖Activity。
我們看下這個方法的方法體

final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread, r.appToken);
 clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
 System.identityHashCode(r), r.info,mergedConfiguration.getGlobalConfiguration(),  mergedConfiguration.getOverrideConfiguration(), r.compat, r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results, newIntents, mService.isNextTransitionForward(),profilerInfo));

obtain是開啓了一個客戶端事務。這個事務的工作就是創建Activity。 addCallback()是添加第一個創建Activity的回調。也就是LaunchActivityItem。這裏的第一個創建Activity指的是添加

 <intent-filter>
                <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>

的Activity。
繼續向下看這個方法體

    if (andResume) {
         lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
    } else {
        lifecycleItem = PauseActivityItem.obtain();
   }

這裏設置所需的最終狀態,
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
這裏的mService就是ActivitymanagerService,getLifecycleManager()是拿到生命週期的管理類,scheduleTransaction是執行事務。我們進入這個方法看看它的方法體會發現它是調用 transaction.schedule();執行事務。我們看下transaction這個類,這個類就是
ClientTransaction。我們看下相應的方法

 public void schedule() throws RemoteException {
     mClient.scheduleTransaction(this);
     }

mClient是private IApplicationThread mClient;
我們在ActivityTread中可以找到該內部類

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

現在我們又回到了客戶端。這次回到客戶端的主要目的是創建Activity。該方法最終調用的是ActivityThread.this.scheduleTransaction(transaction);
在ActivityThread的父類ClientTransactionHandler中調用了該方法

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

發送一個消息,我們看下這個消息是如何處理的。

 final ClientTransaction transaction = (ClientTransaction) msg.obj;
                mTransactionExecutor.execute(transaction);
                     if (isSystem()) {
                        transaction.recycle();
                    }

把ClientTransaction傳入到execute()中。看下mTransactionExecutor的成員變量
private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
我們進入TransactionExecutor 類看看該方法

public void execute(ClientTransaction transaction) {
65          final IBinder token = transaction.getActivityToken();
66          log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
67  
68          executeCallbacks(transaction);
69  
70          executeLifecycleState(transaction);
71          mPendingActions.clear();
72          log("End resolving transaction");
73      }

執行 executeCallbacks(transaction)方法

public void executeCallbacks(ClientTransaction transaction) {
78          final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
79          if (callbacks == null) {
80              // No callbacks to execute, return early.
81              return;
82          }
83          log("Resolving callbacks");
84  
85          final IBinder token = transaction.getActivityToken();
86          ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
87  
88          // In case when post-execution state of the last callback matches the final state requested
89          // for the activity in this transaction, we won't do the last transition here and do it when
90          // moving to final state instead (because it may contain additional parameters from server).
91          final ActivityLifecycleItem finalStateRequest = transaction.getLifecycleStateRequest();
92          final int finalState = finalStateRequest != null ? finalStateRequest.getTargetState()
93                  : UNDEFINED;
94          // Index of the last callback that requests some post-execution state.
95          final int lastCallbackRequestingState = lastCallbackRequestingState(transaction);
96  
97          final int size = callbacks.size();
98          for (int i = 0; i < size; ++i) {
99              final ClientTransactionItem item = callbacks.get(i);
100              log("Resolving callback: " + item);
101              final int postExecutionState = item.getPostExecutionState();
102              final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
103                      item.getPostExecutionState());
104              if (closestPreExecutionState != UNDEFINED) {
105                  cycleToPath(r, closestPreExecutionState);
106              }
107  
108              item.execute(mTransactionHandler, token, mPendingActions);
109              item.postExecute(mTransactionHandler, token, mPendingActions);
110              if (r == null) {
111                  // Launch activity request will create an activity record.
112                  r = mTransactionHandler.getActivityClient(token);
113              }
114  
115              if (postExecutionState != UNDEFINED && r != null) {
116                  // Skip the very last transition and perform it by explicit state request instead.
117                  final boolean shouldExcludeLastTransition =
118                          i == lastCallbackRequestingState && finalState == postExecutionState;
119                  cycleToPath(r, postExecutionState, shouldExcludeLastTransition);
120              }
121          }
122      }

final List callbacks = transaction.getCallbacks();拿到set的CallBack,
final ClientTransactionItem item = callbacks.get(i);這句代碼拿到的就是LaunchActivityItem對象。
item.execute(mTransactionHandler, token, mPendingActions);方法被執行的時候會跳轉到LaunchActivityItem類。我們看下LaunchActivityItem類的execute方法。

@Override
71 public void execute(ClientTransactionHandler client, IBinder token,
72 PendingTransactionActions pendingActions) {
73 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, “activityStart”);
74 ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
75 mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
76 mPendingResults, mPendingNewIntents, mIsForward,
77 mProfilerInfo, client);
78 client.handleLaunchActivity(r, pendingActions, null /* customIntent /);
79 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
80 }
ClientTransactionHandler 是ActivityThread的父類,執行 client.handleLaunchActivity(r, pendingActions, null /
customIntent */);的時候又會重新跳轉到ActivityThread的handleLaunchActivity()方法。

  @Override
3062      public Activity handleLaunchActivity(ActivityClientRecord r,
3063              PendingTransactionActions pendingActions, Intent customIntent) {
3064          // If we are getting ready to gc after going to the background, well
3065          // we are back active so skip it.
3066          unscheduleGcIdler();
3067          mSomeActivitiesChanged = true;
3068  
3069          if (r.profilerInfo != null) {
3070              mProfiler.setProfiler(r.profilerInfo);
3071              mProfiler.startProfiling();
3072          }
3073  
3074          // Make sure we are running with the most recent config.
3075          handleConfigurationChanged(null, null);
3076  
3077          if (localLOGV) Slog.v(
3078              TAG, "Handling launch of " + r);
3079  
3080          // Initialize before creating the activity
3081          if (!ThreadedRenderer.sRendererDisabled) {
3082              GraphicsEnvironment.earlyInitEGL();
3083          }
3084          WindowManagerGlobal.initialize();
3085  
3086          final Activity a = performLaunchActivity(r, customIntent);
3087  
3088          if (a != null) {
3089              r.createdConfig = new Configuration(mConfiguration);
3090              reportSizeConfigurations(r);
3091              if (!r.activity.mFinished && pendingActions != null) {
3092                  pendingActions.setOldState(r.state);
3093                  pendingActions.setRestoreInstanceState(true);
3094                  pendingActions.setCallOnPostCreate(true);
3095              }
3096          } else {
3097              // If there was an error, for any reason, tell the activity manager to stop us.
3098              try {
3099                  ActivityManager.getService()
3100                          .finishActivity(r.token, Activity.RESULT_CANCELED, null,
3101                                  Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
3102              } catch (RemoteException ex) {
3103                  throw ex.rethrowFromSystemServer();
3104              }
3105          }
3106  
3107          return a;
3108      }
3109  
final Activity a = performLaunchActivity(r, customIntent);這句代碼就是得到一個Activity對象。我們進入performLaunchActivity會發現Activity的創建與Application相似,也是通過類加載器和反射創建的。我們可以看下這個方法的代碼
   ContextImpl appContext = createBaseContextForActivity(r);
2866          Activity activity = null;
2867          try {
2868              java.lang.ClassLoader cl = appContext.getClassLoader();
2869              activity = mInstrumentation.newActivity(
2870                      cl, component.getClassName(), r.intent);
2871              StrictMode.incrementExpectedActivityCount(activity.getClass());
2872              r.intent.setExtrasClassLoader(cl);
2873              r.intent.prepareToEnterProcess();
2874              if (r.state != null) {
2875                  r.state.setClassLoader(cl);
2876              }
2877          } catch (Exception e) {
2878              if (!mInstrumentation.onException(activity, e)) {
2879                  throw new RuntimeException(
2880                      "Unable to instantiate activity " + component
2881                      + ": " + e.toString(), e);
2882              }
2883          }
2884  

繼續查看該方法,會發現下面這句代碼

  if (r.isPersistable()) {
2929                      mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
2930                  } else {
2931                      mInstrumentation.callActivityOnCreate(activity, r.state);
2932                  }

我們進入callActivityOnCreate(activity, r.state, r.persistentState);方法。它是Instrumentation類的方法,我們看下方法體

 public void callActivityOnCreate(Activity activity, Bundle icicle) {
1270          prePerformCreate(activity);
1271          activity.performCreate(icicle);
1272          postPerformCreate(activity);
1273      }

activity.performCreate(icicle);就是調用Activity的perform方法。我們看下這個方法

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
7139          mCanEnterPictureInPicture = true;
7140          restoreHasCurrentPermissionRequest(icicle);
7141          if (persistentState != null) {
7142              onCreate(icicle, persistentState);
7143          } else {
7144              onCreate(icicle);
7145          }
7146          writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
7147          mActivityTransitionState.readState(icicle);
7148  
7149          mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
7150                  com.android.internal.R.styleable.Window_windowNoDisplay, false);
7151          mFragments.dispatchActivityCreated();
7152          mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
7153      }
7154  

onCreate(icicle, persistentState);調用Activity的onCreate()。這樣,我們的Activity終於創建成功了。
在這裏插入圖片描述

第三Activity其它的生命週期的加載

我們看下Activity其它的生命週期的加載。在ActivityThread中在調用mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);方法之後可以設置狀態。

 r.setState(ON_CREATE);


 r.setState(ON_START);



 r.setState(ON_RESUME);



r.setState(ON_PAUSE);



  r.setState(ON_STOP);



   r.setState(ON_DESTROY);

那這些狀態有什麼用呢?我們回到TransactionExecutor類,看下這個方法

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

executeCallbacks(transaction);是創建Activity以及onCreate方法的調用;其它的生命週期的調用是在 executeLifecycleState(transaction);我們打開這個方法,查看它的方法體

  /** Transition to the final state if requested by the transaction. */
    private void executeLifecycleState(ClientTransaction transaction) {
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        if (lifecycleItem == null) {
            // No lifecycle request, return early.
            return;
        }
        final IBinder token = transaction.getActivityToken();
        final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
        if (DEBUG_RESOLVER) {
            Slog.d(TAG, tId(transaction) + "Resolving lifecycle state: "
                    + lifecycleItem + " for activity: "
                    + getShortActivityName(token, mTransactionHandler));
        }
        if (r == null) {
            // Ignore requests for non-existent client records for now.
            return;
        }
        // Cycle to the state right before the final requested state.
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
        // Execute the final transition with proper parameters.
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }

final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();得到ActivityLifecycleItem 對象,這裏有一個關鍵的方法cycleToPath();我們進入查看這個方法體

 private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
            ClientTransaction transaction) {
        final int start = r.getLifecycleState();
        if (DEBUG_RESOLVER) {
            Slog.d(TAG, tId(transaction) + "Cycle activity: "
                    + getShortActivityName(r.token, mTransactionHandler)
                    + " from: " + getStateName(start) + " to: " + getStateName(finish)
                    + " excludeLastState: " + excludeLastState);
        }
        final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
        performLifecycleSequence(r, path, transaction);
    }

final int start = r.getLifecycleState();首先拿到getLifecycleState()的狀態。打個斷點第一次運行到這裏,會發現start是1,1就是ON_CREATE(ON_START,ON_RESUME,ON_PAUSE,ON_STOP,ON_DESTROY,ON_RESTART依次是2、3、4、5、6、7);
然後執行這句代碼 final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);我們看下TransactionExecutorHelper(mHelper是該類的一個對象)類的getLifecyclePath();

 @VisibleForTesting
    public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
        if (start == UNDEFINED || finish == UNDEFINED) {
            throw new IllegalArgumentException("Can't resolve lifecycle path for undefined state");
        }
        if (start == ON_RESTART || finish == ON_RESTART) {
            throw new IllegalArgumentException(
                    "Can't start or finish in intermittent RESTART state");
        }
        if (finish == PRE_ON_CREATE && start != finish) {
            throw new IllegalArgumentException("Can only start in pre-onCreate state");
        }
        mLifecycleSequence.clear();
        if (finish >= start) {
            // just go there
            for (int i = start + 1; i <= finish; i++) {
                mLifecycleSequence.add(i);
            }
        } else { // finish < start, can't just cycle down
            if (start == ON_PAUSE && finish == ON_RESUME) {
                // Special case when we can just directly go to resumed state.
                mLifecycleSequence.add(ON_RESUME);
            } else if (start <= ON_STOP && finish >= ON_START) {
                // Restart and go to required state.
                // Go to stopped state first.
                for (int i = start + 1; i <= ON_STOP; i++) {
                    mLifecycleSequence.add(i);
                }
                // Restart
                mLifecycleSequence.add(ON_RESTART);
                // Go to required state
                for (int i = ON_START; i <= finish; i++) {
                    mLifecycleSequence.add(i);
                }
            } else {
                // Relaunch and go to required state
                // Go to destroyed state first.
                for (int i = start + 1; i <= ON_DESTROY; i++) {
                    mLifecycleSequence.add(i);
                }
                // Go to required state
                for (int i = ON_CREATE; i <= finish; i++) {
                    mLifecycleSequence.add(i);
                }
            }
        }
        // Remove last transition in case we want to perform it with some specific params.
        if (excludeLastState && mLifecycleSequence.size() != 0) {
            mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
        }
        return mLifecycleSequence;
    }

該方法需要傳入start和finish 兩個值,start我們在前面已經介紹過,那麼finish又指的是3,即ON_RESUME。
經過一系列的判斷,會執行下面的代碼

     for (int i = start + 1; i <= finish; i++) {
                mLifecycleSequence.add(i);
            }

start+1,即進入下一個狀態。 mLifecycleSequence.add(i);最終添加的是2和3。因爲excludeLastState是true,會執行 mLifecycleSequence.remove(mLifecycleSequence.size() - 1);就是一出最後一個值,我們拿到的最終結果是2.
我們回到方法調用的地方

 private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
            ClientTransaction transaction) {
        final int start = r.getLifecycleState();
        if (DEBUG_RESOLVER) {
            Slog.d(TAG, tId(transaction) + "Cycle activity: "
                    + getShortActivityName(r.token, mTransactionHandler)
                    + " from: " + getStateName(start) + " to: " + getStateName(finish)
                    + " excludeLastState: " + excludeLastState);
        }
        final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
        performLifecycleSequence(r, path, transaction);
    }

繼續往下執行會執行TransactionExecutor類的performLifecycleSequence方法。

  private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
            ClientTransaction transaction) {
        final int size = path.size();
        for (int i = 0, state; i < size; i++) {
            state = path.get(i);
            if (DEBUG_RESOLVER) {
                Slog.d(TAG, tId(transaction) + "Transitioning activity: "
                        + getShortActivityName(r.token, mTransactionHandler)
                        + " to state: " + getStateName(state));
            }
            switch (state) {
                case ON_CREATE:
                    mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                            null /* customIntent */);
                    break;
                case ON_START:
                    mTransactionHandler.handleStartActivity(r, mPendingActions);
                    break;
                case ON_RESUME:
                    mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                            r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                    break;
                case ON_PAUSE:
                    mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
                            false /* userLeaving */, 0 /* configChanges */, mPendingActions,
                            "LIFECYCLER_PAUSE_ACTIVITY");
                    break;
                case ON_STOP:
                    mTransactionHandler.handleStopActivity(r.token, false /* show */,
                            0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
                            "LIFECYCLER_STOP_ACTIVITY");
                    break;
                case ON_DESTROY:
                    mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
                            0 /* configChanges */, false /* getNonConfigInstance */,
                            "performLifecycleSequence. cycling to:" + path.get(size - 1));
                    break;
                case ON_RESTART:
                    mTransactionHandler.performRestartActivity(r.token, false /* start */);
                    break;
                default:
                    throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
            }
        }
    }

final int size = path.size();獲取IntArray的大小, state = path.get(i);然後獲取到狀態。這裏獲取到的狀態是2。會執行
mTransactionHandler.handleStartActivity(r, mPendingActions);mTransactionHandler是ClientTransactionHandler 對象,ClientTransactionHandler 是ActivityThread的父類,所以這裏我們又回到了ActivityThread的代碼。我們看下ActivityThread類的handleStartActivity();

  @Override
    public void handleStartActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions) {
        final Activity activity = r.activity;
        if (r.activity == null) {
            // TODO(lifecycler): What do we do in this case?
            return;
        }
        if (!r.stopped) {
            throw new IllegalStateException("Can't start activity that is not stopped.");
        }
        if (r.activity.mFinished) {
            // TODO(lifecycler): How can this happen?
            return;
        }
        // Start
        activity.performStart("handleStartActivity");
        r.setState(ON_START);
        if (pendingActions == null) {
            // No more work to do.
            return;
        }
        // Restore instance state
        if (pendingActions.shouldRestoreInstanceState()) {
            if (r.isPersistable()) {
                if (r.state != null || r.persistentState != null) {
                    mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                            r.persistentState);
                }
            } else if (r.state != null) {
                mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
            }
        }
        // Call postOnCreate()
        if (pendingActions.shouldCallOnPostCreate()) {
            activity.mCalled = false;
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnPostCreate(activity, r.state,
                        r.persistentState);
            } else {
                mInstrumentation.callActivityOnPostCreate(activity, r.state);
            }
            if (!activity.mCalled) {
                throw new SuperNotCalledException(
                        "Activity " + r.intent.getComponent().toShortString()
                                + " did not call through to super.onPostCreate()");
            }
        }
    }

activity.performStart(“handleStartActivity”);這個方法就是執行Activity的onStart()方法。然後修改下一個狀態 r.setState(ON_START);
onResume()方法的執行原理也是一樣的。我們下面看下onResume()方法是如何被調用的。
我們回到TransactionExecutor

private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
170          final int size = path.size();
171          for (int i = 0, state; i < size; i++) {
172              state = path.get(i);
173              log("Transitioning to state: " + state);
174              switch (state) {
175                  case ON_CREATE:
176                      mTransactionHandler.handleLaunchActivity(r, mPendingActions,
177                              null /* customIntent */);
178                      break;
179                  case ON_START:
180                      mTransactionHandler.handleStartActivity(r, mPendingActions);
181                      break;
182                  case ON_RESUME:
183                      mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
184                              r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
185                      break;
186                  case ON_PAUSE:
187                      mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
188                              false /* userLeaving */, 0 /* configChanges */, mPendingActions,
189                              "LIFECYCLER_PAUSE_ACTIVITY");
190                      break;
191                  case ON_STOP:
192                      mTransactionHandler.handleStopActivity(r.token, false /* show */,
193                              0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
194                              "LIFECYCLER_STOP_ACTIVITY");
195                      break;
196                  case ON_DESTROY:
197                      mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
198                              0 /* configChanges */, false /* getNonConfigInstance */,
199                              "performLifecycleSequence. cycling to:" + path.get(size - 1));
200                      break;
201                  case ON_RESTART:
202                      mTransactionHandler.performRestartActivity(r.token, false /* start */);
203                      break;
204                  default:
205                      throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
206              }
207          }
208      }

這裏執行這個方法。

179                  case ON_START:
180                      mTransactionHandler.handleStartActivity(r, mPendingActions);
181                      break;

我們看下他是如何在ActivityThread中調用的。

 @Override
3846      public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
3847              String reason) {
3848          // If we are getting ready to gc after going to the background, well
3849          // we are back active so skip it.
3850          unscheduleGcIdler();
3851          mSomeActivitiesChanged = true;
3852  
3853          // TODO Push resumeArgs into the activity for consideration
3854          final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
3855          if (r == null) {
3856              // We didn't actually resume the activity, so skipping any follow-up actions.
3857              return;
3858          }
3859  
3860          final Activity a = r.activity;
3861  
3862          if (localLOGV) {
3863              Slog.v(TAG, "Resume " + r + " started activity: " + a.mStartedActivity
3864                      + ", hideForNow: " + r.hideForNow + ", finished: " + a.mFinished);
3865          }
3866  
3867          final int forwardBit = isForward
3868                  ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
3869  
3870          // If the window hasn't yet been added to the window manager,
3871          // and this guy didn't finish itself or start another activity,
3872          // then go ahead and add the window.
3873          boolean willBeVisible = !a.mStartedActivity;
3874          if (!willBeVisible) {
3875              try {
3876                  willBeVisible = ActivityManager.getService().willActivityBeVisible(
3877                          a.getActivityToken());
3878              } catch (RemoteException e) {
3879                  throw e.rethrowFromSystemServer();
3880              }
3881          }
3882          if (r.window == null && !a.mFinished && willBeVisible) {
3883              r.window = r.activity.getWindow();
3884              View decor = r.window.getDecorView();
3885              decor.setVisibility(View.INVISIBLE);
3886              ViewManager wm = a.getWindowManager();
3887              WindowManager.LayoutParams l = r.window.getAttributes();
3888              a.mDecor = decor;
3889              l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
3890              l.softInputMode |= forwardBit;
3891              if (r.mPreserveWindow) {
3892                  a.mWindowAdded = true;
3893                  r.mPreserveWindow = false;
3894                  // Normally the ViewRoot sets up callbacks with the Activity
3895                  // in addView->ViewRootImpl#setView. If we are instead reusing
3896                  // the decor view we have to notify the view root that the
3897                  // callbacks may have changed.
3898                  ViewRootImpl impl = decor.getViewRootImpl();
3899                  if (impl != null) {
3900                      impl.notifyChildRebuilt();
3901                  }
3902              }
3903              if (a.mVisibleFromClient) {
3904                  if (!a.mWindowAdded) {
3905                      a.mWindowAdded = true;
3906                      wm.addView(decor, l);
3907                  } else {
3908                      // The activity will get a callback for this {@link LayoutParams} change
3909                      // earlier. However, at that time the decor will not be set (this is set
3910                      // in this method), so no action will be taken. This call ensures the
3911                      // callback occurs with the decor set.
3912                      a.onWindowAttributesChanged(l);
3913                  }
3914              }
3915  
3916              // If the window has already been added, but during resume
3917              // we started another activity, then don't yet make the
3918              // window visible.
3919          } else if (!willBeVisible) {
3920              if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
3921              r.hideForNow = true;
3922          }
3923  
3924          // Get rid of anything left hanging around.
3925          cleanUpPendingRemoveWindows(r, false /* force */);
3926  
3927          // The window is now visible if it has been added, we are not
3928          // simply finishing, and we are not starting another activity.
3929          if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
3930              if (r.newConfig != null) {
3931                  performConfigurationChangedForActivity(r, r.newConfig);
3932                  if (DEBUG_CONFIGURATION) {
3933                      Slog.v(TAG, "Resuming activity " + r.activityInfo.name + " with newConfig "
3934                              + r.activity.mCurrentConfig);
3935                  }
3936                  r.newConfig = null;
3937              }
3938              if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
3939              WindowManager.LayoutParams l = r.window.getAttributes();
3940              if ((l.softInputMode
3941                      & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
3942                      != forwardBit) {
3943                  l.softInputMode = (l.softInputMode
3944                          & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
3945                          | forwardBit;
3946                  if (r.activity.mVisibleFromClient) {
3947                      ViewManager wm = a.getWindowManager();
3948                      View decor = r.window.getDecorView();
3949                      wm.updateViewLayout(decor, l);
3950                  }
3951              }
3952  
3953              r.activity.mVisibleFromServer = true;
3954              mNumVisibleActivities++;
3955              if (r.activity.mVisibleFromClient) {
3956                  r.activity.makeVisible();
3957              }
3958          }
3959  
3960          r.nextIdle = mNewActivities;
3961          mNewActivities = r;
3962          if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
3963          Looper.myQueue().addIdleHandler(new Idler());
3964      }
3965  

執行的是這個方法。 final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);

 @VisibleForTesting
3775      public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
3776              String reason) {
3777          final ActivityClientRecord r = mActivities.get(token);
3778          if (localLOGV) {
3779              Slog.v(TAG, "Performing resume of " + r + " finished=" + r.activity.mFinished);
3780          }
3781          if (r == null || r.activity.mFinished) {
3782              return null;
3783          }
3784          if (r.getLifecycleState() == ON_RESUME) {
3785              if (!finalStateRequest) {
3786                  final RuntimeException e = new IllegalStateException(
3787                          "Trying to resume activity which is already resumed");
3788                  Slog.e(TAG, e.getMessage(), e);
3789                  Slog.e(TAG, r.getStateString());
3790                  // TODO(lifecycler): A double resume request is possible when an activity
3791                  // receives two consequent transactions with relaunch requests and "resumed"
3792                  // final state requests and the second relaunch is omitted. We still try to
3793                  // handle two resume requests for the final state. For cases other than this
3794                  // one, we don't expect it to happen.
3795              }
3796              return null;
3797          }
3798          if (finalStateRequest) {
3799              r.hideForNow = false;
3800              r.activity.mStartedActivity = false;
3801          }
3802          try {
3803              r.activity.onStateNotSaved();
3804              r.activity.mFragments.noteStateNotSaved();
3805              checkAndBlockForNetworkAccess();
3806              if (r.pendingIntents != null) {
3807                  deliverNewIntents(r, r.pendingIntents);
3808                  r.pendingIntents = null;
3809              }
3810              if (r.pendingResults != null) {
3811                  deliverResults(r, r.pendingResults, reason);
3812                  r.pendingResults = null;
3813              }
3814              r.activity.performResume(r.startsNotResumed, reason);
3815  
3816              r.state = null;
3817              r.persistentState = null;
3818              r.setState(ON_RESUME);
3819          } catch (Exception e) {
3820              if (!mInstrumentation.onException(r.activity, e)) {
3821                  throw new RuntimeException("Unable to resume activity "
3822                          + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
3823              }
3824          }
3825          return r;
3826      }

這個方法就是執行onResume()。 r.activity.performResume(r.startsNotResumed, reason);我們看下在Activity中是如何調用的。

  final void performResume(boolean followedByPause, String reason) {
7282          performRestart(true /* start */, reason);
7283  
7284          mFragments.execPendingActions();
7285  
7286          mLastNonConfigurationInstances = null;
7287  
7288          if (mAutoFillResetNeeded) {
7289              // When Activity is destroyed in paused state, and relaunch activity, there will be
7290              // extra onResume and onPause event,  ignore the first onResume and onPause.
7291              // see ActivityThread.handleRelaunchActivity()
7292              mAutoFillIgnoreFirstResumePause = followedByPause;
7293              if (mAutoFillIgnoreFirstResumePause && DEBUG_LIFECYCLE) {
7294                  Slog.v(TAG, "autofill will ignore first pause when relaunching " + this);
7295              }
7296          }
7297  
7298          mCalled = false;
7299          // mResumed is set by the instrumentation
7300          mInstrumentation.callActivityOnResume(this);
7301          writeEventLog(LOG_AM_ON_RESUME_CALLED, reason);
7302          if (!mCalled) {
7303              throw new SuperNotCalledException(
7304                  "Activity " + mComponent.toShortString() +
7305                  " did not call through to super.onResume()");
7306          }
7307  
7308          // invisible activities must be finished before onResume() completes
7309          if (!mVisibleFromClient && !mFinished) {
7310              Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
7311              if (getApplicationInfo().targetSdkVersion
7312                      > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
7313                  throw new IllegalStateException(
7314                          "Activity " + mComponent.toShortString() +
7315                          " did not call finish() prior to onResume() completing");
7316              }
7317          }
7318  
7319          // Now really resume, and install the current status bar and menu.
7320          mCalled = false;
7321  
7322          mFragments.dispatchResume();
7323          mFragments.execPendingActions();
7324  
7325          onPostResume();
7326          if (!mCalled) {
7327              throw new SuperNotCalledException(
7328                  "Activity " + mComponent.toShortString() +
7329                  " did not call through to super.onPostResume()");
7330          }
7331      }
7332  

mInstrumentation.callActivityOnResume(this);這句代碼就是調用onResume();我們現在回到ActivityThread類。有一個大家都比較感興趣的東東。那就是我們UI的繪製,寫了那麼多,終於到我們本文的主題了。

我們下面的代碼,在Activity執行完onCreate(),onStart(),onResume()後,就會執行這些代碼

@Override
3846      public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
3847              String reason) {
3848          // If we are getting ready to gc after going to the background, well
3849          // we are back active so skip it.
3850          unscheduleGcIdler();
3851          mSomeActivitiesChanged = true;
3852  
3853          // TODO Push resumeArgs into the activity for consideration
3854          final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
3855          if (r == null) {
3856              // We didn't actually resume the activity, so skipping any follow-up actions.
3857              return;
3858          }
3859  
3860          final Activity a = r.activity;
3861  
3862          if (localLOGV) {
3863              Slog.v(TAG, "Resume " + r + " started activity: " + a.mStartedActivity
3864                      + ", hideForNow: " + r.hideForNow + ", finished: " + a.mFinished);
3865          }
3866  
3867          final int forwardBit = isForward
3868                  ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
3869  
3870          // If the window hasn't yet been added to the window manager,
3871          // and this guy didn't finish itself or start another activity,
3872          // then go ahead and add the window.
3873          boolean willBeVisible = !a.mStartedActivity;
3874          if (!willBeVisible) {
3875              try {
3876                  willBeVisible = ActivityManager.getService().willActivityBeVisible(
3877                          a.getActivityToken());
3878              } catch (RemoteException e) {
3879                  throw e.rethrowFromSystemServer();
3880              }
3881          }
3882          if (r.window == null && !a.mFinished && willBeVisible) {
3883              r.window = r.activity.getWindow();
3884              View decor = r.window.getDecorView();
3885              decor.setVisibility(View.INVISIBLE);
3886              ViewManager wm = a.getWindowManager();
3887              WindowManager.LayoutParams l = r.window.getAttributes();
3888              a.mDecor = decor;
3889              l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
3890              l.softInputMode |= forwardBit;
3891              if (r.mPreserveWindow) {
3892                  a.mWindowAdded = true;
3893                  r.mPreserveWindow = false;
3894                  // Normally the ViewRoot sets up callbacks with the Activity
3895                  // in addView->ViewRootImpl#setView. If we are instead reusing
3896                  // the decor view we have to notify the view root that the
3897                  // callbacks may have changed.
3898                  ViewRootImpl impl = decor.getViewRootImpl();
3899                  if (impl != null) {
3900                      impl.notifyChildRebuilt();
3901                  }
3902              }
3903              if (a.mVisibleFromClient) {
3904                  if (!a.mWindowAdded) {
3905                      a.mWindowAdded = true;
3906                      wm.addView(decor, l);
3907                  } else {
3908                      // The activity will get a callback for this {@link LayoutParams} change
3909                      // earlier. However, at that time the decor will not be set (this is set
3910                      // in this method), so no action will be taken. This call ensures the
3911                      // callback occurs with the decor set.
3912                      a.onWindowAttributesChanged(l);
3913                  }
3914              }
3915  
3916              // If the window has already been added, but during resume
3917              // we started another activity, then don't yet make the
3918              // window visible.
3919          } else if (!willBeVisible) {
3920              if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
3921              r.hideForNow = true;
3922          }
3923  
3924          // Get rid of anything left hanging around.
3925          cleanUpPendingRemoveWindows(r, false /* force */);
3926  
3927          // The window is now visible if it has been added, we are not
3928          // simply finishing, and we are not starting another activity.
3929          if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
3930              if (r.newConfig != null) {
3931                  performConfigurationChangedForActivity(r, r.newConfig);
3932                  if (DEBUG_CONFIGURATION) {
3933                      Slog.v(TAG, "Resuming activity " + r.activityInfo.name + " with newConfig "
3934                              + r.activity.mCurrentConfig);
3935                  }
3936                  r.newConfig = null;
3937              }
3938              if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
3939              WindowManager.LayoutParams l = r.window.getAttributes();
3940              if ((l.softInputMode
3941                      & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
3942                      != forwardBit) {
3943                  l.softInputMode = (l.softInputMode
3944                          & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
3945                          | forwardBit;
3946                  if (r.activity.mVisibleFromClient) {
3947                      ViewManager wm = a.getWindowManager();
3948                      View decor = r.window.getDecorView();
3949                      wm.updateViewLayout(decor, l);
3950                  }
3951              }
3952  
3953              r.activity.mVisibleFromServer = true;
3954              mNumVisibleActivities++;
3955              if (r.activity.mVisibleFromClient) {
3956                  r.activity.makeVisible();
3957              }
3958          }
3959  
3960          r.nextIdle = mNewActivities;
3961          mNewActivities = r;
3962          if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
3963          Looper.myQueue().addIdleHandler(new Idler());
3964      }

跟UI相關的邏輯在這裏。

     r.window = r.activity.getWindow();
3884              View decor = r.window.getDecorView();
3885              decor.setVisibility(View.INVISIBLE);
3886              ViewManager wm = a.getWindowManager();
3887              WindowManager.LayoutParams l = r.window.getAttributes();
3888              a.mDecor = decor;
3889              l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
3890              l.softInputMode |= forwardBit;

第四應用中啓動Activity

我們上面寫的是如何在屏幕中啓動Activity,即點擊手機屏幕中的app圖標啓動Activity,但是我們啓動Activity不止是這一種方法,還可以在應用中啓動Activity,比如常見的有startActivty();
我們點擊startActivity();發現它是調用ContextWrapper類的

377      @Override
378      public void startActivity(Intent intent) {
379          mBase.startActivity(intent);
380      }

我們發現 mBase是Context對象;我們繼續跟蹤,來到Context類。

               public abstract void startActivity(@RequiresPermission Intent intent,
1738              @Nullable Bundle options);
1739  
1740      /**

這個方法最終調用是在Activity中的startActivity。因爲activity實現了Context

4872      @Override
4873      public void startActivity(Intent intent) {
4874          this.startActivity(intent, null);
4875      }

繼續往下跟蹤,

 public void startActivity(Intent intent, @Nullable Bundle options) {
4901          if (options != null) {
4902              startActivityForResult(intent, -1, options);
4903          } else {
4904              // Note we want to go through this call for compatibility with
4905              // applications that may have overridden the method.
4906              startActivityForResult(intent, -1);
4907          }
4908      }
4909  

我們可以發現startActivityForResult()也可以啓動Activity。startActivity最終也是調用的startActivityForResult();我們看下Activity的startActivityForResult()的方法。

 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
4583              @Nullable Bundle options) {
4584          if (mParent == null) {
4585              options = transferSpringboardActivityOptions(options);
4586              Instrumentation.ActivityResult ar =
4587                  mInstrumentation.execStartActivity(
4588                      this, mMainThread.getApplicationThread(), mToken, this,
4589                      intent, requestCode, options);
4590              if (ar != null) {
4591                  mMainThread.sendActivityResult(
4592                      mToken, mEmbeddedID, requestCode, ar.getResultCode(),
4593                      ar.getResultData());
4594              }
4595              if (requestCode >= 0) {
4596                  // If this start is requesting a result, we can avoid making
4597                  // the activity visible until the result is received.  Setting
4598                  // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
4599                  // activity hidden during this time, to avoid flickering.
4600                  // This can only be done when a result is requested because
4601                  // that guarantees we will get information back when the
4602                  // activity is finished, no matter what happens to it.
4603                  mStartedActivity = true;
4604              }
4605  
4606              cancelInputsAndStartExitTransition(options);
4607              // TODO Consider clearing/flushing other event sources and events for child windows.
4608          } else {
4609              if (options != null) {
4610                  mParent.startActivityFromChild(this, intent, requestCode, options);
4611              } else {
4612                  // Note we want to go through this method for compatibility with
4613                  // existing applications that may have overridden it.
4614                  mParent.startActivityFromChild(this, intent, requestCode);
4615              }
4616          }
4617      }
4618  

看下這句代碼

  Instrumentation.ActivityResult ar =
4587                  mInstrumentation.execStartActivity(
4588                      this, mMainThread.getApplicationThread(), mToken, this,
4589                      intent, requestCode, options);

我們跟蹤下,會走到Instrumentation類的execStartActivity方法

 public ActivityResult execStartActivity(
1636              Context who, IBinder contextThread, IBinder token, Activity target,
1637              Intent intent, int requestCode, Bundle options) {
1638          IApplicationThread whoThread = (IApplicationThread) contextThread;
1639          Uri referrer = target != null ? target.onProvideReferrer() : null;
1640          if (referrer != null) {
1641              intent.putExtra(Intent.EXTRA_REFERRER, referrer);
1642          }
1643          if (mActivityMonitors != null) {
1644              synchronized (mSync) {
1645                  final int N = mActivityMonitors.size();
1646                  for (int i=0; i<N; i++) {
1647                      final ActivityMonitor am = mActivityMonitors.get(i);
1648                      ActivityResult result = null;
1649                      if (am.ignoreMatchingSpecificIntents()) {
1650                          result = am.onStartActivity(intent);
1651                      }
1652                      if (result != null) {
1653                          am.mHits++;
1654                          return result;
1655                      } else if (am.match(who, null, intent)) {
1656                          am.mHits++;
1657                          if (am.isBlocking()) {
1658                              return requestCode >= 0 ? am.getResult() : null;
1659                          }
1660                          break;
1661                      }
1662                  }
1663              }
1664          }
1665          try {
1666              intent.migrateExtraStreamToClipData();
1667              intent.prepareToLeaveProcess(who);
1668              int result = ActivityManager.getService()
1669                  .startActivity(whoThread, who.getBasePackageName(), intent,
1670                          intent.resolveTypeIfNeeded(who.getContentResolver()),
1671                          token, target != null ? target.mEmbeddedID : null,
1672                          requestCode, 0, null, options);
1673              checkStartActivityResult(result, intent);
1674          } catch (RemoteException e) {
1675              throw new RuntimeException("Failure from system", e);
1676          }
1677          return null;
1678      }

看這句代碼

  int result = ActivityManager.getService()
1669                  .startActivity(whoThread, who.getBasePackageName(), intent,
1670                          intent.resolveTypeIfNeeded(who.getContentResolver()),
1671                          token, target != null ? target.mEmbeddedID : null,
1672                          requestCode, 0, null, options);

又是通過AMS調用。調用了AMS的StartActivity的方法,我們進入 ActivityManagerService 類看下startActivity方法。

public final int startActivity(IApplicationThread caller, String callingPackage,
5089              Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
5090              int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
5091          return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
5092                  resultWho, requestCode, startFlags, profilerInfo, bOptions,
5093                  UserHandle.getCallingUserId());

我們接着看下startActivityAsUser方法。

public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
5106              Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
5107              int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
5108              boolean validateIncomingUser) {
5109          enforceNotIsolatedCaller("startActivity");
5110  
5111          userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
5112                  Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
5113  
5114          // TODO: Switch to user app stacks here.
5115          return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
5116                  .setCaller(caller)
5117                  .setCallingPackage(callingPackage)
5118                  .setResolvedType(resolvedType)
5119                  .setResultTo(resultTo)
5120                  .setResultWho(resultWho)
5121                  .setRequestCode(requestCode)
5122                  .setStartFlags(startFlags)
5123                  .setProfilerInfo(profilerInfo)
5124                  .setActivityOptions(bOptions)
5125                  .setMayWait(userId)
5126                  .execute();
5127  
5128      }
5129  

這裏最終調用的是 mActivityStartController.obtainStarter(intent, “startActivityAsUser”),我們繼續跟蹤mActivityStartController是ActivityStartController的對象,我們看下ActivityStartController類的obtainStarter()方法。

     ActivityStarter obtainStarter(Intent intent, String reason) {
138          return mFactory.obtain().setIntent(intent).setReason(reason);
139      }

我們繼續追蹤代碼,查看ActivityStarter的execute();執行的方法在這裏

 int execute() {
486          try {
487              // TODO(b/64750076): Look into passing request directly to these methods to allow
488              // for transactional diffs and preprocessing.
489              if (mRequest.mayWait) {
490                  return startActivityMayWait(mRequest.caller, mRequest.callingUid,
491                          mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
492                          mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
493                          mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
494                          mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
495                          mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
496                          mRequest.inTask, mRequest.reason,
497                          mRequest.allowPendingRemoteAnimationRegistryLookup,
498                          mRequest.originatingPendingIntent);
499              } else {
500                  return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
501                          mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
502                          mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
503                          mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
504                          mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
505                          mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
506                          mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
507                          mRequest.outActivity, mRequest.inTask, mRequest.reason,
508                          mRequest.allowPendingRemoteAnimationRegistryLookup,
509                          mRequest.originatingPendingIntent);
510              }
511          } finally {
512              onExecutionComplete();
513          }
514      }

mRequest.mayWait爲true,所以會執行startActivityMayWait()方法。
我們看下startActivityMayWait()方法

                private int startActivityMayWait(IApplicationThread caller, int callingUid,
1002              String callingPackage, Intent intent, String resolvedType,
1003              IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
1004              IBinder resultTo, String resultWho, int requestCode, int startFlags,
1005              ProfilerInfo profilerInfo, WaitResult outResult,
1006              Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
1007              int userId, TaskRecord inTask, String reason,
1008              boolean allowPendingRemoteAnimationRegistryLookup,
1009              PendingIntentRecord originatingPendingIntent) {}

這個方法的方法體裏有這樣的代碼

 final ActivityRecord[] outRecord = new ActivityRecord[1];
1156              int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
1157                      voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
1158                      callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
1159                      ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
1160                      allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent);

我們進入startActivity()代碼,發現它會調用到 result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity);
我們在看下startActivityUnchecked();會執行這個方法 mSupervisor.resumeFocusedStackTopActivityLocked();然後我們看下這個方法
額,追蹤到這裏追蹤不下去了,這裏暫時不寫了。抱歉……

第五佈局的加載

我們讓當前activity繼承Activity,點擊setContentView();會進入Activity類,查看源碼

 public void setContentView(@LayoutRes int layoutResID) {
2772          getWindow().setContentView(layoutResID);
2773          initWindowDecorActionBar();
2774      }

getWindow()拿到的是一個Window對象,我們看下它的源碼

 public Window getWindow() {
939          return mWindow;
940      }

Window對象是再attach中創建的,我們看下源碼

final void attach(Context context, ActivityThread aThread,
 ……
7063  
7064          mWindow = new PhoneWindow(this, window, activityConfigCallback);
7065          mWindow.setWindowControllerCallback(this);
7066          mWindow.setCallback(this);
7067          mWindow.setOnWindowDismissedCallback(this);
7068          mWindow.getLayoutInflater().setPrivateFactory(this);
……
}

我們在看下PhoneWindow對象的setContentVIew();

  @Override
405      public void setContentView(int layoutResID) {
406          // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
407          // decor, when theme attributes and the like are crystalized. Do not check the feature
408          // before this happens.
409          if (mContentParent == null) {
410              installDecor();
411          } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
412              mContentParent.removeAllViews();
413          }
414  
415          if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
416              final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
417                      getContext());
418              transitionTo(newScene);
419          } else {
420              mLayoutInflater.inflate(layoutResID, mContentParent);
421          }
422          mContentParent.requestApplyInsets();
423          final Callback cb = getCallback();
424          if (cb != null && !isDestroyed()) {
425              cb.onContentChanged();
426          }
427          mContentParentExplicitlySet = true;
428      }

我們這裏講解下mContentParent ,首先一個界面是分爲好多層的,我這裏有一張圖
在這裏插入圖片描述
if (mContentParent == null) {
installDecor();
}
這句代碼就是創建DecorView,該方法依舊在PhoneWindow中,我們看下installDecor()方法的方法體中的兩行代碼。
mDecor = generateDecor(-1);這句代碼是創建DecorView;
mContentParent = generateLayout(mDecor);這句代碼是創建ContentParent ;
我們看下DecorView的創建

  protected DecorView generateDecor(int featureId) {
2293          // System process doesn't have application context and in that case we need to directly use
2294          // the context we have. Otherwise we want the application context, so we don't cling to the
2295          // activity.
2296          Context context;
2297          if (mUseDecorContext) {
2298              Context applicationContext = getContext().getApplicationContext();
2299              if (applicationContext == null) {
2300                  context = getContext();
2301              } else {
2302                  context = new DecorContext(applicationContext, getContext());
2303                  if (mTheme != -1) {
2304                      context.setTheme(mTheme);
2305                  }
2306              }
2307          } else {
2308              context = getContext();
2309          }
2310          return new DecorView(context, featureId, this, getAttributes());
2311      }

代碼很簡單,獲取上下文後直接new DecorView();通過以上代碼我們可以發現一個Activity對應一個Window,還對應一個DecorView。一個應用會有多個界面,每一個界面都對應一個Activity,每一個Activity對象都會有自己對應的window對象和DecorView對象。
我們現在看下,如何創建mContentParent,mContentParent是一個ViewGroup。我們看下PhoneWindow中如何獲取mContentParent的代碼。

 private void installDecor() {
2660          mForceDecorInstall = false;
2661          if (mDecor == null) {
2662              mDecor = generateDecor(-1);
2663              mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
2664              mDecor.setIsRootNamespace(true);
2665              if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
2666                  mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
2667              }
2668          } else {
2669              mDecor.setWindow(this);//若果已經有了,直接設置,不需要在創建
2670          }
2671          if (mContentParent == null) {
2672              mContentParent = generateLayout(mDecor);

mContentParent = generateLayout(mDecor);這段代碼就是創建mContentParent,我們進入PhoneWindow這個類的方法。這個方法很長,就不全貼出來了。
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);在這裏設置佈局。然後return這個contentParent。
現在PhoneWindow類的setContentView方法中的installDecor();就分析完了,我們繼續往下走。會執行到這個方法
mLayoutInflater.inflate(layoutResID, mContentParent);使用佈局加載器把layoutResID添加到mContentParent中。
最後來張圖總結下
在這裏插入圖片描述
首先是一個手機桌面,是一個一個的應用app,點擊打開app應用,就啓動了一個Launch程序,Launch程序是系統裏面的一個app(該app主要是用來顯示已安裝的其它app的界面,也是其它App啓動的一個入口),現在我們打開app3(打開的app3是在launch裏面,不是在app3裏面),當用戶點擊app3的時候,就會發送一條消息到SystemSever裏面的SMS,它們中間是通過binder機制來傳送消息的。然後再由AMS向孵化器發送一條消息,開啓一個新的進程,這個新的進程就是我們的app3。孵化器會調用到app3進程的main方法。應用進程會使用IActivityManager發送一條消息到AMS,AMS會拿到我們當前進程的一個PID,UID等信息,然後通過IApplicationThread發送一條消息給app3,創建Application,並創建Application的生命週期,Activity的創建依舊如此。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章