Activity启动流程

2018-01-12  本文已影响0人  刘佳阔

1. activity的启动过程有一下几种

  在应用程序中调用startActivity启动.
  在home程序点击应用图标启动
  按Back键结束当前activity,自动启动上一个activity
  显示任务列表,选择一个启动.

这几种方式的主题流程都是按第一种启动方式运行,先看第一种.

2.先介绍几个数据类.

PropressRecord 进程数据类,每个apk文件运行时都对应一个进程
ActivityRecord  Activity数据类.抽象了所有Activity的共性,用来保存activity的信息,
TaskRecord 任务数据类,用来保存activity的启动顺序.对应activity的launchmode和launchflag功能
activityStack activity的任务栈,ActivityStack管理了一系列的TaskRecord,通过mStackId来唯一标识
ActivityThread 既ui线程,每启动一个应用进程,都会创建ActivityThread与之对应的实例,Android进程启动时会建立消息循环,
负责管理应用程序的生命周期.
ApplicationThread 用来实现ActivityManagerService与ActivityThread之间的交互.ApplicationThread接受到Ams的消息后,
通过发送msg来告知ActivityThread
图片来自网络

3.大概流程

图片出自安卓内核剖析

4.单击启动activity过程

1.首先会调用到该activity内部的startActivity(),不需要回调时传入-1

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

2.接着看activity的startAtivityForResult --通过Instrumentation来启动.

//activity
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
    if (mParent == null) {  //第一次启动时 Activity  mParent 肯定不存在,所以走这里.
        Instrumentation.ActivityResult ar = //Instrumentation mInstrumentation该对象一个应用程序只有一个,在AcitivityThread创建
//Activity时创建的.可以理解为进程的管家,可以用来统计创建activity时的开销.Activity在应用进程端的启动实际上就是Instrumentation执行的.实际
//上acitivty的启动分为应用进程端的启动和SystemServer服务进程端的启动的,多个应用进程相互配合最终完成了Activity在系统中的启动
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        if (ar != null) {
            mMainThread.sendActivityResult(
                mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                ar.getResultData());
        }
    } else {
        ...
    }
}

3.接着看 Instrumentation.execStartActivity --通过Ams来启动activity

Instrumentation
 public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    //1.此处的 IApplicationThread ,就是Ams用来通知ActivityThread的ApplicathonThread.源码在ActivityThread的内部类ApplicationThread中.
    IApplicationThread A= (IApplicationThread) contextThread;   
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess();
//2.这个ActivityManagerNative.getDeafult获得的是IActivityManager类的对象.其实就是远程服务端的
//ActivityManagerService的本地代理.此时.就是夸进程调用Ams的startActivity来启动Activity.这个方法会阻塞在这里等待Ams的startActivity返回.
//而Ams.startActivity是异步处理的,他会立刻返回结果,然后使用异步调用通过IApplicationThread A通知ActivityThread. 而下问的token参数.对应Activity里的IBinder,在Ams端对应一个AcitivityRecord,Ams通过这个AcitivityRecord来找到相对应的Activity.
            int result = ActivityManagerNative.getDefault() .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) {
    }
    return null;
}

4.接着看Ams中的startActivity --通过ActivityStackSupervisor 来启动activity.这个类可以管理activity栈记录

//Ams
@Override //这段没意义
public final int startActivity(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle options) {
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
        resultWho, requestCode, startFlags, profilerInfo, options,
        UserHandle.getCallingUserId());
}

@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {

    return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
            resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
            profilerInfo, null, null, options, userId, null, null);
}

//ActivityStackSupervisor 是ActivityStack的管理类,是Android系统Activity的栈管理器,管理着两个重要的Activity栈,在Ams的构造函数中创建.
//两个栈是mHomeStack和mFocusedStack,AMS使用这两个栈完成系统全部的Activity的管理和调度。其中mHomeStack管理的是Launcher相关的任务,
 //包括Launcher、RecentTask,Keyguad,除了上述以外的任务都归mFocusedStack管理。
//ActivityStackSupervisor 
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 config,
        Bundle options, int userId, IActivityContainer iContainer, TaskRecord inTask) {
   
    // 删减后的代码大概如下,先从PackageManager中查询intente匹配的component信息,
    intent = new Intent(intent);
                    try {
                        ResolveInfo rInfo =
                            AppGlobals.getPackageManager().resolveIntent(
                                    intent, null,
                                    PackageManager.MATCH_DEFAULT_ONLY
                                    | ActivityManagerService.STOCK_PM_FLAGS, userId);
                        aInfo = rInfo != null ? rInfo.activityInfo : null;
                        aInfo = mService.getActivityInfoForUser(aInfo, userId);
                    } catch (RemoteException e) {
                        aInfo = null;
                    }
            }
        }
        //接着调用startActivityLocked 方法名意味着必须是线程安全的.
        int res = startActivityLocked(caller, intent, resolvedType, aInfo,
                voiceSession, voiceInteractor, resultTo, resultWho,
                requestCode, callingPid, callingUid, callingPackage,
                realCallingPid, realCallingUid, startFlags, options,
                componentSpecified, null, container, inTask);
        return res;
    }
}

5.接着看ActivityStackSupervisor 的startActivityLocked方法,该方法用来进行环境检查--

