Activity啟動原理分析

從Activity的startActivity開始,根據調用流程來解釋主要類以及重點代碼作用:

1. Activity

   @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            startActivityForResult(intent, -1);
        }
    }




 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            //execStartActivity   
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            if (ar != null) {
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
           ...
            }

        ...
        } else {
          ...
    }

2. Instrumentation

每一個應用程序只有一個Instrumentation對象,每個Activity內都有一個對該對象的引用。Instrumentation可以理解為應用進程的管家,ActivityThread要創建或暫停某個Activity時,都需要通過Instrumentation來進行具體的操作。

public class Instrumentation {
...
    public ActivityResult execStartActivity(
                Context who, IBinder contextThread, IBinder token, Activity target,
                Intent intent, int requestCode, Bundle options) {
            IApplicationThread whoThread = (IApplicationThread) contextThread;
         
            try {
                intent.migrateExtraStreamToClipData();
                intent.prepareToLeaveProcess(who);
                //TODO
                int result = ActivityManager.getService()
                    .startActivity(whoThread, who.getBasePackageName(), intent,
                            intent.resolveTypeIfNeeded(who.getContentResolver()),
                            token, target != null ? target.mEmbeddedID : null,
                            requestCode, 0, null, options);
                checkStartActivityResult(result, intent);
            } 
    }

Instrumentation是啟動Activity的一個實際操作類。
Instrumentation是在任何應用程序運行前進行初始化的,可以用它來檢測系統和應用程序間的交互。每一個activity都會
持有instrumentation的引用,但是整個進程只有一個instrumentation實例,instrumentation相當于一個大管家,管理著
activity和application的生命周期,包括activity的創建。

3. ActivityManager

  public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }
    
  private static final Singleton<IActivityManager> IActivityManagerSingleton =
           new Singleton<IActivityManager>() {
                @Override
               protected IActivityManager create() {
                        //獲取服務端(系統)的Binder對象
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                    //并生成一個Binder的代理對象am。這個asInterface方法就是stub的方法,stub繼承Binder,參數就是服務端Binder對象。
                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
                    return am;
                }
            };
  }
3.1 Singleton
 public abstract class Singleton<T> {
27    private T mInstance;
29    protected abstract T create();
30
31    public final T get() {
32        synchronized (this) {
33            if (mInstance == null) {
34                mInstance = create();
35            }
36            return mInstance;
37        }
38    }
39}

Instrumentation調用其execStartActivity()方法,其內部通過ActivityManager.getService()獲取一個IBinder對象,然后在通過這個對象獲取一個IActivityManager代理對象。通過IBinder機制去調用ActivityManagerService方法

到了這里就引出了一個在Android系統中非常重要的概念:Binder機制。
因為ActivityManagerService(AMS)負責系統中四大組件的啟動、切換、調度及應用程序的管理和調度等工作,Android中最核心的服務。所以Activity啟動一定是要經他手的,但是問題來了,AMS是SystemServer服務進程端,屬于跨進程,如何跨進程通信呢?是不是發現找來找去都找不到IActivityManager?那當然了,這里使用的是AIDL跨進程通信方式,他被寫到了aidl文件里。
上面代碼中IActivityManager.Stub.asInterface(b)返回了一個IActivityManager的代理對象,基于Binder機制,通過調用代理對象的方法,使得AMS對應的方法被調用。所以可以猜出AMS肯定繼承了IActivityManager.Stub,事實也確實如此。

3.2 IActivityManager
public interface IActivityManager extends IInterface {
      
        public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
68            String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flags,
69            ProfilerInfo profilerInfo, Bundle options) throws RemoteException;
70      public int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent,
71            String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flags,
72            ProfilerInfo profilerInfo, Bundle options, int userId) throws RemoteException;
        ....
這個接口類是aidl生成的,定義的方法就是用來app和系統進行Binder通信的。

4. ActivityManagerService (android.service.am)

