Activity启动的源码分析 基于android SDK 27

Android 7.0版本对代码做了一些封装,把启动Activity的任务交给ApplicationThread来处理。(ApplicationThread是ActivityThread的内部类)
1.整体启动流程 :

//  Activity :
1、startActivity(intent); --> 
2、context.startActivity(intent, null); -->
3、startActivityForResult(intent, -1, options); --> 
4、startActivityForResult(intent, requestCode, null); -->
5、mInstrumentation.execStartActivity(this,mMainThread.getApplicationThread(), 
                mToken, this,intent, requestCode, options); -->
//  Instrumentation :
6、ActivityManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options); -->
//  ActivityManagerService :
7、startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions,
                UserHandle.getCallingUserId()); -->
8、mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                profilerInfo, null, null, bOptions, false, userId, null, "startActivityAsUser"); -->
// ctivityStarter :
9、startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
                    aInfo, rInfo, voiceSession, voiceInteractor,
                    resultTo, resultWho, requestCode, callingPid,
                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                    options, ignoreTargetSecurity, componentSpecified, outRecord, inTask,
                    reason); -->
10、startActivity(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                inTask); -->
11、doPendingActivityLaunchesLocked(false); -->
12、startActivity(pal.r, pal.sourceRecord, null, null, pal.startFlags, resume, null,
                        null, null /*outRecords*/); -->
13、startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity); -->
14、mSupervisor.resumeFocusedStackTopActivityLocked(); -->
// ActivityStackSupervisor :
15、resumeFocusedStackTopActivityLocked(null, null, null); -->
16、mFocusedStack.resumeTopActivityUncheckedLocked(null, null); -->
//  ActivityStack :
17、resumeTopActivityInnerLocked(prev, options); -->
      1)、final ActivityRecord next = topRunningActivityLocked(true);
18、mStackSupervisor.startSpecificActivityLocked(next, true, true); -->
// ActivityStackSupervisor :
19、realStartActivityLocked(r, app, andResume, checkConfig); -->
20、app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                        System.identityHashCode(r), r.info,
                        mergedConfiguration.getGlobalConfiguration(),
                        mergedConfiguration.getOverrideConfiguration(), r.compat,
                        r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                        r.persistentState, results, newIntents, !andResume,
                        mService.isNextTransitionForward(), profilerInfo); -->
      // 用于封装启动Activity需要的一些参数值。
      1) 、ActivityClientRecord r = new ActivityClientRecord();
// ActivityThread.ApplicationThread :
21、sendMessage(H.LAUNCH_ACTIVITY, r); -->
22、sendMessage(what, obj, 0, 0, false); -->
23、mH.sendMessage(msg); -->
24、handleMessage(msg) -->
25、handleLaunchActivity(r, null, "LAUNCH_ACTIVITY"); -->
26、Activity a = performLaunchActivity(r, customIntent); -->
    1)、ContextImpl appContext = createBaseContextForActivity(r);
    2)、activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent); -->
          public Activity newActivity(ClassLoader cl, String className,Intent intent)throws InstantiationException, IllegalAccessException,ClassNotFoundException {
            return (Activity)cl.loadClass(className).newInstance();
          }
    3)、Application app = r.packageInfo.makeApplication(false, mInstrumentation);
    4)、activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);
      // Instrumentation :
    5)、mInstrumentation.callActivityOnCreate(activity, r.state); -->
    6)、activity.performCreate(icicle); -->
      // Activity :
    7)、performCreate(icicle, null);  -->
    8)、onCreate(icicle);
// ActivityThread.ApplicationThread :
27、if (a != null) {  
         handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);  -->
    } else {  
         ActivityManager.getService().finishActivity(r.token, Activity.RESULT_CANCELED, null,  
                            Activity.DONT_FINISH_TASK_WITH_ACTIVITY);  
    }  
28、r = performResumeActivity(token, clearHide, reason); -->
29、r.activity.performResume(); -->
// Activity :
30、performRestart(); -->
31、mInstrumentation.callActivityOnRestart(this); -->
    // Instrumentation :
    1> activity.onRestart();
32、performStart(); -->
33、mInstrumentation.callActivityOnStart(this); -->
    // Instrumentation :
    1> activity.onStart(); 
34、mInstrumentation.callActivityOnResume(this);
    // Instrumentation :
    1>activity.onResume();
  1. 源码分析:
    略过 startActivity(intent); --> this.startActivity(intent, null); -->startActivityForResult(intent, -1, options); --> startActivityForResult(intent, requestCode, null);
    (T_T) !!!!!
    直接进入Instrumentation的execStartActivity(...)方法
public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
            //......
     try {
            //......
           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);
      } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
      }
        return null;
}