//ActivityStackSupervisor
final int startActivityLocked(IApplicationThread caller,
        Intent intent, String resolvedType, ActivityInfo aInfo,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        IBinder resultTo, String resultWho, int requestCode,
        int callingPid, int callingUid, String callingPackage,
        int realCallingPid, int realCallingUid, int startFlags, Bundle options,
        boolean componentSpecified, ActivityRecord[] outActivity, ActivityContainer container,
        TaskRecord inTask) {
    int err = ActivityManager.START_SUCCESS;

    ProcessRecord callerApp = null; //1.找到activity对应的processRecord 对象,既应用进程对象.
    if (caller != null) {
        callerApp = mService.getRecordForAppLocked(caller);
        if (callerApp != null) {
            callingPid = callerApp.pid; //2.PID是进程的身份标识,程序一旦运行,就会给应用分配一个独一无二的PID
            callingUid = callerApp.info.uid; //3.为了实现数据共享,android为每个应用几乎都分配了不同的UID,主要用于权限的管理
        } else {
            err = ActivityManager.START_PERMISSION_DENIED;
        }
    }

//4.sourceRecord 代表请求启动当前activity的activity;resultRecord 表示当前的activity在启动之后需要返回结果的ActivityRecord,
//如果sourceRecord的activity使用startActivityForResult()启动当前activity并且requestCode>=0时,则resultRecord不为空
//且resultRecord=sourceRecord。
    ActivityRecord sourceRecord = null;
    ActivityRecord resultRecord = null;
    if (resultTo != null) {
        sourceRecord = isInAnyStackLocked(resultTo);
        if (sourceRecord != null) {
            if (requestCode >= 0 && !sourceRecord.finishing) {
                resultRecord = sourceRecord;
            }
        }
    }
    ActivityStack resultStack = resultRecord == null ? null : resultRecord.task.stack;

    final int launchFlags = intent.getFlags();
 //5.这里是处理FLAG_ACTIVITY_FORWARD_RESULT Activity. 如: A 启动了Activity B,Activity B又启动了C,A-->B-->C, 这种情况下,
//A启动B要求B返回result给A,但是如果B在启动C时,Intent设置了Intent.FLAG_ACTIVITY_FORWARD_RESULT标志,C setResult 会把结果返回给A.
//为了避免冲突,B启动C时不得指定resultRecord>=0。
    if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {
        // Transfer the result target from the source activity to the new
        // one being started, including any failures.
        if (requestCode >= 0) {
            ActivityOptions.abort(options);
            return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
        }
        resultRecord = sourceRecord.resultTo;
        resultWho = sourceRecord.resultWho;
        requestCode = sourceRecord.requestCode;
        sourceRecord.resultTo = null;
        if (resultRecord != null) {
            resultRecord.removeResultsLocked(sourceRecord, resultWho, requestCode);
        }
        if (sourceRecord.launchedFromUid == callingUid) {
            callingPackage = sourceRecord.launchedFromPackage;
        }
    }

    if (err != ActivityManager.START_SUCCESS) { //6.缺乏某些东西,标识启动失败.
        if (resultRecord != null) {
            resultStack.sendActivityResultLocked(-1,
                resultRecord, resultWho, requestCode,
                Activity.RESULT_CANCELED, null);
        }
        ActivityOptions.abort(options);
        return err;
    }

    final int startAnyPerm = mService.checkPermission(//7.检查是否具有启动Activity的权限.
            START_ANY_ACTIVITY, callingPid, callingUid);
    final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
            callingUid, aInfo.applicationInfo.uid, aInfo.exported);
    if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
        if (resultRecord != null) {
            resultStack.sendActivityResultLocked(-1,
                resultRecord, resultWho, requestCode,
                Activity.RESULT_CANCELED, null);
        }
    }

    boolean abort = !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
            callingPid, resolvedType, aInfo.applicationInfo);//8.intnet是否有权限启动activity

    if (abort) {
        if (resultRecord != null) {
            resultStack.sendActivityResultLocked(-1, resultRecord, resultWho, requestCode,
                    Activity.RESULT_CANCELED, null);
        }
        ActivityOptions.abort(options);
        return ActivityManager.START_SUCCESS;
    }