簡稱AMS,服務端對象,負責系統中所有Activity的生命周期

   public class ActivityManagerService extends IActivityManager.Stub{
    @Override
4461    public final int startActivity(IApplicationThread caller, String callingPackage,
4462            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
4463            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
4464        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
4465                resultWho, requestCode, startFlags, profilerInfo, bOptions,
4466                UserHandle.getCallingUserId());
4467    }
4489    @Override
4490    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
4491            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
4492            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
4493        enforceNotIsolatedCaller("startActivity");
4494        userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
4495                userId, false, ALLOW_FULL_ONLY, "startActivity", null);
4496        // TODO: Switch to user app stacks here.
4497        return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
4498                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
4499                profilerInfo, null, null, bOptions, false, userId, null, null,
4500                "startActivityAsUser");
4501    }}

5. ActivityStarter (android.service.am)

 class ActivityStarter {
 
      final int startActivityMayWait(IApplicationThread caller, int callingUid,
669            String callingPackage, Intent intent, String resolvedType,
670            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
671            IBinder resultTo, String resultWho, int requestCode, int startFlags,
672            ProfilerInfo profilerInfo, WaitResult outResult,
673            Configuration globalConfig, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
674            IActivityContainer iContainer, TaskRecord inTask, String reason) {  
            //省去大量代碼
685      
823            final ActivityRecord[] outRecord = new ActivityRecord[1];    
              
824            int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
825                    aInfo, rInfo, voiceSession, voiceInteractor,
826                    resultTo, resultWho, requestCode, callingPid,
827                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
828                    options, ignoreTargetSecurity, componentSpecified, outRecord, container,
829                    inTask, reason);
830
888    }
    
}
   int  startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
257            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
258            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
259            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
260            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
261            ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
262            ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
263            TaskRecord inTask, String reason) {
264
265        if (TextUtils.isEmpty(reason)) {
266            throw new IllegalArgumentException("Need to specify a reason.");
267        }
268        mLastStartReason = reason;
269        mLastStartActivityTimeMs = System.currentTimeMillis();
270        mLastStartActivityRecord[0] = null;
271
272        mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
273                aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
274                callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
275                options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
276                container, inTask);
277
278        if (outActivity != null) {
279            // mLastStartActivityRecord[0] is set in the call to startActivity above.
280            outActivity[0] = mLastStartActivityRecord[0];
281        }
282        return mLastStartActivityResult;
 
  private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
996            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
997            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
998            ActivityRecord[] outActivity) {
999        int result = START_CANCELED;
1000        try {
1001            mService.mWindowManager.deferSurfaceLayout();
1002            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
1003                    startFlags, doResume, options, inTask, outActivity);
1004        } finally {
1005            // If we are not able to proceed, disassociate the activity from the task. Leaving an
1006            // activity in an incomplete state can lead to issues, such as performing operations
1007            // without a window container.
1008            if (!ActivityManager.isStartResultSuccessful(result)
1009                    && mStartActivity.getTask() != null) {
1010                mStartActivity.getTask().removeActivity(mStartActivity);
1011            }
1012            mService.mWindowManager.continueSurfaceLayout();
1013        }
1014
1015        postStartActivityProcessing(r, result, mSupervisor.getLastStack().mStackId,  mSourceRecord,
1016                mTargetStack);
1017
1018        return result;
1019    }

  // Note: This method should only be called from {@link startActivity}.
