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 IActivityManagerSingleton =
           new Singleton() {
                @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 {
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 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 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> mLastAssistStructures = new ArrayList<>();
239    private int mLastSessionId;
240    final ArrayMap 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 pendingResults, List 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

你可能感兴趣的:(Activity启动原理分析)