//9.创建一个临时的ActivityRecord 只是为了后面调用过程的对比
    ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
            intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,
            requestCode, componentSpecified, this, container, options);
    if (outActivity != null) {
        outActivity[0] = r;
    }

    final ActivityStack stack = getFocusedStack();
    if (voiceSession == null && (stack.mResumedActivity == null
            || stack.mResumedActivity.info.applicationInfo.uid != callingUid)) {
  //10.检查当前是否允许activity切换,常发生在当前activity已经暂停,正等待下一个activity启动.就把指定的activity保存在
//ArrayList<PendingActivityLaunch> mPendingActivityLaunches 中,等系统恢复后执行
        if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid,
                realCallingPid, realCallingUid, "Activity start")) {
            PendingActivityLaunch pal =
                    new PendingActivityLaunch(r, sourceRecord, startFlags, stack);
            mPendingActivityLaunches.add(pal);
            ActivityOptions.abort(options);
            return ActivityManager.START_SWITCHES_CANCELED;
        }
    }

    if (mService.mDidAppSwitch) {

        mService.mAppSwitchesAllowedTime = 0;
    } else {
        mService.mDidAppSwitch = true;
    }

    doPendingActivityLaunchesLocked(false);//11.启动等待序列中的activity
     //12.到这里,表示要启动的activity已经通过的检查,接下来Ams会判断以何种方式启动指定的activity
    err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
            startFlags, true, options, inTask);

    if (err < 0) {
     
        notifyActivityDrawnForKeyguard();
    }
    return err;
}
  1. ActivityStackSupervisor.startActivityUncheckedLocked 方法用来找到或创建合适的task,并指定activity的启动方式
 //ActivityStackSupervisor
 final int startActivityUncheckedLocked(ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags,
        boolean doResume, Bundle options, TaskRecord inTask) {
    final Intent intent = r.intent;
    final int callingUid = r.launchedFromUid;

    final boolean launchSingleTop = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP;
    final boolean launchSingleInstance = r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE;
    final boolean launchSingleTask = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK;
 //1.为保证activity能按照指定的方式退出,在启动activity之前,ams要确定是否需要创建新的task,根据launchMode 和launchFlags 来觉得,
// launchMode是在manifest中配置的声明自己的启动方式,launchFlags是指以何种方式运行指定的activity,是在startActivity中intent添加的.
    int launchFlags = intent.getFlags();

 //2.FLAG_ACTIVITY_NEW_TASK 标识不能用在startActivityForResult中,系统认为不同task不能传递数据
    if (r.resultTo != null && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
        r.resultTo.task.stack.sendActivityResultLocked(-1,
                r.resultTo, r.resultWho, r.requestCode,
                Activity.RESULT_CANCELED, null);
        r.resultTo = null;
    }




    //3.处理FLAG_ACTIVITY_NO_USER_ACTION标识,一般不包含该标识,ams会判断如果一段时间内如果没有用户交互,就会回调onUserLeaving方法
    //  如果有该标识就不会回调
    mUserLeaving = (launchFlags & Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;

    // 4.确定是否现在启动activity,就设置为true,表示不延迟启动而是立即启动
    if (!doResume) {
        r.delayedResume = true;
    }

    boolean addingToTask = false;
    TaskRecord reuseTask = null;


  //5.设置根据原来的activity设置目标activity的launchflags
    if (inTask == null) {
        if (sourceRecord == null) {
            if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0 && inTask == null) {
                launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
            }
        } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
            launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
        } else if (launchSingleInstance || launchSingleTask) {
            launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
        }
    }

    intent.setFlags(launchFlags);
     //6.这里是根据原activity的launchmode和新activity的launchflags来觉得新activity的task问题
    if (((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
            (launchFlags & Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
            || launchSingleInstance || launchSingleTask) {

                if ((launchFlags &
                                (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME))
                                == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME))  
                }
               

                if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {

                    if (doResume) {
                        resumeTopActivitiesLocked(targetStack, null, options);
                    } 
                    return ActivityManager.START_RETURN_INTENT_TO_CALLER;
                }
                if ((launchFlags &
                        (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
                        == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
                     
                } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
                        || launchSingleInstance || launchSingleTask) {
               
                    }  
                }  
   
                    if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0 || launchSingleTop)
                            && intentActivity.realActivity.equals(r.realActivity)) {
                    }  
                } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
            
                }  
                if (!addingToTask && reuseTask == null) { 
                    if (doResume) {
                        targetStack.resumeTopActivityLocked(null, options); //7.这里启动真正的activity ActivityStack  targetStack 
                    }  
                    return ActivityManager.START_TASK_TO_FRONT;
                }
    }
    targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);

    return ActivityManager.START_SUCCESS;
}

7.接着看 ActivityStack targetStack的resumeTopActivityLocked方法,运行mHitory中最后一个ActivityRecord

//ActivityStack 
final boolean resumeTopActivityLocked(ActivityRecord prev) {
    return resumeTopActivityLocked(prev, null);
}

final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
        result = resumeTopActivityInnerLocked(prev, options);
    return result;
}