1022    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
1023            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
1024            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
1025            ActivityRecord[] outActivity) {
         //這里面有對不同啟動模式的不同棧的處理。關鍵方法如下:
        ...
        mSupervisor.resumeFocusedStackTopActivityLocked()
        ...

6. ActivityStackSupervisor

    boolean resumeFocusedStackTopActivityLocked() {
2056        return resumeFocusedStackTopActivityLocked(null, null, null);
2057    }
2058
2059    boolean resumeFocusedStackTopActivityLocked(
2060            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
2061        if (targetStack != null && isFocusedStack(targetStack)) {
2062            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
2063        }
2064        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
2065        if (r == null || r.state != RESUMED) {
2066            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
2067        } else if (r.state == RESUMED) {
2068            // Kick off any lingering app transitions form the MoveTaskToFront operation.
2069            mFocusedStack.executeAppTransition(targetOptions);
2070        }
2071        return false;
2072    }  
   

7. ActivityStack(st?k)

Activity在AMS的棧管理,用來記錄已經啟動的Activity的先后關系,狀態信息等。通過ActivityStack決定是否需要啟動新的進程。

    class ActivityStack<T extends StackWindowController> extends ConfigurationContainer
145        implements StackWindowListener {
            ...
      boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
2206        if (mStackSupervisor.inResumeTopActivity) {
2207            // Don't even start recursing.
2208            return false;
2209        }
2210
2211        boolean result = false;
2212        try {
2213            // Protect against recursion.
2214            mStackSupervisor.inResumeTopActivity = true;
2215            result = resumeTopActivityInnerLocked(prev, options);
2216        } finally {
2217            mStackSupervisor.inResumeTopActivity = false;
2218        }
2219        // When resuming the top activity, it may be necessary to pause the top activity (for
2220        // example, returning to the lock screen. We suppress the normal pause logic in
2221        // {@link #resumeTopActivityUncheckedLocked}, since the top activity is resumed at the end.
2222        // We call the {@link ActivityStackSupervisor#checkReadyForSleepLocked} again here to ensure
2223        // any necessary pause logic occurs.
2224        mStackSupervisor.checkReadyForSleepLocked();
2225
2226        return result;
2227    }
2
    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
2241    
2248
        ...
           mStackSupervisor.startSpecificActivityLocked(next, true, true);
2664        }
2250
這里代碼太多,簡要說下這里遇到了生命周期方法,也就是說我們在啟動一個Activity的時候最先被執行的是棧頂的Activity的onPause方法,后當前Activity的Resume

8.又到 ActivityStackSupervisor

         void startSpecificActivityLocked(ActivityRecord r,
1553            boolean andResume, boolean checkConfig) {
1554        // Is this activity's application already running?
1555        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
1556                r.info.applicationInfo.uid, true);
1557
1558        r.getStack().setLaunchTime(r);
1559
1560        if (app != null && app.thread != null) {
1561            try {
1562                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1563                        || !"android".equals(r.info.packageName)) {
1564                    // Don't add this if it is a platform component that is marked
1565                    // to run in multiple processes, because this is actually
1566                    // part of the framework so doesn't make sense to track as a
1567                    // separate apk in the process.
1568                    app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1569                            mService.mProcessStats);
1570                }
1571                realStartActivityLocked(r, app, andResume, checkConfig);
1572                return;
1573            } catch (RemoteException e) {
1574                Slog.w(TAG, "Exception when starting activity "
1575                        + r.intent.getComponent().flattenToShortString(), e);
1576            }
1577
1578            // If a dead object exception was thrown -- fall through to
1579            // restart the application.
1580        }
1581
1582        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
1583                "activity", r.intent.getComponent(), false, false, true);
1584    }
 final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1326            boolean andResume, boolean checkConfig) throws RemoteException {
        ...
        
1467            app.thread.==scheduleLaunchActivity==(new Intent(r.intent), r.appToken,
1468                    System.identityHashCode(r), r.info,
1469                    // TODO: Have this take the merged configuration instead of separate global and
1470                    // override configs.
1471                    mergedConfiguration.getGlobalConfiguration(),
1472                    mergedConfiguration.getOverrideConfiguration(), r.compat,
1473                    r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
1474                    r.persistentState, results, newIntents, !andResume,
1475                    mService.isNextTransitionForward(), profilerInfo);
}
變量app是一個ProcessRecord對象,它的成員變量thread是IApplicationThread類型,ApplicationThread繼承了IApplicationThread.Stub。
因此app.thread是一個IApplicationThread的代理對象。
和IActivityManager一樣,app.thread調用scheduleLaunchActivity方法,
通過Binder機制,會使ApplicationThread的scheduleLaunchActivity方法被調用。
由此實現了又一次進程間的通信,將啟動Activity的操作交給了ApplicationThread類。