调用的是 ActivityManager.getService().startActivity()

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

来看一下ActivityManager.getService()这个方法:

public static IActivityManager getService() {
  return IActivityManagerSingleton.get();
}
// IActivityManagerSingleton 初始化
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
  @Override
  protected IActivityManager create() {
    // 获取ActivityManagerService
    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
    final IActivityManager am = IActivityManager.Stub.asInterface(b);
    return am;
  }
};
/**
*  注:ActivityManager.getService()与之前的版本有所区别,拿到的是ActivityManagerService类。 (ActivityManagerService 继承了 IActivityManager.Stub)
*  旧版本的是ActivityManagerNative.getDefault() 它返回的是一个 ActivityManagerService的一个代理类ActivityManagerProxy类。
*/

可以看出ActivityManager.getService()拿到的是service是通过Singleton中的get()方法拿到ActivityManagerService;

继续进入ActivityManagerService的startActivity(...)方法:

 @Override
public int startActivity(IBinder whoThread, String callingPackage,Intent intent, String resolvedType, Bundle bOptions) {
  TaskRecord tr;
  IApplicationThread appThread;
  synchronized (ActivityManagerService.this) {
    // 初始化TaskRecord
    tr = mStackSupervisor.anyTaskForIdLocked(mTaskId);
    // 初始化IApplicationThread 
    appThread = IApplicationThread.Stub.asInterface(whoThread);
  }
  // 调用了mActivityStarter 实例是ActivityStarter
  return mActivityStarter.startActivityMayWait(appThread, -1, callingPackage, intent,resolvedType, null, null, null, null, 0, 0, null, null,null, bOptions, false, callingUser, tr, "AppTaskImpl");
}

继续进入ActivityStarter的startActivityMayWait(...)方法:

final int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, Intent intent, String resolvedType,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int startFlags,
            ProfilerInfo profilerInfo, WaitResult outResult,
            Configuration globalConfig, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
            TaskRecord inTask, String reason) {
      //...code...
      // Collect information about the target of the Intent.
      // 收集有关目标的Intent信息。
      ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
      //...code...
      final ActivityRecord[] outRecord = new ActivityRecord[1];
      int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,aInfo, rInfo, voiceSession, voiceInteractor,resultTo, resultWho, requestCode, callingPid,callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,options, ignoreTargetSecurity, componentSpecified, outRecord, inTask,reason);
    //...code...
}

继续进入ActivityStarter的startActivityLocked(...)方法:

int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,String callingPackage, int realCallingPid, int realCallingUid, int startFlags,ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,ActivityRecord[] outActivity, TaskRecord inTask, String reason) {
        //...code...
        mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                inTask);
        //...code...
    }

继续进入ActivityStarter的startActivity(...)方法:

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
            ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
            ActivityRecord[] outActivity, TaskRecord inTask) {
        //...code...
        doPendingActivityLaunchesLocked(false);
        return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,options, inTask, outActivity);
}

继续进入ActivityStarter的doPendingActivityLaunchesLocked(...)方法:

final void doPendingActivityLaunchesLocked(boolean doResume) {
  //...code...
  startActivity(pal.r, pal.sourceRecord, null, null, pal.startFlags, resume, null,null, null /*outRecords*/);
  //...code...
}

继续进入ActivityStarter的startActivity(...)方法:

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,ActivityRecord[] outActivity) {
  int result = START_CANCELED;
  //...code...
  result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,startFlags, doResume, options, inTask, outActivity);
  //...code...
  return result;
  }

继续进入ActivityStarter的startActivityUnchecked(...)方法:

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
//...code...
  if (mDoResume) {
    // mSupervisor 的实例是ActivityStackSupervisor
    mSupervisor.resumeFocusedStackTopActivityLocked(); // code number 1150
  }
//...code...
}

继续进入ActivityStackSupervisor的resumeFocusedStackTopActivityLocked(...)方法:

boolean resumeFocusedStackTopActivityLocked() {
        return resumeFocusedStackTopActivityLocked(null, null, null);
}

boolean resumeFocusedStackTopActivityLocked( ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
  //...code...
  // mFocusedStack 的实例是ActivityStack
  mFocusedStack.resumeTopActivityUncheckedLocked(null, null);  // code number 2098
  //...code...
}

继续进入ActivityStack的resumeTopActivityUncheckedLocked(...)方法:

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
  //...code...
  result = resumeTopActivityInnerLocked(prev, options); // code number 2249
  //...code...
}

继续进入ActivityStack的resumeTopActivityInnerLocked(...)方法:

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
  //...code...
  // mStackSupervisor 的实例是 ActivityStackSupervisor
  mStackSupervisor.startSpecificActivityLocked(next, true, false); // code number 2689
  //...code...
}