final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
    if (!mService.mBooting && !mService.mBooted) { //1.ams没初始化完成
        // Not ready yet!
        return false;
    }

    cancelInitializingActivities(); //2.把top activity下的正在初始化的activity 给停止掉.

    //3.得到正在运行的activityrecord,这个record对应的就是一会要启动的目标activity
    ActivityRecord next = topRunningActivityLocked(null);

    final TaskRecord prevTask = prev != null ? prev.task : null;
    if (next == null) {//4.表示没有运行过任何activity,那么先启动主界面程序既home程序
        final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
                HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
        return isOnHomeDisplay() &&
                mStackSupervisor.resumeHomeStackTask(returnTaskType, prev);
    }



    // 5.正在运行的activity和目标activity一样,就什么也不做
    if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
                mStackSupervisor.allResumedActivitiesComplete()) {
        mWindowManager.executeAppTransition();
        mNoAnimActivities.clear();
        mStackSupervisor.notifyActivityDrawnForKeyguard();
        return false;
    }

    // If we are sleeping, and there is no resumed activity, and the top
    // activity is paused, well that is the state we want.
    //6.如果系统在休眠,正在运行的activity是pause状态.就什么也不做
    if (mService.isSleepingOrShuttingDown()
            && mLastPausedActivity == next
            && mStackSupervisor.allPausedActivitiesComplete()) {
        mWindowManager.executeAppTransition();
        mNoAnimActivities.clear();
        return false;
    }

    // 7.从mStoppingActivities和mWaitingVisibleActivities 中删除,因为该activityrecord对应的activity将要被启动
    mStackSupervisor.mStoppingActivities.remove(next);
    mStackSupervisor.mGoingToSleepActivities.remove(next);
    next.sleeping = false;
    mStackSupervisor.mWaitingVisibleActivities.remove(next);


    // If we are currently pausing an activity, then don't do anything
    // until that is done.8. 如果正在暂停一个activity,那么什么也不能做
    if (!mStackSupervisor.allPausedActivitiesComplete()) {
        return false;
    }

    boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
    boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
    if (mResumedActivity != null) { 
//9.接下来就是暂停之前的activity,android仅允许同时执行一个activity,此处代码以后在看,这里的逻辑会使ams异步执行
//,然后ams在执行完后会通过ApplicationThread通知给activityThread
        pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
    }
    if (pausing) {
        //把即将启动的activity的process信息加到ams中
        if (next.app != null && next.app.thread != null) {
            mService.updateLruProcessLocked(next.app, true, null);
        }
        return true;
    }

    //10.ams休眠后.结束掉执行了onstop的activity
    if (mService.isSleeping() && mLastNoHistoryActivity != null &&
            !mLastNoHistoryActivity.finishing) {
        requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED,
                null, "no-history", false);
        mLastNoHistoryActivity = null;
    }

    if (prev != null && prev != next) { //11.把上一个activityrecord 变成等待显示状态,因为next要变成显示状态
        if (!prev.waitingVisible && next != null && !next.nowVisible) {
            prev.waitingVisible = true;
            mStackSupervisor.mWaitingVisibleActivities.add(prev);
        } else {
            if (prev.finishing) {//隐藏上一个activity
                mWindowManager.setAppVisibility(prev.appToken, false);

        }
    }


    try {//12.利用packagemanager来加载新的activity
        AppGlobals.getPackageManager().setPackageStoppedState(
                next.packageName, false, next.userId); /* TODO: Verify if correct userid */
    }  


    boolean anim = true;
    if (prev != null) { //13.新activity已经启动. 隐藏旧activity 同时加一个activity切换动画
                mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
           
            mWindowManager.setAppWillBeHidden(prev.appToken);
            mWindowManager.setAppVisibility(prev.appToken, false);
        }
    }    


    ActivityStack lastStack = mStackSupervisor.getLastStack();
    if (next.app != null && next.app.thread != null) { 
      //14.要判断新activity对应的线程是否存在.及ApplicationThread不为空,标识该activity已经出于运行状态,并且activity对像已经存在,
      //就resume该activity,否则如果进程不存在就创建新进程,如果activity不存在就创建activity.
    //通知activityThread 显示最新的activity
            next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState,
                    mService.isNextTransitionForward(), resumeAnimOptions);
        }  
    } else {//15.新activity无法正常resume,通过这个方法判断新activity对应的进程是否存在,新activity是否加载.
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
    }
    return true;
}

8.接下来看ActivityStackSupervisor.startSpecificActivityLocked 方法,该方法内部会判断新activity对应的进程是否存在,新activity是否加载.然后分别加载进程及activity.

 //ActivityStackSupervisor
void startSpecificActivityLocked(ActivityRecord r,
        boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
            r.info.applicationInfo.uid, true);//1.新activity对应的进程ProcessRecord 对象.

    r.task.stack.setLaunchTime(r);

    if (app != null && app.thread != null) {//2.标识进程存在,可以直接启动activity.
        try {
            if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                    || !"android".equals(r.info.packageName)) {
                app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
                        mService.mProcessStats);
            }
            realStartActivityLocked(r, app, andResume, checkConfig);
            return;
        } catch (RemoteException e) {

    }
  //3.到这里说明activity对应的进程不存在.则要先加载进程.
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
            "activity", r.intent.getComponent(), false, false, true);
}

9.因为对应的进程不存在.我们先看8.3的代码执行.ActivityManagerService.startProcessLocked,大致过程是Ams调用Process类启动一个新的应用进程,新的进程会从ActivityThread的main函数开始执行,当进程启动后,会报告ams自己已经启动,然后Ams在通知目标进程启动目标activity.

//ActivityManagerService
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
        boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
        boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
        String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
    long startTime = SystemClock.elapsedRealtime();
    ProcessRecord app; //1.获取目标进程的processrecord对象,
    if (!isolated) {
        app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
        checkTime(startTime, "startProcess: after getProcessRecord");
    } else {
        app = null;
    }

     //2.由三个条件判断目标进程存在,1.目标进程对应的ProcessRecord不为空,2.如果ProcessRecord.pid>0,说明目标进程存在,但可能在初始化,
     //3.ProcessRecord.thread不为空,这是一个ActivityThread对象,说明目标进程存在且初始化完毕
    if (app != null && app.pid > 0) {
        if (!knownToBeDead || app.thread == null) { //3.目标进程存在且初始化中,什么也不做
            app.addPackage(info.packageName, info.versionCode, mProcessStats);
            checkTime(startTime, "startProcess: done, added package to proc");
            return app;
        }
    }

    String hostingNameStr = hostingName != null
            ? hostingName.flattenToShortString() : null;

    if (!isolated) {
//4.处理FLAG_FROM_BACKGROUND 标识,以背景方式启动的进程,会加这个标识,进程死亡后不会再尝试启动.不加这个标识可以尝试重新启动
        if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
            if (mBadProcesses.get(info.processName, info.uid) != null) {                
                return null;
            }
        } else { 
            mProcessCrashTimes.remove(info.processName, info.uid);
            if (mBadProcesses.get(info.processName, info.uid) != null) {
                EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
                        UserHandle.getUserId(info.uid), info.uid,
                        info.processName);
                mBadProcesses.remove(info.processName, info.uid);
                if (app != null) {
                    app.bad = false;
                }
            }
        }
    }

    if (app == null) {
//5.如果ProcessRecord为空,就新建一个,并添加到mProcessNames中,同时给app.info赋值ApplicationInfo,
        app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
        app.crashHandler = crashHandler;
        if (app == null) {     
            return null;
        }
        mProcessNames.put(processName, app.uid, app);
        if (isolated) {
            mIsolatedProcesses.put(app.uid, app);
        }      
    } else {        
        app.addPackage(info.packageName, info.versionCode, mProcessStats);
        
    }

 //6.如果ams还没准备好,把目标progressRecord加入到准备序列中
    if (!mProcessesReady
            && !isAllowedWhileBooting(info)
            && !allowWhileBooting) {
        if (!mProcessesOnHold.contains(app)) {
            mProcessesOnHold.add(app);
        }
        return app;
    }

   //7.正式启动进程
    startProcessLocked(
            app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);

    return (app.pid != 0) ? app : null;
}