通過IActivityManager→ActivityManagerService實現了應用進程與SystemServer進程的通訊 
通過AppicationThread ← IApplicationThread實現了SystemServer進程與應用進程的通訊

ApplicationThread是ActivityThread的內部類,因此ApplicationThread可以調用外部類ActivityThread的方法,
也就是說,啟動Activity的操作交給了ActivityThread來處理。

9. ActivityThread

    public final class ActivityThread {
       private ContextImpl mSystemContext;
225    private ContextImpl mSystemUiContext;
226
227    static volatile IPackageManager sPackageManager;
228
229    final ApplicationThread mAppThread = new ApplicationThread();
230    final Looper mLooper = Looper.myLooper();
231    final H mH = new H();
232    final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
233    // List of new activities (via ActivityRecord.nextIdle) that should
234    // be reported when next we idle.
235    ActivityClientRecord mNewActivities = null;
236    // Number of activities that are currently visible on-screen.
237  
238    ArrayList<WeakReference<AssistStructure>> mLastAssistStructures = new ArrayList<>();
239    private int mLastSessionId;
240    final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
    }
//ApplicationThread是繼承IApplicationThread.stub
AMS就是通過這個ApplicationThread的代理類實現與ActivityThread的交互。
 private class ApplicationThread extends IApplicationThread.Stub {
 
   // we use token to identify this activity without having to send the
749        // activity itself back to the activity manager. (matters more with ipc)
750        @Override
751        public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
752                ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
753                CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
754                int procState, Bundle state, PersistableBundle persistentState,
755                List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
756                boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
757
758            updateProcessState(procState, false);
759
760            ActivityClientRecord r = new ActivityClientRecord();
761
762            r.token = token;
763            r.ident = ident;
764            r.intent = intent;
765            r.referrer = referrer;
766            r.voiceInteractor = voiceInteractor;
767            r.activityInfo = info;
768            r.compatInfo = compatInfo;
769            r.state = state;
770            r.persistentState = persistentState;
771
772            r.pendingResults = pendingResults;
773            r.pendingIntents = pendingNewIntents;
774
775            r.startsNotResumed = notResumed;
776            r.isForward = isForward;
777
778            r.profilerInfo = profilerInfo;
779
780            r.overrideConfig = overrideConfig;
781            updatePendingConfiguration(curConfig);
782
783            sendMessage(H.LAUNCH_ACTIVITY, r);
784        }
 
       public final void schedulePauseActivity(IBinder token, boolean finished,
700                boolean userLeaving, int configChanges, boolean dontReport) {
701            int seq = getLifecycleSeq();
702            if (DEBUG_ORDER) Slog.d(TAG, "pauseActivity " + ActivityThread.this
703                    + " operation received seq: " + seq);
704            sendMessage(
705                    finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
706                    token,
707                    (userLeaving ? USER_LEAVING : 0) | (dontReport ? DONT_REPORT : 0),
708                    configChanges,
709                    seq);
710        }
711
712        public final void scheduleStopActivity(IBinder token, boolean showWindow,
713                int configChanges) {
714            int seq = getLifecycleSeq();
715            if (DEBUG_ORDER) Slog.d(TAG, "stopActivity " + ActivityThread.this
716                    + " operation received seq: " + seq);
717            sendMessage(
718                showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
719                token, 0, configChanges, seq);
720        }
721
 }    public final void scheduleResumeActivity(IBinder token, int processState,
733                boolean isForward, Bundle resumeArgs) {
734            int seq = getLifecycleSeq();
735            if (DEBUG_ORDER) Slog.d(TAG, "resumeActivity " + ActivityThread.this
736                    + " operation received seq: " + seq);
737            updateProcessState(processState, false);
738            sendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0, 0, seq);
739        }

