Activity启动流程【从Launcher点击图标】和【在Activity中调用startActivity()】

 
  
从Launch进程启动Application及Activity
Android系统是基于Linux的,所以它的所有应用也是基于Linux的Init进程创建出来的,
首先Init进程启动Zygote(受精卵)进程,然后再fork出其他进程(包括SystemServer),最后开启各种应用进程
Zygote孵化的第一个进程是system_server进程,而且孵化的第一个App进程是Launcher,也就是桌面App。
当点击桌面App的时候,发起进程就是Launcher所在的进程,启动远程进程,利用Binder发送消息给system_server进程;
在system_server进程中启动了N多服务,例如ActiivityManagerService,WindowManagerService等。
启动进程的操作会先调用AMS.startProcessLocked方法,内部调用 Process.start(android.app.ActivityThread);
而后通过socket通信告知Zygote进程fork子进程,即app进程。进程创建后将ActivityThread加载进去,
执行ActivityThread.main()方法,如下:

一、ActivityThread.main()
    1.初始化主线程
    Looper.prepareMainLooper();

    2.ActivityThread thread = new ActivityThread();
    thread.attach(false);

    3.判断当前主线程的Handler是否为空
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }

    4.Looper.loop();

    5.attach(false)
    IActivityManager mgr = ActivityManagerNative.getDefault();
    mgr.attachApplication(mAppThread);//mAppThread--ApplicationThread

二、ActivityManagerNative
    6.getDefault()---gDefault.get()
    IBinder b = ServiceManager.getService("activity");
    IActivityManager am = asInterface(b);
    return am;

    7.getService("activity");
    ServiceManager这里是getService,ActivityManagerService.setSystemProcess()中有个ServiceManager.addService();

    //ActivityManagerNative.ActivityManagerProxy
    8.asInterface(b)---new ActivityManagerProxy(obj);//"回到6"
    mRemote = remote;//IBinder

    9.mgr.attachApplication(mAppThread)在ActivityManagerNative中//将thread信息AMS//"回到5"
    mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0);//在system_server进程中,AMS会调用ActivityManagerNative.onTransact()//通过Binder进程间通信进入到ActivityManagerService中

三、ActivityManagerService
    10.attachApplication(mAppThread)在ActivityManagerService中//"回到5"
    attachApplicationLocked(thread, callingPid);//真正的逻辑部分

    11.attachApplicationLocked(thread, callingPid)//thread--IApplicationThread
    thread.bindApplication();
    mStackSupervisor.attachApplicationLocked(app)//app--ProcessRecord

四、ActivityThread
    12.bindApplication();
    sendMessage(H.BIND_APPLICATION, data);

    13.handleBindApplication(data);
    final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
    final ClassLoader cl = instrContext.getClassLoader();
    Instrumentation mInstrumentation = (Instrumentation) cl.loadClass(data.instrumentationName.getClassName()).newInstance();
    Application app = data.info.makeApplication(data.restrictedBackupMode, null);
    mInstrumentation.callApplicationOnCreate(app);//---app.onCreate();

五、LoadedApk
    14.makeApplication(data.restrictedBackupMode, null);
    String appClass = mApplicationInfo.className;
    if (forceDefaultAppClass || (appClass == null))   appClass = "android.app.Application";
    ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
    Application app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);//cl--getClassLoader()

六、Instrumentation---管家的角色
    15.newApplication(cl, appClass, appContext);
        newApplication(cl.loadClass(className), context)
            Application app = (Application)clazz.newInstance();//反射创建,调用简单粗暴,native方法
            app.attach(context);//Application被创建后第一个调用的方法,目的是为了绑定Context

七、ActivityStackSupervisor
    16.attachApplicationLocked(app)//"回到11"(***************************)
    realStartActivityLocked(hr, app, true, true)
            app.thread.scheduleLaunchActivity();