10.接下来正式启动目标进程.其实是通过ams来启动进程

//ActivityManagerService
private final void startProcessLocked(ProcessRecord app, String hostingType,
        String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {

    if (app.pid > 0 && app.pid != MY_PID) {
        checkTime(startTime, "startProcess: removing from pids map");
        synchronized (mPidsSelfLocked) {
//1.这个表保存了所有正在运行的进程的pid到ProcessRecord的映射.其实通过pid和mProcessName都可以找到ProcessRecord,
//因为每个进程对应的ProcessRecord唯一.所以这两个值都必须唯一.而mProcessName通常是包名.
            mPidsSelfLocked.remove(app.pid);

            mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
        }
        app.setPid(0);
    }

    //2.从进程准备列中删除掉
    mProcessesOnHold.remove(app);
    try {
 //3.启动目标线程,这是一个native方法,内部会总zygote中fork出一个新进程,并且进程会从ActivityThread的main方法中开始执行,
        Process.ProcessStartResult startResult = Process.start(entryPoint,
                app.processName, uid, uid, gids, debugFlags, mountExternal,
                app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
                app.info.dataDir, entryPointArgs);

        synchronized (mPidsSelfLocked) {
//4.把pid添加到mPidsSelfLocked中,在后边的attachApplication中还要根据pid 获得app对象.
            this.mPidsSelfLocked.put(startResult.pid, app); 
            }
        } 
    } catch (RuntimeException e) {
    }
}

11.至此,启动进程结束,Ams会等待目标进程报告启动完毕,目标进程会调用ams的attachtApplication方法请求ams给目标进程指定activity去运行.接着看Ams.attachtApplication

//ActivityManagerService
 @Override
public final void attachApplication(IApplicationThread thread) {
    synchronized (this) {
        int callingPid = Binder.getCallingPid();//1.获取目标进程的pid
        final long origId = Binder.clearCallingIdentity();
        attachApplicationLocked(thread, callingPid);
        Binder.restoreCallingIdentity(origId);
    }
}
private final boolean attachApplicationLocked(IApplicationThread thread,
        int pid) {
    ProcessRecord app; //2.根据pid先找到processRecord对象,如果找不到.说明是一个未经Ams允许的野进程.
    if (pid != MY_PID && pid >= 0) {
        synchronized (mPidsSelfLocked) {
            app = mPidsSelfLocked.get(pid);
        }
    } else {
        app = null;
    }

    if (app == null) { //2.野进程.杀死并退出.
        if (pid > 0 && pid != MY_PID) {
            Process.killProcessQuiet(pid);
            //TODO: Process.killProcessGroup(app.info.uid, pid);
        } else {
            try {
                thread.scheduleExit();
            }  
        }
        return false;
    }
    //3.配置目标进程信息
    app.makeActive(thread, mProcessStats);
    app.curAdj = app.setAdj = -100;
    app.curSchedGroup = app.setSchedGroup = Process.THREAD_GROUP_DEFAULT;
    app.forcingToForeground = null;
    updateProcessForegroundLocked(app, false, false);
    app.hasShownUi = false;
    app.debugging = false;
    app.cached = false;
    try {
 //4.确保目标程序(apk)文件已经被转换为odex文件了.dex是从zip文件中提取出来的.为了提高运行效率.
        ensurePackageDexOpt(app.instrumentationInfo != null
                ? app.instrumentationInfo.packageName
                : app.info.packageName);
        if (app.instrumentationClass != null) {
            ensurePackageDexOpt(app.instrumentationClass.getPackageName());
        }

         //5.通知客户进程运行指定的activity所在的apk文件.顺便调用updateLruProcessLocked更新 最近调用的进程列表
        thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
                profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
                app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
                isRestrictedBackupMode || !normalMode, app.persistent,
                new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
                mCoreSettingsObserver.getCoreSettingsLocked());
        updateLruProcessLocked(app, false, null);
        app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
    } catch (Exception e) {
         
        return false;
    }


    if (normalMode) {
        try {
//6.内部会调用 mStackSupervisor.realStartActivityLocked,然后调用app.thread.scheduleLaunchActivity来通知客户进程运行指定的activity,5步是告诉目标进程加载application类运行,这一步才是真正启动activity.
            if (mStackSupervisor.attachApplicationLocked(app)) {
                didSomething = true;
            }
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
            badApp = true;
        }
    }

    // 7.如果有的话,启动目标进程等待的service
    if (!badApp) {
        try {
            didSomething |= mServices.attachApplicationLocked(app, processName);
        }  
    }

    //   8.如果有的话,启动目标进程等待的broadcast
    if (!badApp && isPendingBroadcastProcessLocked(pid)) {
        try {
            didSomething |= sendPendingBroadcastsLocked(app);
        }  
    }

    

    return true;
}