继续进入ActivityStackSupervisor的startSpecificActivityLocked(...)方法:

void startSpecificActivityLocked(ActivityRecord r,boolean andResume, boolean checkConfig) {
  //...code...
  realStartActivityLocked(r, app, andResume, checkConfig); // code number 1579
  //...code...
}

继续进入ActivityStackSupervisor的realStartActivityLocked(...)方法:

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,boolean andResume, boolean checkConfig) throws RemoteException {
  //...code...
  // code number 1457
  // app.thread 实例是ActivityThread.ApplicationThread
 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                        System.identityHashCode(r), r.info,
                        // TODO: Have this take the merged configuration instead of separate global
                        // and override configs.
                        mergedConfiguration.getGlobalConfiguration(),
                        mergedConfiguration.getOverrideConfiguration(), r.compat,
                        r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                        r.persistentState, results, newIntents, !andResume,
                        mService.isNextTransitionForward(), profilerInfo); 
  //...code...
}

继续进入ActivityThread.ApplicationThread的scheduleLaunchActivity(...)方法:

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,ActivityInfo info, Configuration curConfig, Configuration overrideConfig,CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,int procState, Bundle state, PersistableBundle persistentState,List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
            updateProcessState(procState, false);
            // 用于封装启动Activity需要的一些参数值。
            ActivityClientRecord r = new ActivityClientRecord();
            r.token = token;
            r.ident = ident;
            r.intent = intent;
            r.referrer = referrer;
            r.voiceInteractor = voiceInteractor;
            r.activityInfo = info;
            r.compatInfo = compatInfo;
            r.state = state;
            r.persistentState = persistentState;
            r.pendingResults = pendingResults;
            r.pendingIntents = pendingNewIntents;
            r.startsNotResumed = notResumed;
            r.isForward = isForward;
            r.profilerInfo = profilerInfo;
            r.overrideConfig = overrideConfig;
            updatePendingConfiguration(curConfig);
            sendMessage(H.LAUNCH_ACTIVITY, r);
}

继续进入ActivityThread的handleMessage(...)方法:

public void handleMessage(Message msg) {
            switch (msg.what) {
                case LAUNCH_ACTIVITY: {
                    //...code...
                    handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
                    //...code...
                }
                    //...code...
}

继续进入ActivityThread的handleLaunchActivity(...)方法:

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
    //...code...
    Activity a = performLaunchActivity(r, customIntent);
    //...code...
}

继续进入ActivityThread的performLaunchActivity(...)方法:

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
  //...code...
  ContextImpl appContext = createBaseContextForActivity(r);
  Activity activity = null;
  //...code...
  ClassLoader cl = appContext.getClassLoader();
  activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
  //...code...
  Application app = r.packageInfo.makeApplication(false, mInstrumentation);
  if (activity != null) {
     //...code...
    activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);
    //...code...
    if (r.isPersistable()) {
      mInstrumentation.callActivityOnCreate(activity, r.state,r.persistentState);
    } else {
      mInstrumentation.callActivityOnCreate(activity, r.state);
    }
    //...code...
  }
  //...code...
}

继续进入Instrumentation的callActivityOnCreate(...)方法:

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

继续进入Activity的performCreate(...)方法:

final void performCreate(Bundle icicle) {
        performCreate(icicle, null);
}
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        mCanEnterPictureInPicture = true;
        restoreHasCurrentPermissionRequest(icicle);
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
        mActivityTransitionState.readState(icicle);
        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
                com.android.internal.R.styleable.Window_windowNoDisplay, false);
        mFragments.dispatchActivityCreated();
        mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
    }

终于见到了我们可爱的onCreate();

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一个Android系统的手机,面对桌面一大堆的应用图标,我们随便点击一个应用图标,打开该应用,然后就进行了...
    黑衣_fy阅读 3,369评论 0 6
  • 1. 简介 本文源码基于android 27。startActivity的流程较复杂,我们这里将其过程分成三部分:...
    四月葡萄阅读 1,409评论 0 8
  • Zygote是什么?有什么作用? Android系统底层基于Linux Kernel, 当Kernel启动过程会创...
    Mr槑阅读 2,828评论 4 18
  • 半夜醒来,耳边是母亲酣酣的眠声。 我不知是有幸还是无力,近年来数次和母亲相伴而眠!常常恍惊而起,泪痕已然双颊。狭小...
    弦子之歌阅读 401评论 2 3
  • 很多人说雪茄必须陈年才好抽,如果要抽非陈年的雪茄,那就要在它制成后的1个月内品尝。显然,我们要抽到后者的情况很不现...
    雪茄小生阅读 1,345评论 1 1