八、ActivityThread
    17.scheduleLaunchActivity();//--ApplicationThread
    sendMessage(H.LAUNCH_ACTIVITY, r);//发送创建Activity的消息

    18.handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");//处理消息
    Activity a = performLaunchActivity(r, customIntent);//创建并调用onCreate(),onStart()
    handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);//调用onResume

    19.performLaunchActivity(r, customIntent);//创建并调用onCreate(),onStart()
    java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
    Activity activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);//创建Activity
    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);
    if (r.isPersistable()) {//根据是否可持久化选择callActivityOnCreate()方法。
        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);//可获得持久化数据;
    } else {
        mInstrumentation.callActivityOnCreate(activity, r.state);
    }
    if (!r.activity.mFinished) {
        activity.performStart();//调用onStart
        r.stopped = false;
    }
    if (!r.activity.mFinished) {
        if (r.isPersistable()) {//根据是否可持久化选择callActivityOnRestoreInstanceState()方法。
            if (r.state != null || r.persistentState != null) {
                mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state, r.persistentState);//可获得持久化数据;
            }
        } else if (r.state != null) {
            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
        }
    }
    if (!r.activity.mFinished) {
        activity.mCalled = false;
        if (r.isPersistable()) {//根据是否可持久化选择callActivityOnCreate()方法。
            mInstrumentation.callActivityOnPostCreate(activity, r.state, r.persistentState);//可获得持久化数据;
        } else {
            mInstrumentation.callActivityOnPostCreate(activity, r.state);
        }
        ...
    }

九、Instrumentation
    20.newActivity(cl, component.getClassName(), r.intent);//创建Activity
    (Activity)cl.loadClass(className).newInstance();//反射创建,调用native方法

    21.callActivityOnCreate();
    activity.performCreate(icicle);/activity.performCreate(icicle, persistentState);
        onCreate(icicle)//平时重写的最多的;/onCreate(icicle, persistentState)//可获得持久化数据;

    22.callActivityOnRestoreInstanceState();
    activity.performRestoreInstanceState(savedInstanceState);/activity.performRestoreInstanceState(savedInstanceState, persistentState);

    23.callActivityOnPostCreate();
    activity.onPostCreate(icicle);/activity.onPostCreate(icicle, persistentState);

十、Activity
    24.performRestoreInstanceState();
        onRestoreInstanceState(savedInstanceState);/onRestoreInstanceState(savedInstanceState, persistentState);

    25.onPostCreate();
    onPostCreate(savedInstanceState);
        if (!isChild()) {
            mTitleReady = true;
            onTitleChanged(getTitle(), getTitleColor());
        }
        mCalled = true;

    26.performStart();//调用onStart
    mInstrumentation.callActivityOnStart(this);---activity.onStart();

十一、ActivityThread
    27.handleResumeActivity();“回到18”
    r = performResumeActivity(token, clearHide, reason);
        r.activity.performResume();

十二、Activity
    28.performResume();//调用onResume
    mInstrumentation.callActivityOnResume(this);---activity.onResume();

在Activity中调用startActivity();
一、Activity
    1.startActivity()
    Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options);

二、Instrumentation
    2.execStartActivity();
    int result = ActivityManagerNative.getDefault().startActivity(whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
        ActivityManagerProxy.startActivity();
            BinderProxy.transact(); //Binder驱动将处理逻辑从Activity所在进程切换到ActivityManagerService所在进程

三、ActivityManagerService
    3.startActivity();
    startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, options, UserHandle.getCallingUserId());
        mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, null, null, options, false, userId, null, null);

四、ActivityStackSupervisor
    4.startActivityMayWait();
    int res = startActivityLocked(caller, intent, resolvedType, aInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity, componentSpecified, null, container, inTask);
        int err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true, options, inTask);
            targetStack.resumeTopActivityLocked(null, options);//启动新的Activity之前,栈顶的Activity需要先onPause
            targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);//启动Activity

五、ActivityStack
    5.resumeTopActivityLocked();
    result = resumeTopActivityInnerLocked(prev, options);

    6.resumeTopActivityInnerLocked();
    // We need to start pausing the current activity so the top one can be resumed...
    // 我们需要暂停当前的活动,这样可以恢复最新的活动。
    boolean dontWaitForPause = (next.info.flags& ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
    boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);//暂停所有的Activity
    if (mResumedActivity != null) {
        ...
        pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);//暂停当前的Activity
    }

    5.startActivityLocked();//启动Activity
    task.addActivityToTop(r);//将Activity添加至栈顶
    task.setFrontOfTask();//设置Activity为栈内前天
    ensureActivitiesVisibleLocked(null, 0);//确保Activity用户可见,启动Activity

    6.ensureActivitiesVisibleLocked(null, 0);//启动Activity
    mStackSupervisor.startSpecificActivityLocked(r, noStackActivityResumed, false);

六、ActivityStackSupervisor
    7.startSpecificActivityLocked();
    realStartActivityLocked(r, app, andResume, checkConfig);
        app.thread.scheduleLaunchActivity();//接下来同“从Launch进程启动Application及Activity---七-16 加***处”

开头部分可参考:https://www.jianshu.com/p/b59db6250c61


智商有限,理解有误,还请指点!



你可能感兴趣的:(Android)