12.接着看11.5 thread.bindApplication 本质是Ams通过Ipc想客户端进程发消息.通过Application thread.发送msg通知ActivityThread 启动目标activity所在的apk.加载Application运行.

  //ActivityThread 
  public final void bindApplication(String processName, ApplicationInfo appInfo,
            List<ProviderInfo> providers, ComponentName instrumentationName,
            ProfilerInfo profilerInfo, Bundle instrumentationArgs,
            IInstrumentationWatcher instrumentationWatcher,
            IUiAutomationConnection instrumentationUiConnection, int debugMode,
            boolean enableOpenGlTrace, boolean isRestrictedBackupMode, boolean persistent,
            Configuration config, CompatibilityInfo compatInfo, Map<String, IBinder> services,
            Bundle coreSettings) {
         //1.ActivitThread内部有个Handler类 H , 通过H mh,ApplicationThread 把消息传递给 ActivityThread.所以接下来看ActivityThread的内部处理方法 handleBindApplication
        AppBindData data = new AppBindData();
        data.processName = processName;
        sendMessage(H.BIND_APPLICATION, data);
    }
  1. Activitythread.handleBindApplication
//Activitythread
private void handleBindApplication(AppBindData data) {
    mBoundApplication = data;

    TimeZone.setDefault(null);//1.设置时区,和区域,不用的时区和区域对应不同资源,新建进程时需要此步骤
    Locale.setDefault(data.config.locale);

    //2.如果是debug模式.就弹出一个等待框,说明debug模式的对话框是系统的一部分
    if (data.debugMode != IApplicationThread.DEBUG_OFF) {
            Debug.changeDebugPort(8100);
            IActivityManager mgr = ActivityManagerNative.getDefault();
            try {
                mgr.showWaitingForDebugger(mAppThread, true);
            }  
            Debug.waitForDebugger();
            try {
                mgr.showWaitingForDebugger(mAppThread, false);
            }  
    }

    
    try {
    //3.创建application对象.也是通过反射方式生成,一个apk只有一个application对象,让后把它添加到Activitythread的mAllApplications中去,然后在读取Asserts资源.
        Application app = data.info.makeApplication(data.restrictedBackupMode, null);
        mInitialApplication = app;

         
        if (!data.restrictedBackupMode) {
            List<ProviderInfo> providers = data.providers;
            if (providers != null) {
    //4.如果应用中有provider对象,启动他们,说明,provider先于activity被启动.
                installContentProviders(app, providers);
            }
        }

    
        // 5.然后调用application的oncreate方法
        try {
            mInstrumentation.callApplicationOnCreate(app);
        } catch (Exception e) {
            
            }
        }
    } 
}

13.接着看11.6 mStackSupervisor.attachApplicationLocked 如何启动指定的activity.

//AcitivityStactSupervisor
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
    final String processName = app.processName;
    boolean didSomething = false;//1.找到最上边的可见的stack栈.
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
        for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
            final ActivityStack stack = stacks.get(stackNdx);
            if (!isFrontStack(stack)) {
                continue;
            }
            ActivityRecord hr = stack.topRunningActivityLocked(null); //2.找到最上边的activityRecord
            if (hr != null) {
                if (hr.app == null && app.uid == hr.info.applicationInfo.uid
                        && processName.equals(hr.processName)) {
                    try {
                        if (realStartActivityLocked(hr, app, true, true)) {//3.通过这个方法启动activity
                            didSomething = true;
                        }
                    }  
                }
            }
        }
    }

 //AcitivityStactSupervisor
 final boolean realStartActivityLocked(ActivityRecord r,
        ProcessRecord app, boolean andResume, boolean checkConfig)
        throws RemoteException {


     // 1.显示该activity
    mWindowManager.setAppVisibility(r.appToken, true);

     //2.更新屏幕方向
    if (checkConfig) {
        Configuration config = mWindowManager.updateOrientationFromAppTokens(
                mService.mConfiguration,
                r.mayFreezeScreenLocked(app) ? r.appToken : null);
        mService.updateConfigurationLocked(config, r, false, false);
    }

    r.app = app;
    app.waitingToKill = null;
    r.launchCount++;
    r.lastLaunchTime = SystemClock.uptimeMillis();
   
    int idx = app.activities.indexOf(r);
    if (idx < 0) {
        app.activities.add(r);
    }
    mService.updateLruProcessLocked(app, true, null);//3.更新最近显示的界面,及内存回收
    mService.updateOomAdjLocked();

    final ActivityStack stack = r.task.stack;
    try {  //4.和12步一样,也是通过ApplicationThread像activity发消息,然后有activityThread来进行处理启动activity
        app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
                r.compat, r.task.voiceInteractor, app.repProcState, r.icicle, r.persistentState,
                results, newIntents, !andResume, mService.isNextTransitionForward(),
                profilerInfo);            
    }  
    return true;
}