740     //最終是mH.sendMessage(msg),也就是說H這個類接收了消息
     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);
}

    private class H extends Handler {
//將打開Activity的必要參數拿出來,調用ActivityThread$handleLaunchActivity方法啟動Activity
        ...
        public void handleMessage(Message msg) {
                if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
                switch (msg.what) {
                    case LAUNCH_ACTIVITY: {
                        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                        final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
                        r.packageInfo = getPackageInfoNoCheck(
                                r.activityInfo.applicationInfo, r.compatInfo);
                        handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
                        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    } break;

        ...

    }
        //handleMessage()調用了ActivityThread的handleLaunchActivity方法
        private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
2873        ...
2883        // Make sure we are running with the most recent config.
2884        handleConfigurationChanged(null, null);
2885
2886        if (localLOGV) Slog.v(
2887            TAG, "Handling launch of " + r);
2888
2889        // Initialize before creating the activity
2890        WindowManagerGlobal.initialize();
2891
2892        Activity a = performLaunchActivity(r, customIntent);
2893
2894        if (a != null) {
2895            r.createdConfig = new Configuration(mConfiguration);
2896            reportSizeConfigurations(r);
2897            Bundle oldState = r.state;
2898            handleResumeActivity(r.token, false, r.isForward,
2899                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
2900
2901            if (!r.activity.mFinished && r.startsNotResumed) {
2902                // The activity manager actually wants this one to start out paused, because it
2903                // needs to be visible but isn't in the foreground. We accomplish this by going
2904                // through the normal startup (because activities expect to go through onResume()
2905                // the first time they run, before their window is displayed), and then pausing it.
2906                // However, in this case we do -not- need to do the full pause cycle (of freezing
2907                // and such) because the activity manager assumes it can just retain the current
2908                // state it has.
2909                performPauseActivityIfNeeded(r, reason);
2910
2911                // We need to keep around the original state, in case we need to be created again.
2912                // But we only do this for pre-Honeycomb apps, which always save their state when
2913                // pausing, so we can not have them save their state when restarting from a paused
2914                // state. For HC and later, we want to (and can) let the state be saved as the
2915                // normal part of stopping the activity.
2916                if (r.isPreHoneycomb()) {
2917                    r.state = oldState;
2918                }
2919            }
2920        } else {
2921            // If there was an error, for any reason, tell the activity manager to stop us.
2922            try {
2923                ActivityManager.getService()
2924                    .finishActivity(r.token, Activity.RESULT_CANCELED, null,
2925                            Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
2926            } catch (RemoteException ex) {
2927                throw ex.rethrowFromSystemServer();
2928            }
2929        }
2930    }
2931
    performLaunchActivity方法啟動Activity。若Activity不為空,
    則調用handleResumeActivity方法,內部會調用Activity$onResume方法。
    當Activity為空,也就是創建Activity的實例出錯了,最終會調用ActivityManagerService$finishActivity方法。
    也就是說,當創建Activity實例出錯后,停止啟動Activity的具體操作交給ActivityManagerService來處理。

 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
       ActivityInfo aInfo = r.activityInfo;
2687        if (r.packageInfo == null) {
                //獲取LoadedApk對象,表示加載過的 Apk ,通常一個 App 對應著一個 LoadedApk
2688            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
2689                    Context.CONTEXT_INCLUDE_CODE);
2690        }
2691
2692        ComponentName component = r.intent.getComponent();
2693        if (component == null) {
2694            component = r.intent.resolveActivity(
2695                mInitialApplication.getPackageManager());
2696            r.intent.setComponent(component);
2697        }
2698
2699        if (r.activityInfo.targetActivity != null) {
2700            component = new ComponentName(r.activityInfo.packageName,
2701                    r.activityInfo.targetActivity);
2702        }
2703        //創建ContextImpl對象
2704        ContextImpl appContext = createBaseContextForActivity(r);
2705        Activity activity = null;
2706        try {
2707            java.lang.ClassLoader cl = appContext.getClassLoader();
             // 反射創建 Activity 對象
2708            activity = mInstrumentation.newActivity(
2709                    cl, component.getClassName(), r.intent);
2710            StrictMode.incrementExpectedActivityCount(activity.getClass());
2711            r.intent.setExtrasClassLoader(cl);
2712            r.intent.prepareToEnterProcess();
2713            if (r.state != null) {
2714                r.state.setClassLoader(cl);
2715            }
2716        } catch (Exception e) {
2717            if (!mInstrumentation.onException(activity, e)) {
2718                throw new RuntimeException(
2719                    "Unable to instantiate activity " + component
2720                    + ": " + e.toString(), e);
2721            }
2722        }
2723
2724        try {
                //使用LoadedApk中創建Application,也是反射
2725            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
2726
2727         
2734
2735            if (activity != null) {
2736                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
2737                Configuration config = new Configuration(mCompatConfiguration);
2738                if (r.overrideConfig != null) {
2739                    config.updateFrom(r.overrideConfig);
2740                }
2741                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
2742                        + r.activityInfo.name + " with config " + config);
2743                Window window = null;
2744                if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
2745                    window = r.mPendingRemoveWindow;
2746                    r.mPendingRemoveWindow = null;
2747                    r.mPendingRemoveWindowManager = null;
2748                }
2749                appContext.setOuterContext(activity);
                    //綁定Actiity
2750                activity.attach(appContext, this, getInstrumentation(), r.token,
2751                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
2752                        r.embeddedID, r.lastNonConfigurationInstances, config,
2753                        r.referrer, r.voiceInteractor, window, r.configCallback);
2754
2755                if (customIntent != null) {
2756                    activity.mIntent = customIntent;
2757                }
2758                r.lastNonConfigurationInstances = null;
2759                checkAndBlockForNetworkAccess();
2760                activity.mStartedActivity = false;
2761                int theme = r.activityInfo.getThemeResource();
2762                if (theme != 0) {
2763                    activity.setTheme(theme);
2764                }
2765
2766                activity.mCalled = false;
                   // 回調 onCreate()
2767                if (r.isPersistable()) {
2768                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
2769                } else {
2770                    mInstrumentation.callActivityOnCreate(activity, r.state);
2771                }
2772                if (!activity.mCalled) {
2773                    throw new SuperNotCalledException(
2774                        "Activity " + r.intent.getComponent().toShortString() +
2775                        " did not call through to super.onCreate()");
2776                }
2777                r.activity = activity;
2778                r.stopped = true;
2779                if (!r.activity.mFinished) {
2780                    activity.performStart();
2781                    r.stopped = false;
2782                }
2783                if (!r.activity.mFinished) {
2784                    if (r.isPersistable()) {
2785                        if (r.state != null || r.persistentState != null) {
2786                            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
2787                                    r.persistentState);
2788                        }
2789                    } else if (r.state != null) {
2790                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2791                    }
2792                }
2793                if (!r.activity.mFinished) {
2794                    activity.mCalled = false;
2795                    if (r.isPersistable()) {
2796                        mInstrumentation.callActivityOnPostCreate(activity, r.state,
2797                                r.persistentState);
2798                    } else {
2799                        mInstrumentation.callActivityOnPostCreate(activity, r.state);
2800                    }
2801                    
2806                }
2807            }
2808            r.paused = true;
2809
2810            mActivities.put(r.token, r);
2811
2812    
2821        }
2822
2823        return activity;
2824    }
  
 }
 獲取要啟動的Activity的ComponentName對象:里面包含了包名,類名相關的信息;
 調用mInstrumentation.newActivity方法,attach方法后啟動Activity(調用Instrumentation$callActivityOnCreate方法)
