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();

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,634评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,951评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,427评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,770评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,835评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,799评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,768评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,544评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,979评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,271评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,427评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,121评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,756评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,375评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,579评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,410评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,315评论 2 352

推荐阅读更多精彩内容

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