14.activityThread的scheduleLaunchActivity最终会调用activityThread.handleLaunchActivity来加载指定的类.继续看

//activityThread
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    
    unscheduleGcIdler();//1.暂停内存回收器
    mSomeActivitiesChanged = true;


    // 2.处理屏幕方向
    handleConfigurationChanged(null, null);


    //3.加载activity,这里真正将activity创建出来.并和窗口Window绑定,指向activity的onCreate,onStar,onRestoreInstanceState,等方法.
    Activity a = performLaunchActivity(r, customIntent);

    if (a != null) {
        r.createdConfig = new Configuration(mConfiguration);
        Bundle oldState = r.state;
        //4.内部调用activity的onResuem,同时会通过WindowManager把当前acitvity的窗口隐藏
        handleResumeActivity(r.token, false, r.isForward,
                !r.activity.mFinished && !r.startsNotResumed);

        if (!r.activity.mFinished && r.startsNotResumed) {
            try {
                r.activity.mCalled = false;
                //5.如果activity没有resume成功,就调用onPause方法,这应该是意外情况
                mInstrumentation.callActivityOnPause(r.activity);
             }  
    }
}

15.接下来在看一下14.3加载activity方法

//activityThread
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
   //1.找到packageInfo,通过packageInfo和PackageManager找到activity对应的ComponentName 
  //通过ComponentName 就能加载得到指定的activity
    ActivityInfo aInfo = r.activityInfo;
    if (r.packageInfo == null) {
        r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                Context.CONTEXT_INCLUDE_CODE);
    }
    ComponentName component = r.intent.getComponent();
    if (component == null) {
        component = r.intent.resolveActivity(
            mInitialApplication.getPackageManager());
        r.intent.setComponent(component);
    }


    Activity activity = null;
    try {
        java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        StrictMode.incrementExpectedActivityCount(activity.getClass());
        r.intent.setExtrasClassLoader(cl);
        r.intent.prepareToEnterProcess();
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    } catch (Exception e) {
        if (!mInstrumentation.onException(activity, e)) {
            throw new RuntimeException(
                "Unable to instantiate activity " + component
                + ": " + e.toString(), e);
        }
    }

    try {//2.拿到application对象,没有的话就创建一个
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);

 

        if (activity != null) {//3.创建一个ContextImpl对象,每个activity都含一个ContextImpl对象 ,该对象是一个轻量类.然后调用 
// activity.attach方法把contextImpl设置为activity的baseContext,并创建window对象,为window对象设置WindowManager
            Context appContext = createBaseContextForActivity(r, activity);
            CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
            Configuration config = new Configuration(mCompatConfiguration);
            
            activity.attach(appContext, this, getInstrumentation(), r.token,
                    r.ident, app, r.intent, r.activityInfo, title, r.parent,
                    r.embeddedID, r.lastNonConfigurationInstances, config,
                    r.voiceInteractor);

           
            if (theme != 0) {//4.为activity设置主题模式,该主题模式从AndroidManifest.xml中获取
                activity.setTheme(theme);
            }

            activity.mCalled = false;
            if (r.isPersistable()) {//5.调用activity的oncreate
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
          

            if (!r.activity.mFinished) {
                if (r.isPersistable()) {
                    if (r.state != null || r.persistentState != null) {//5.调用activity的onRestoreInstanceState
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                                r.persistentState);
                    }
                } 
            }
            if (!r.activity.mFinished) {
                activity.mCalled = false;
                if (r.isPersistable()) {//6.调用activity的OnPostCreate
                    mInstrumentation.callActivityOnPostCreate(activity, r.state,
                            r.persistentState);
                }  
            }
        }
        r.paused = true;
        mActivities.put(r.token, r); //7.目标activity的ActivityRecord加入到mActivities中,
    } catch (SuperNotCalledException e) {
        throw e;
    }  
    return activity; 
}

16.至此.目标activity的启动就差不多了.剩下一些是activity和WindowManagerService 的调用来显示窗口的.这些不看了.之前7.9步骤中.是先暂停旧的activity.在启动加载新的activity.所以我们要看下 ActivityStack.startPausingLocked如何暂停旧的activity 这些代码的执行流程是在 8-15步之前的

//ActivityStack
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming,
        boolean dontWait) {
    if (mPausingActivity != null) {//1.mPausingActivity 是正在执行pause的activity.如果不为空,应该先等他执行完.    
        completePauseLocked(false);
    }
    ActivityRecord prev = mResumedActivity;//2.mResumedActivity是正在显示的activity.如果他为空,
//说明没有activity可见,则不需要执行pause,而是应该找到栈顶的activityRecord对应的activity,让他显示出来
    if (prev == null) {
        if (!resuming) {    
            mStackSupervisor.resumeTopActivitiesLocked();
        }
        return false;
    }
    //3.如果当前activity有子activity,则把他们都暂停.
    if (mActivityContainer.mParentActivity == null) {
        mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping, resuming, dontWait);
    }


    if (prev.app != null && prev.app.thread != null) {//4.需要判断要被暂停的activity的进程正在运行,如果线程都不运行了,就不用暂停,
//然后通过applicationThread.schedulePauseActivity执行暂停过程
        try {
            prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
                    userLeaving, prev.configChangeFlags, dontWait);
        } catch (Exception e) {
            mPausingActivity = null;
            mLastPausedActivity = null;
            mLastNoHistoryActivity = null;
        }
    } else {
        mPausingActivity = null;
        mLastPausedActivity = null;
        mLastNoHistoryActivity = null;
    }

    if (mPausingActivity != null) { 
        if (!uiSleeping) {//5.如果只是因为关闭屏幕而暂停activity,那么不应该断掉该activity的事件触发连接,以免在屏幕亮起时没有出门事件的分发.
            prev.pauseKeyDispatchingLocked();
        }  
        if (dontWait) {
            completePauseLocked(false);//6.立刻完成该activity的暂停
            return false;
        } else {
             //8.发消息延时通知activity的暂停,以防app 没有响应
            Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
            msg.obj = prev;
            prev.pauseTime = SystemClock.uptimeMillis();
            mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);        
            return true;
        }

    } else {           
        if (!resuming) {//9.展示目标activity
            mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null);
        }
        return false;
    }
}