//LoaderApk
  public Application makeApplication(boolean forceDefaultAppClassInstrumentation instrumentation) {
    
948         ...
949        Application app = null;
                     ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
965            app = mActivityThread.mInstrumentation.newApplication(
966                    cl, appClass, appContext);
967            appContext.setOuterContext(app);
            ...
             instrumentation.callApplicationOnCreate(app);
}
        //Activity
              final void attach(Context context, ActivityThread aThread,
6903            Instrumentation instr, IBinder token, int ident,
6904            Application application, Intent intent, ActivityInfo info,
6905            CharSequence title, Activity parent, String id,
6906            NonConfigurationInstances lastNonConfigurationInstances,
6907            Configuration config, String referrer, IVoiceInteractor voiceInteractor,
6908            Window window, ActivityConfigCallback activityConfigCallback) {
                //將contextImpl綁定到這個Activity。
6909        attachBaseContext(context);
6910
6911        mFragments.attachHost(null /*parent*/);

6912        //創建了PhoneWindow,PhoneWindow是Window唯一實現類
6913        mWindow = new PhoneWindow(this, window, activityConfigCallback);
6914        mWindow.setWindowControllerCallback(this);
6915        mWindow.setCallback(this);
6916        mWindow.setOnWindowDismissedCallback(this);
6917        mWindow.getLayoutInflater().setPrivateFactory(this);
6918        if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
6919            mWindow.setSoftInputMode(info.softInputMode);
6920        }
6921        if (info.uiOptions != 0) {
6922            mWindow.setUiOptions(info.uiOptions);
6923        }
6924        mUiThread = Thread.currentThread();
6925
6926        mMainThread = aThread;
6927        mInstrumentation = instr;
6928        mToken = token;
6929        mIdent = ident;
6930        mApplication = application;
6931        mIntent = intent;
6932        mReferrer = referrer;
6933        mComponent = intent.getComponent();
6934        mActivityInfo = info;
6935        mTitle = title;
6936        mParent = parent;
6937        mEmbeddedID = id;
6938        mLastNonConfigurationInstances = lastNonConfigurationInstances;
6939        if (voiceInteractor != null) {
6940            if (lastNonConfigurationInstances != null) {
6941                mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
6942            } else {
6943                mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
6944                        Looper.myLooper());
6945            }
6946        }
6947        //設置WindowManager
6948        mWindow.setWindowManager(
6949                (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
6950                mToken, mComponent.flattenToString(),
6951                (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
6952        if (mParent != null) {
6953            mWindow.setContainer(mParent.getWindow());
6954        }
6955        mWindowManager = mWindow.getWindowManager();
6956        mCurrentConfig = config;
6957
6958        mWindow.setColorMode(info.colorMode);
6959    }
public class Instrumentation {
    ...
    public Activity newActivity(ClassLoader cl, String className,Intent intent)throws InstantiationException, IllegalAccessException,
            ClassNotFoundException {
            return (Activity)cl.loadClass(className).newInstance();
    }
    ...
    static public Application newApplication(Class<?> clazz, Context context)throws InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        Application app = (Application)clazz.newInstance();
        app.attach(context);
        return app;
    }
    ...
    
    public void callActivityOnCreate(Activity activity, Bundle icicle,
1225            PersistableBundle persistentState) {
1226        prePerformCreate(activity);
            //準備創建
1227        activity.performCreate(icicle, persistentState);
1228        postPerformCreate(activity);
1229    }
}

10. Activity

//Activity,最終調用了onCreate()方法
  final void performCreate(Bundle icicle) {
6974        restoreHasCurrentPermissionRequest(icicle);
6975        onCreate(icicle);
6976        mActivityTransitionState.readState(icicle);
6977        performCreateCommon();
6978    }
6979
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,825評論 6 546
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,814評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 178,980評論 0 384
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 64,064評論 1 319
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,779評論 6 414
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,109評論 1 330
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,099評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,287評論 0 291
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,799評論 1 338
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,515評論 3 361
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,750評論 1 375
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,221評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,933評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,327評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,667評論 1 296
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,492評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,703評論 2 380

推薦閱讀更多精彩內容