17.接下来看16,4步,ApplicationThread.schedulePauseActivity,内部依旧是通过发送消息.通知ActivityThread的handlePauseActivity方法来进行activity的暂停,所以接着看ActivityThread.handlePauseActivity方法

 // ActivityThread
private void handlePauseActivity(IBinder token, boolean finished,
        boolean userLeaving, int configChanges, boolean dontReport) {
    ActivityClientRecord r = mActivities.get(token);
    if (r != null) {//1.判断是否为用户离开产生的消息,安卓后台会检测用户多长时间没有和activity交互,当用户离开时,
//系统会调用 Activity.onUserLeaving方法通知activity.
        if (userLeaving) {
            performUserLeavingActivity(r);
        }

        r.activity.mConfigChangeFlags |= configChanges;
        performPauseActivity(token, finished, r.isPreHoneycomb());//2.执行activity的暂停

        // 3.通知Ams.当前activity已经暂停了
        if (!dontReport) {
            try {
                ActivityManagerNative.getDefault().activityPaused(token);
            } catch (RemoteException ex) {
            }
        }
        mSomeActivitiesChanged = true;
    }
}
//ActivityThread
final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
        boolean saveState) {
    if (r.paused) {//4.同一个activity不可以暂停两次,如果已经暂停了.就抛出一个异常
        if (r.activity.mFinished) {
            return null;
        }
        RuntimeException e = new RuntimeException(
                "Performing pause of activity that is not resumed: "
                + r.intent.getComponent().toShortString());
      
    }
    if (finished) {
        r.activity.mFinished = true;
    }
    try {
        //  5.调用activity的onSaveInstanceState 方法保存数据,把数据保存在了ActivityRecord里了.
        if (!r.activity.mFinished && saveState) {
            callCallActivityOnSaveInstanceState(r);
        }
        // Now we are idle.
        r.activity.mCalled = false;
        mInstrumentation.callActivityOnPause(r.activity);//6.调用activity的onpause

} catch (Exception e) {
        if (!mInstrumentation.onException(r.activity, e)) {
            throw new RuntimeException(
                    "Unable to pause activity "
                    + r.intent.getComponent().toShortString()
                    + ": " + e.toString(), e);
        }
    }
    r.paused = true;

    ArrayList<OnActivityPausedListener> listeners;
    synchronized (mOnPauseListeners) {
        listeners = mOnPauseListeners.remove(r.activity);
    }
    int size = (listeners != null ? listeners.size() : 0);
    for (int i = 0; i < size; i++) {
        listeners.get(i).onPaused(r.activity);//7.通知所有的监听器.
    }

    return !r.activity.mFinished && saveState ? r.state : null;
}

18.接着看 17.3 activityThread在执行完performPauseActivity后会通知Ams,当前activity已经暂停完毕.看Ams.activityPaused.内部又回调ActivityStack.activityPausedLocked,内部又回调ActivityStack.completePauseLocked方法

//ActivityStack
private void completePauseLocked(boolean resumeNext) {
    ActivityRecord prev = mPausingActivity;//1.正在被暂停的activity
 

    if (prev != null) {
        prev.state = ActivityState.PAUSED;//2.把该activity的状态更新
        if (prev.finishing) {//3.如果该activity已经finish标识为true,就执行finish,该条件在内存回收时使用
            prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
        } else if (prev.app != null) {
          

            if (prev.configDestroy) {
                destroyActivityLocked(prev, true, "pause-config");//4.销毁该activity.
            } else if (!hasVisibleBehindActivity()) {
                 //5.stop该activity,这里和要关闭的activity数量有关,如果要关闭的数量大于3个,就开始执行activity的关闭,否则延迟执行.
                mStackSupervisor.mStoppingActivities.add(prev);
                if (mStackSupervisor.mStoppingActivities.size() > 3 ||
                        prev.frontOfTask && mTaskHistory.size() <= 1) {
                    mStackSupervisor.scheduleIdleLocked();
                } else {
                    mStackSupervisor.checkReadyForSleepLocked();
                }
            }
        } else {
            
            prev = null;
        }
        mPausingActivity = null; //6.此时activity已经pause完毕.
    }

   //7.显示新的activity
  mStackSupervisor.resumeTopActivitiesLocked(topStack, null, null);
}

19.至此,旧activity已经pause完毕,他会等待在合适的时候被stop,destory掉.然后在执行8-15之间的新activity的启动.这就是activity的启动流程.

上一篇下一篇

猜你喜欢

热点阅读