Activity的启动流程 Android5.1.1

启动Activity有多种方式,简单记录下在Launcher下点击应用图表启动Activity的流程。

以启动Setting为例,通过跟踪Launcher.java的onclick事件,发现最终通过ActivityManagerNative.getDefault()获取ActivityManager的代理对象,然后调用startActivity()方法调用到ActivityManagerService中的startActivity()方法。继续跟踪,调用到ActivityStackSupervisor中的startActivityMayWait()方法。

  1. final int startActivityMayWait(IApplicationThread caller, int callingUid,  
  2.             String callingPackage, Intent intent, String resolvedType,  
  3.             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,  
  4.             IBinder resultTo, String resultWho, int requestCode, int startFlags,  
  5.             ProfilerInfo profilerInfo, WaitResult outResult, Configuration config,  
  6.             Bundle options, int userId, IActivityContainer iContainer, TaskRecord inTask) {  
  7.         // Refuse possible leaked file descriptors  
  8.         if (intent != null && intent.hasFileDescriptors()) {  
  9.             throw new IllegalArgumentException("File descriptors passed in Intent");  
  10.         }  
  11.         boolean componentSpecified = intent.getComponent() != null;//true  
  12.   
  13.         // Don't modify the client's object!  
  14.         intent = new Intent(intent);//new一个Intent,不改变原始Intent.  
  15.   
  16.         // Collect information about the target of the Intent.  
  17.         ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,  
  18.                 profilerInfo, userId);//通过PackageManager查询对应的ActivityInfo.  
  19.   
  20.         ActivityContainer container = (ActivityContainer)iContainer;  
  21.         synchronized (mService) {  
  22.             //判断启动此Activity的pid与uid  
  23.             final int realCallingPid = Binder.getCallingPid();  
  24.             final int realCallingUid = Binder.getCallingUid();  
  25.             int callingPid;  
  26.             if (callingUid >= 0) {  
  27.                 callingPid = -1;  
  28.             } else if (caller == null) {  
  29.                 callingPid = realCallingPid;  
  30.                 callingUid = realCallingUid;  
  31.             } else {  
  32.                 callingPid = callingUid = -1;  
  33.             }  
  34.   
  35.             final ActivityStack stack;  
  36.             if (container == null || container.mStack.isOnHomeDisplay()) {  
  37.                 stack = getFocusedStack();  
  38.             } else {  
  39.                 stack = container.mStack;  
  40.             }  
  41.             stack.mConfigWillChange = config != null  
  42.                     && mService.mConfiguration.diff(config) != 0;  
  43.   
  44.             final long origId = Binder.clearCallingIdentity();  
  45.   
  46.             if (aInfo != null &&  
  47.                     (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {  
  48.               //不满足此条件  
  49.               ''''''  
  50.             }  
  51.              //调用到startActivityLocked()方法。  
  52.             int res = startActivityLocked(caller, intent, resolvedType, aInfo,  
  53.                     voiceSession, voiceInteractor, resultTo, resultWho,  
  54.                     requestCode, callingPid, callingUid, callingPackage,  
  55.                     realCallingPid, realCallingUid, startFlags, options,  
  56.                     componentSpecified, null, container, inTask);  
  57.   
  58.             Binder.restoreCallingIdentity(origId);  
  59.             //没有回调  
  60.             if (outResult != null) {  
  61.                ''''''  
  62.             }  
  63.   
  64.             return res;  
  65.         }  
  66.     }  

startActivityMayWait的主要作用就是查询对应的ActivityInfo,获取callingPid与callingUid,然后转交给startActivityLocked()方法。

  1. final int startActivityLocked(IApplicationThread caller,  
  2.             Intent intent, String resolvedType, ActivityInfo aInfo,  
  3.             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,  
  4.             IBinder resultTo, String resultWho, int requestCode,  
  5.             int callingPid, int callingUid, String callingPackage,  
  6.             int realCallingPid, int realCallingUid, int startFlags, Bundle options,  
  7.             boolean componentSpecified, ActivityRecord[] outActivity, ActivityContainer container,  
  8.             TaskRecord inTask) {  
  9.         int err = ActivityManager.START_SUCCESS;  
  10.   
  11.         ProcessRecord callerApp = null;  
  12.         if (caller != null) {  
  13.             //获取caller对应的ProcessRecord  
  14.             callerApp = mService.getRecordForAppLocked(caller);  
  15.             if (callerApp != null) {  
  16.                 callingPid = callerApp.pid;  
  17.                 callingUid = callerApp.info.uid;  
  18.             } else {  
  19.                 Slog.w(TAG, "Unable to find app for caller " + caller  
  20.                       + " (pid=" + callingPid + ") when starting: "  
  21.                       + intent.toString());  
  22.                 err = ActivityManager.START_PERMISSION_DENIED;  
  23.             }  
  24.         }  
  25.   
  26.         ActivityRecord sourceRecord = null;  
  27.         ActivityRecord resultRecord = null;  
  28.         if (resultTo != null) {//resultTo代表Launcher  
  29.             sourceRecord = isInAnyStackLocked(resultTo);  
  30.             if (DEBUG_RESULTS) Slog.v(  
  31.                 TAG, "Will send result to " + resultTo + " " + sourceRecord);  
  32.             if (sourceRecord != null) {  
  33.                 //requestCode 为-1,不需要返回结果。  
  34.                 if (requestCode >= 0 && !sourceRecord.finishing) {  
  35.                     resultRecord = sourceRecord;  
  36.                 }  
  37.             }  
  38.         }  
  39.   
  40.         final int launchFlags = intent.getFlags();  
  41.   
  42.         ......  
  43.   
  44.         final ActivityStack resultStack = resultRecord == null ? null : resultRecord.task.stack;//resultStack为空。  
  45.   
  46.   
  47.         //检查是否有启动权限。  
  48.         final int startAnyPerm = mService.checkPermission(  
  49.                 START_ANY_ACTIVITY, callingPid, callingUid);  
  50.         final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,  
  51.                 callingUid, aInfo.applicationInfo.uid, aInfo.exported);  
  52.         if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {  
  53.             if (resultRecord != null) {  
  54.                 resultStack.sendActivityResultLocked(-1,  
  55.                     resultRecord, resultWho, requestCode,  
  56.                     Activity.RESULT_CANCELED, null);  
  57.             }  
  58.             String msg;  
  59.             if (!aInfo.exported) {  
  60.                 msg = "Permission Denial: starting " + intent.toString()  
  61.                         + " from " + callerApp + " (pid=" + callingPid  
  62.                         + ", uid=" + callingUid + ")"  
  63.                         + " not exported from uid " + aInfo.applicationInfo.uid;  
  64.             } else {  
  65.                 msg = "Permission Denial: starting " + intent.toString()  
  66.                         + " from " + callerApp + " (pid=" + callingPid  
  67.                         + ", uid=" + callingUid + ")"  
  68.                         + " requires " + aInfo.permission;  
  69.             }  
  70.             Slog.w(TAG, msg);  
  71.             throw new SecurityException(msg);  
  72.         }  
  73.   
  74.         boolean abort = !mService.mIntentFirewall.checkStartActivity(intent, callingUid,  
  75.                 callingPid, resolvedType, aInfo.applicationInfo);  
  76.   
  77.         ......  
  78.   
  79.         //创建对应的ActivityRecord  
  80.         ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,  
  81.                 intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,  
  82.                 requestCode, componentSpecified, this, container, options);  
  83.         if (outActivity != null) {  
  84.             outActivity[0] = r;  
  85.         }  
  86.   
  87.         final ActivityStack stack = getFocusedStack();  
  88.         ......  
  89.   
  90.         doPendingActivityLaunchesLocked(false);  
  91.           
  92.         //调用startActivityUncheckedLocked()方法。  
  93.         err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,  
  94.                 startFlags, true, options, inTask);  
  95.   
  96.         if (err < 0) {  
  97.             // If someone asked to have the keyguard dismissed on the next  
  98.             // activity start, but we are not actually doing an activity  
  99.             // switch...  just dismiss the keyguard now, because we  
  100.             // probably want to see whatever is behind it.  
  101.             notifyActivityDrawnForKeyguard();  
  102.         }  
  103.         return err;  
  104.     }  

startActivityLocked的主要作用:获取caller的ProcessRecord,检查是否需要返回结果,检查各种flag标记,检查caller是否有启动权限,创建对应的ActivityRecord,最后转到startActivityUncheckedLocked()方法。

  1. final int startActivityUncheckedLocked(ActivityRecord r, ActivityRecord sourceRecord,  
  2.         IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags,  
  3.         boolean doResume, Bundle options, TaskRecord inTask) {  
  4.     final Intent intent = r.intent;  
  5.     final int callingUid = r.launchedFromUid;  
  6.   
  7.     // In some flows in to this function, we retrieve the task record and hold on to it  
  8.     // without a lock before calling back in to here...  so the task at this point may  
  9.     // not actually be in recents.  Check for that, and if it isn't in recents just  
  10.     // consider it invalid.  
  11.     if (inTask != null && !inTask.inRecents) {  
  12.         Slog.w(TAG, "Starting activity in task not in recents: " + inTask);  
  13.         inTask = null;  
  14.     }  
  15.     //检查启动模式  
  16.     final boolean launchSingleTop = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP;  
  17.     final boolean launchSingleInstance = r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE;  
  18.     final boolean launchSingleTask = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK;  
  19.   
  20.     int launchFlags = intent.getFlags();  
  21.     if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0 &&  
  22.         ......  
  23.     } else {  
  24.         switch (r.info.documentLaunchMode) {  
  25.             case ActivityInfo.DOCUMENT_LAUNCH_NONE:  
  26.                 break;  
  27.             case ActivityInfo.DOCUMENT_LAUNCH_INTO_EXISTING:  
  28.                 launchFlags |= Intent.FLAG_ACTIVITY_NEW_DOCUMENT;  
  29.                 break;  
  30.             case ActivityInfo.DOCUMENT_LAUNCH_ALWAYS:  
  31.                 launchFlags |= Intent.FLAG_ACTIVITY_NEW_DOCUMENT;  
  32.                 break;  
  33.             case ActivityInfo.DOCUMENT_LAUNCH_NEVER:  
  34.                 launchFlags &= ~Intent.FLAG_ACTIVITY_MULTIPLE_TASK;  
  35.                 break;  
  36.         }  
  37.     }  
  38.   
  39.     final boolean launchTaskBehind = r.mLaunchTaskBehind  
  40.             && !launchSingleTask && !launchSingleInstance  
  41.             && (launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0;  
  42.     //resultTo为空  
  43.     if (r.resultTo != null && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {  
  44.        ......  
  45.     }  
  46.   
  47.     if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0 && r.resultTo == null) {  
  48.         launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;  
  49.     }  
  50.   
  51.     // If we are actually going to launch in to a new task, there are some cases where  
  52.     // we further want to do multiple task.  
  53.     if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {  
  54.         if (launchTaskBehind  
  55.                 || r.info.documentLaunchMode == ActivityInfo.DOCUMENT_LAUNCH_ALWAYS) {  
  56.             launchFlags |= Intent.FLAG_ACTIVITY_MULTIPLE_TASK;  
  57.         }  
  58.     }  
  59.   
  60.     // We'll invoke onUserLeaving before onPause only if the launching  
  61.     // activity did not explicitly state that this is an automated launch.  
  62.     mUserLeaving = (launchFlags & Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;  
  63.     // If the caller has asked not to resume at this point, we make note  
  64.     // of this in the record so that we can skip it when trying to find  
  65.     // the top running activity.  
  66.     if (!doResume) {  
  67.         r.delayedResume = true;  
  68.     }  
  69.   
  70.     ActivityRecord notTop =  
  71.             (launchFlags & Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP) != 0 ? r : null;  
  72.     if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {  
  73.         ActivityRecord checkedCaller = sourceRecord;  
  74.         if (checkedCaller == null) {  
  75.             checkedCaller = getFocusedStack().topRunningNonDelayedActivityLocked(notTop);  
  76.         }  
  77.         if (!checkedCaller.realActivity.equals(r.realActivity)) {  
  78.             // Caller is not the same as launcher, so always needed.  
  79.             startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;  
  80.         }  
  81.     }  
  82.     //上边主要是通过启动模式跟flag来确定actiivty是否需要运行于新的task  
  83.   
  84.     boolean addingToTask = false;  
  85.     TaskRecord reuseTask = null;  
  86.   
  87.     // If the caller is not coming from another activity, but has given us an  
  88.     // explicit task into which they would like us to launch the new activity,  
  89.     // then let's see about doing that.  
  90.     if (sourceRecord == null && inTask != null && inTask.stack != null) {  
  91.         //不满足此条件  
  92.     } else {  
  93.         inTask = null;  
  94.     }  
  95.   
  96.     if (inTask == null) {  
  97.         if (sourceRecord == null) {//sourceRecord不为空  
  98.             // This activity is not being started from another...  in this  
  99.             // case we -always- start a new task.  
  100.             if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0 && inTask == null) {  
  101.                 Slog.w(TAG, "startActivity called from non-Activity context; forcing " +  
  102.                         "Intent.FLAG_ACTIVITY_NEW_TASK for: " + intent);  
  103.                 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;  
  104.             }  
  105.         } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {  
  106.             // The original activity who is starting us is running as a single  
  107.             // instance...  this new activity it is starting must go on its  
  108.             // own task.  
  109.             launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;  
  110.         } else if (launchSingleInstance || launchSingleTask) {  
  111.             // The activity being started is a single instance...  it always  
  112.             // gets launched into its own task.  
  113.             launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;  
  114.         }  
  115.     }  
  116.   
  117.     ActivityInfo newTaskInfo = null;  
  118.     Intent newTaskIntent = null;  
  119.     ActivityStack sourceStack;  
  120.     if (sourceRecord != null) {  
  121.         if (sourceRecord.finishing) {  
  122.             // If the source is finishing, we can't further count it as our source.  This  
  123.             // is because the task it is associated with may now be empty and on its way out,  
  124.             // so we don't want to blindly throw it in to that task.  Instead we will take  
  125.             // the NEW_TASK flow and try to find a task for it. But save the task information  
  126.             // so it can be used when creating the new task.  
  127.             if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {  
  128.                 Slog.w(TAG, "startActivity called from finishing " + sourceRecord  
  129.                         + "; forcing " + "Intent.FLAG_ACTIVITY_NEW_TASK for: " + intent);  
  130.                 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;  
  131.                 newTaskInfo = sourceRecord.info;  
  132.                 newTaskIntent = sourceRecord.task.intent;  
  133.             }  
  134.             sourceRecord = null;  
  135.             sourceStack = null;  
  136.         } else {  
  137.             sourceStack = sourceRecord.task.stack;  
  138.         }  
  139.     } else {  
  140.         sourceStack = null;  
  141.     }  
  142.   
  143.     boolean movedHome = false;  
  144.     ActivityStack targetStack;  
  145.   
  146.     intent.setFlags(launchFlags);  
  147.   
  148.     // We may want to try to place the new activity in to an existing task.  We always  
  149.     // do this if the target activity is singleTask or singleInstance; we will also do  
  150.     // this if NEW_TASK has been requested, and there is not an additional qualifier telling  
  151.     // us to still place it in a new task: multi task, always doc mode, or being asked to  
  152.     // launch this as a new task behind the current one.  
  153.     if (((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&  
  154.             (launchFlags & Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)  
  155.             || launchSingleInstance || launchSingleTask) {//满足此条件  
  156.         // If bring to front is requested, and no result is requested and we have not  
  157.         // been given an explicit task to launch in to, and  
  158.         // we can find a task that was started with this same  
  159.         // component, then instead of launching bring that one to the front.  
  160.         if (inTask == null && r.resultTo == null) {//满足  
  161.             // See if there is a task to bring to the front.  If this is  
  162.             // a SINGLE_INSTANCE activity, there can be one and only one  
  163.             // instance of it in the history, and it is always in its own  
  164.             // unique task, so we do a special search.  
  165.             //检查是否有可复用的Task及Activity。  
  166.             ActivityRecord intentActivity = !launchSingleInstance ?  
  167.                     findTaskLocked(r) : findActivityLocked(intent, r.info);  
  168.             //本例为第一次启动,所以intentActivity为空。  
  169.             if (intentActivity != null) {  
  170.                 ......  
  171.         }  
  172.     }  
  173.   
  174.     if (r.packageName != null) {  
  175.         // If the activity being launched is the same as the one currently  
  176.         // at the top, then we need to check if it should only be launched  
  177.         // once.  
  178.         ActivityStack topStack = getFocusedStack();  
  179.         //top为Launcher  
  180.         ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(notTop);  
  181.         if (top != null && r.resultTo == null) {//满足  
  182.             //检测是否可复用Activity,top为Launcher,r为Setting,不满足  
  183.             if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {  
  184.                 if (top.app != null && top.app.thread != null) {  
  185.                     if ((launchFlags & Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0  
  186.                         || launchSingleTop || launchSingleTask) {  
  187.                         ActivityStack.logStartActivity(EventLogTags.AM_NEW_INTENT, top,  
  188.                                 top.task);  
  189.                         // For paranoia, make sure we have correctly  
  190.                         // resumed the top activity.  
  191.                         topStack.mLastPausedActivity = null;  
  192.                         if (doResume) {  
  193.                             resumeTopActivitiesLocked();  
  194.                         }  
  195.                         ActivityOptions.abort(options);  
  196.                         if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {  
  197.                             // We don't need to start a new activity, and  
  198.                             // the client said not to do anything if that  
  199.                             // is the case, so this is it!  
  200.                             return ActivityManager.START_RETURN_INTENT_TO_CALLER;  
  201.                         }  
  202.                         top.deliverNewIntentLocked(callingUid, r.intent, r.launchedFromPackage);  
  203.                         return ActivityManager.START_DELIVERED_TO_TOP;  
  204.                     }  
  205.                 }  
  206.             }  
  207.         }  
  208.   
  209.     } else {  
  210.         .....  
  211.     }  
  212.   
  213.     boolean newTask = false;  
  214.     boolean keepCurTransition = false;  
  215.   
  216.     TaskRecord taskToAffiliate = launchTaskBehind && sourceRecord != null ?  
  217.             sourceRecord.task : null;  
  218.   
  219.     // Should this be considered a new task?  
  220.     if (r.resultTo == null && inTask == null && !addingToTask  
  221.             && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {//满足  
  222.         if (isLockTaskModeViolation(reuseTask)) {  
  223.             Slog.e(TAG, "Attempted Lock Task Mode violation r=" + r);  
  224.             return ActivityManager.START_RETURN_LOCK_TASK_MODE_VIOLATION;  
  225.         }  
  226.         newTask = true;  
  227.         targetStack = adjustStackFocus(r, newTask);  
  228.         if (!launchTaskBehind) {  
  229.             targetStack.moveToFront("startingNewTask");  
  230.         }  
  231.         if (reuseTask == null) {  
  232.             //ActivityRecord与TaskRecord相关连。  
  233.             //getNextTaskId()方法更新Task数量  
  234.             r.setTask(targetStack.createTaskRecord(getNextTaskId(),  
  235.                     newTaskInfo != null ? newTaskInfo : r.info,  
  236.                     newTaskIntent != null ? newTaskIntent : intent,  
  237.                     voiceSession, voiceInteractor, !launchTaskBehind /* toTop */),  
  238.                     taskToAffiliate);  
  239.         } else {  
  240.             r.setTask(reuseTask, taskToAffiliate);  
  241.         }  
  242.         if (!movedHome) {  
  243.             if ((launchFlags &  
  244.                     (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))  
  245.                     == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {  
  246.                 // Caller wants to appear on home activity, so before starting  
  247.                 // their own activity we will bring home to the front.  
  248.                 r.task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);  
  249.             }  
  250.         }  
  251.     } else if (sourceRecord != null) {  
  252.         ......  
  253.     } else if (inTask != null) {  
  254.        ......  
  255.     } else {  
  256.        ......  
  257.     }  
  258.     //权限相关  
  259.     mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,  
  260.             intent, r.getUriPermissionsLocked(), r.userId);  
  261.   
  262.     if (sourceRecord != null && sourceRecord.isRecentsActivity()) {  
  263.         r.task.setTaskToReturnTo(RECENTS_ACTIVITY_TYPE);  
  264.     }  
  265.     if (newTask) {  
  266.         EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.userId, r.task.taskId);  
  267.     }  
  268.     ActivityStack.logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);  
  269.     targetStack.mLastPausedActivity = null;  
  270.     //转到startActivityLocked()方法。  
  271.     targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);  
  272.     if (!launchTaskBehind) {  
  273.         // Don't set focus on an activity that's going to the back.  
  274.         mService.setFocusedActivityLocked(r, "startedActivity");  
  275.     }  
  276.     return ActivityManager.START_SUCCESS;  
  277. }  

startActivityUncheckedLocked主要功能:根据启动模式和启动标记,判断是否需要在新的Task中启动Activity。判断是否有可复用的Task或Activity。将ActivityRecord与TaskRecord关连,更新Task数量,调用startActivityLocked()方法。

  1. final void startActivityLocked(ActivityRecord r, boolean newTask,  
  2.             boolean doResume, boolean keepCurTransition, Bundle options) {  
  3.         TaskRecord rTask = r.task;  
  4.         final int taskId = rTask.taskId;  
  5.         // mLaunchTaskBehind tasks get placed at the back of the task stack.  
  6.         if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {  
  7.             // Last activity in task had been removed or ActivityManagerService is reusing task.  
  8.             // Insert or replace.  
  9.             // Might not even be in.  
  10.             insertTaskAtTop(rTask);  
  11.             mWindowManager.moveTaskToTop(taskId);  
  12.         }  
  13.         TaskRecord task = null;  
  14.         if (!newTask) {//本例中newTask为true。  
  15.             // If starting in an existing task, find where that is...  
  16.             boolean startIt = true;  
  17.             for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {  
  18.                 task = mTaskHistory.get(taskNdx);  
  19.                 if (task.getTopActivity() == null) {  
  20.                     // All activities in task are finishing.  
  21.                     continue;  
  22.                 }  
  23.                 if (task == r.task) {  
  24.                     // Here it is!  Now, if this is not yet visible to the  
  25.                     // user, then just add it without starting; it will  
  26.                     // get started when the user navigates back to it.  
  27.                     if (!startIt) {  
  28.                         if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "  
  29.                                 + task, new RuntimeException("here").fillInStackTrace());  
  30.                         task.addActivityToTop(r);  
  31.                         r.putInHistory();  
  32.                         mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,  
  33.                                 r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,  
  34.                                 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0,  
  35.                                 r.userId, r.info.configChanges, task.voiceSession != null,  
  36.                                 r.mLaunchTaskBehind);  
  37.                         if (VALIDATE_TOKENS) {  
  38.                             validateAppTokensLocked();  
  39.                         }  
  40.                         ActivityOptions.abort(options);  
  41.                         return;  
  42.                     }  
  43.                     break;  
  44.                 } else if (task.numFullscreen > 0) {  
  45.                     startIt = false;  
  46.                 }  
  47.             }  
  48.         }  
  49.         ......  
  50.   
  51.         task = r.task;  
  52.   
  53.         task.addActivityToTop(r);//将Setting对应的ActivityRecord放到栈顶。  
  54.         task.setFrontOfTask();  
  55.   
  56.         r.putInHistory();  
  57.         if (!isHomeStack() || numActivities() > 0) {  
  58.             // We want to show the starting preview window if we are  
  59.             // switching to a new task, or the next activity's process is  
  60.             // not currently running.  
  61.             boolean showStartingIcon = newTask;  
  62.             ProcessRecord proc = r.app;  
  63.             if (proc == null) {  
  64.                 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);  
  65.             }  
  66.             if (proc == null || proc.thread == null) {  
  67.                 showStartingIcon = true;  
  68.             }  
  69.             if (DEBUG_TRANSITION) Slog.v(TAG,  
  70.                     "Prepare open transition: starting " + r);  
  71.             if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {  
  72.                 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, keepCurTransition);  
  73.                 mNoAnimActivities.add(r);  
  74.             } else {  
  75.                 mWindowManager.prepareAppTransition(newTask  
  76.                         ? r.mLaunchTaskBehind  
  77.                                 ? AppTransition.TRANSIT_TASK_OPEN_BEHIND  
  78.                                 : AppTransition.TRANSIT_TASK_OPEN  
  79.                         : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition);  
  80.                 mNoAnimActivities.remove(r);  
  81.             }  
  82.             mWindowManager.addAppToken(task.mActivities.indexOf(r),  
  83.                     r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,  
  84.                     (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId,  
  85.                     r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);  
  86.             boolean doShow = true;  
  87.             if (newTask) {  
  88.                 // Even though this activity is starting fresh, we still need  
  89.                 // to reset it to make sure we apply affinities to move any  
  90.                 // existing activities from other tasks in to it.  
  91.                 // If the caller has requested that the target task be  
  92.                 // reset, then do so.  
  93.                 if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {  
  94.                     resetTaskIfNeededLocked(r, r);  
  95.                     doShow = topRunningNonDelayedActivityLocked(null) == r;  
  96.                 }  
  97.             } else if (options != null && new ActivityOptions(options).getAnimationType()  
  98.                     == ActivityOptions.ANIM_SCENE_TRANSITION) {  
  99.                 doShow = false;  
  100.             }  
  101.             if (r.mLaunchTaskBehind) {  
  102.                 // Don't do a starting window for mLaunchTaskBehind. More importantly make sure we  
  103.                 // tell WindowManager that r is visible even though it is at the back of the stack.  
  104.                 mWindowManager.setAppVisibility(r.appToken, true);  
  105.                 ensureActivitiesVisibleLocked(null0);  
  106.             } else if (SHOW_APP_STARTING_PREVIEW && doShow) {  
  107.                 // Figure out if we are transitioning from another activity that is  
  108.                 // "has the same starting icon" as the next one.  This allows the  
  109.                 // window manager to keep the previous window it had previously  
  110.                 // created, if it still had one.  
  111.                 ActivityRecord prev = mResumedActivity;  
  112.                 if (prev != null) {  
  113.                     // We don't want to reuse the previous starting preview if:  
  114.                     // (1) The current activity is in a different task.  
  115.                     if (prev.task != r.task) {  
  116.                         prev = null;  
  117.                     }  
  118.                     // (2) The current activity is already displayed.  
  119.                     else if (prev.nowVisible) {  
  120.                         prev = null;  
  121.                     }  
  122.                 }  
  123.                 mWindowManager.setAppStartingWindow(  
  124.                         r.appToken, r.packageName, r.theme,  
  125.                         mService.compatibilityInfoForPackageLocked(  
  126.                                 r.info.applicationInfo), r.nonLocalizedLabel,  
  127.                         r.labelRes, r.icon, r.logo, r.windowFlags,  
  128.                         prev != null ? prev.appToken : null, showStartingIcon);  
  129.                 r.mStartingWindowShown = true;  
  130.             }  
  131.         } else {  
  132.             // If this is the first activity, don't do any fancy animations,  
  133.             // because there is nothing for it to animate on top of.  
  134.             mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,  
  135.                     r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,  
  136.                     (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId,  
  137.                     r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);  
  138.             ActivityOptions.abort(options);  
  139.             options = null;  
  140.         }  
  141.         if (VALIDATE_TOKENS) {  
  142.             validateAppTokensLocked();  
  143.         }  
  144.   
  145.         if (doResume) {  
  146.             mStackSupervisor.resumeTopActivitiesLocked(this, r, options);  
  147.         }  
  148.     }  

startActivityLocked主要功能:根据newTask判断是否复用task,将ActivityRecord放入栈顶,准备Activity切换动画,调用resumeTopActivitiesLocked()方法。

  1. boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,  
  2.             Bundle targetOptions) {  
  3.         if (targetStack == null) {  
  4.             targetStack = getFocusedStack();  
  5.         }  
  6.         // Do targetStack first.  
  7.         boolean result = false;  
  8.         if (isFrontStack(targetStack)) {//调用到ActivityStack的resumeTopActivityLocked()方法。本例中target为Setting  
  9.             result = targetStack.resumeTopActivityLocked(target, targetOptions);  
  10.         }  
  11.         for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {  
  12.             final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;  
  13.             for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {  
  14.                 final ActivityStack stack = stacks.get(stackNdx);  
  15.                 if (stack == targetStack) {  
  16.                     // Already started above.  
  17.                     continue;  
  18.                 }  
  19.                 if (isFrontStack(stack)) {  
  20.                     stack.resumeTopActivityLocked(null);  
  21.                 }  
  22.             }  
  23.         }  
  24.         return result;  
  25.     }  

resumeTopActivitiesLocked中继续调用了ActivityStack的resumeTopActivityLocked()方法,resumeTopActivityLocked()中又调用了resumeTopActivityInnerLocked()方法。

  1. final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {  
  2.         if (ActivityManagerService.DEBUG_LOCKSCREEN) mService.logLockScreen("");  
  3.         //判断ActivityManagerService是否在启动阶段  
  4.         if (!mService.mBooting && !mService.mBooted) {  
  5.             // Not ready yet!  
  6.             return false;  
  7.         }  
  8.   
  9.         // Find the first activity that is not finishing.  
  10.         //获取栈顶Activity,之前已经把对应的ActivityRecord放入栈顶,本例为Settings。  
  11.         final ActivityRecord next = topRunningActivityLocked(null);  
  12.   
  13.         // Remember how we'll process this pause/resume situation, and ensure  
  14.         // that the state is reset however we wind up proceeding.  
  15.         final boolean userLeaving = mStackSupervisor.mUserLeaving;  
  16.         mStackSupervisor.mUserLeaving = false;  
  17.   
  18.         final TaskRecord prevTask = prev != null ? prev.task : null;  
  19.         //如果next为空,启动Launcher。  
  20.         if (next == null) {  
  21.             // There are no more activities!  Let's just start up the  
  22.             // Launcher...  
  23.             ActivityOptions.abort(options);  
  24.             // Only resume home if on home display  
  25.             final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?  
  26.                     HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();  
  27.             return isOnHomeDisplay() &&  
  28.                     mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, "noMoreActivities");  
  29.         }  
  30.   
  31.         next.delayedResume = false;  
  32.   
  33.         // If the top activity is the resumed one, nothing to do.  
  34.         // mResumedActivity为Launcher,next为Settings  
  35.         if (mResumedActivity == next && next.state == ActivityState.RESUMED &&  
  36.                     mStackSupervisor.allResumedActivitiesComplete()) {  
  37.           ......  
  38.         }  
  39.   
  40.         final TaskRecord nextTask = next.task;  
  41.         ......  
  42.   
  43.         // The activity may be waiting for stop, but that is no longer  
  44.         // appropriate for it.  
  45.         //mStoppingActivities移除对应的ActivityRecord  
  46.         mStackSupervisor.mStoppingActivities.remove(next);  
  47.         mStackSupervisor.mGoingToSleepActivities.remove(next);  
  48.         next.sleeping = false;  
  49.         mStackSupervisor.mWaitingVisibleActivities.remove(next);  
  50.   
  51.         // If we are currently pausing an activity, then don't do anything  
  52.         // until that is done.  
  53.         ......  
  54.         // We need to start pausing the current activity so the top one  
  55.         // can be resumed...  
  56.         boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;  
  57.         boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);  
  58.         //mResumedActivity此时为Launcher  
  59.         if (mResumedActivity != null) {  
  60.             //调用startPausingLocked去暂停  
  61.             pausing |= startPausingLocked(userLeaving, falsetrue, dontWaitForPause);  
  62.         }  
  63.         //暂停成功为true  
  64.         if (pausing) {  
  65.             // At this point we want to put the upcoming activity's process  
  66.             // at the top of the LRU list, since we know we will be needing it  
  67.             // very soon and it would be a waste to let it get killed if it  
  68.             // happens to be sitting towards the end.  
  69.             if (next.app != null && next.app.thread != null) {  
  70.                 mService.updateLruProcessLocked(next.app, truenull);  
  71.             }  
  72.             if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();  
  73.             return true;  
  74.         }  
  75.         //后续省略,此次不会进入后续步骤,之后还会进入这个方法。  
  76.           ......  
  77.        }  

resumeTopActivityInnerLocked主要功能:判断next是否为空,mStoppingActivities移除对应的ActivityRecord,调用startPausingLocked()方法,去暂停mResumedActivity对应的Activity,本例为Launcher。

  1. final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming,  
  2.         boolean dontWait) {  
  3.     if (mPausingActivity != null) {  
  4.         Slog.wtf(TAG, "Going to pause when pause is already pending for " + mPausingActivity);  
  5.         completePauseLocked(false);  
  6.     }  
  7.     //将prev赋值为Launcher的ActivityRecord。  
  8.     ActivityRecord prev = mResumedActivity;  
  9.     if (prev == null) {  
  10.         ......  
  11.     }  
  12.     //置空mResumedActivity,mPausingActivity、mLastPausedActivity赋值为Launcher的ActivityRecord。  
  13.     mResumedActivity = null;  
  14.     mPausingActivity = prev;  
  15.     mLastPausedActivity = prev;  
  16.     mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0  
  17.             || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null;  
  18.     prev.state = ActivityState.PAUSING;//Launcher状态改为PAUSING。  
  19.     prev.task.touchActiveTime();  
  20.     clearLaunchTime(prev);  
  21.     final ActivityRecord next = mStackSupervisor.topRunningActivityLocked();  
  22.     if (mService.mHasRecents && (next == null || next.noDisplay || next.task != prev.task || uiSleeping)) {  
  23.         prev.updateThumbnailLocked(screenshotActivities(prev), null);  
  24.     }  
  25.     stopFullyDrawnTraceIfNeeded();  
  26.   
  27.     mService.updateCpuStats();  
  28.   
  29.     if (prev.app != null && prev.app.thread != null) {  
  30.         try {  
  31.             EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,  
  32.                     prev.userId, System.identityHashCode(prev),  
  33.                     prev.shortComponentName);  
  34.             mService.updateUsageStats(prev, false);  
  35.             //调度schedulePauseActivity方法  
  36.             prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,  
  37.                     userLeaving, prev.configChangeFlags, dontWait);  
  38.         } catch (Exception e) {  
  39.         }  
  40.     } else {  
  41.         mPausingActivity = null;  
  42.         mLastPausedActivity = null;  
  43.         mLastNoHistoryActivity = null;  
  44.     }  
  45.   
  46.     if (mPausingActivity != null) {  
  47.         if (!uiSleeping) {//在新Activity启动之前,暂停key dispatch事件。  
  48.             prev.pauseKeyDispatchingLocked();  
  49.         } else {  
  50.         }  
  51.   
  52.         if (dontWait) {//本例为false  
  53.             completePauseLocked(false);  
  54.             return false;  
  55.         } else {  
  56.             // 暂停超时处理  
  57.             Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);  
  58.             msg.obj = prev;  
  59.             prev.pauseTime = SystemClock.uptimeMillis();  
  60.             mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);  
  61.             return true;  
  62.         }  
  63.   
  64.     } else {  
  65.         // This activity failed to schedule the  
  66.         // pause, so just treat it as being paused now.  
  67.         if (!resuming) {  
  68.             mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null);  
  69.         }  
  70.         return false;  
  71.     }  
  72. }  

startPausingLocked方法主要功能:置空mResumedActivity,记录要暂停的Activity,调度Activity暂停方法的生命周期,暂停超时处理。下面分析schedulePauseActivity方法。

ActivityStack与当前要暂停的Activity处于不同的进程中,因此需要通过当前的Activity的ProcessRecord的IApplicationThread的代理类,通过代理对象访问主线程定义的ActivityThread,进而调用到ActivityThread暂停Activity。

/frameworks/base/core/java/android/app/ActivityThread.java

  1. public final void schedulePauseActivity(IBinder token, boolean finished,  
  2.                 boolean userLeaving, int configChanges, boolean dontReport) {  
  3.          //通过消息机制发送  
  4.          sendMessage(  
  5.                     finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,  
  6.                     token,  
  7.                     (userLeaving ? 1 : 0) | (dontReport ? 2 : 0),  
  8.                     configChanges);  
  9.         }  

找到handleMessage对应的case:PAUSE_ACTIVITY,调用了handlePauseActivity()方法。
  1. private void handlePauseActivity(IBinder token, boolean finished,  
  2.             boolean userLeaving, int configChanges, boolean dontReport) {  
  3.         ActivityClientRecord r = mActivities.get(token);//token代表Launcher信息  
  4.         if (r != null) {  
  5.             if (userLeaving) {  
  6.                 performUserLeavingActivity(r);//调用onUserInteraction和onUserLeaveHint方法。  
  7.             }  
  8.   
  9.             r.activity.mConfigChangeFlags |= configChanges;  
  10.             //调用暂停的生命周期  
  11.             performPauseActivity(token, finished, r.isPreHoneycomb());  
  12.   
  13.             // Make sure any pending writes are now committed.  
  14.             if (r.isPreHoneycomb()) {  
  15.                 QueuedWork.waitToFinish();  
  16.             }  
  17.   
  18.             // Tell the activity manager we have paused.  
  19.             if (!dontReport) {  
  20.                 try {//通知ActivityManagerService暂停完毕。  
  21.                     ActivityManagerNative.getDefault().activityPaused(token);  
  22.                 } catch (RemoteException ex) {  
  23.                 }  
  24.             }  
  25.             mSomeActivitiesChanged = true;  
  26.         }  
  27.     }  

  1. final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,  
  2.             boolean saveState) {  
  3.         if (r.paused) {  
  4.             if (r.activity.mFinished) {  
  5.                 return null;  
  6.             }  
  7.            ......  
  8.         }  
  9.         if (finished) {  
  10.             r.activity.mFinished = true;  
  11.         }  
  12.         try {  
  13.             // Next have the activity save its current state and managed dialogs...  
  14.             if (!r.activity.mFinished && saveState) {  
  15.                 callCallActivityOnSaveInstanceState(r);//调用Activity生命周期的onSaveInstanceState方法。  
  16.             }  
  17.             // Now we are idle.  
  18.             r.activity.mCalled = false;  
  19.             mInstrumentation.callActivityOnPause(r.activity);//调用Activity生命周期onPause方法。  
  20.             EventLog.writeEvent(LOG_ON_PAUSE_CALLED, UserHandle.myUserId(),  
  21.                     r.activity.getComponentName().getClassName());  
  22.             if (!r.activity.mCalled) {  
  23.                 throw new SuperNotCalledException(  
  24.                     "Activity " + r.intent.getComponent().toShortString() +  
  25.                     " did not call through to super.onPause()");  
  26.             }  
  27.   
  28.         } catch (SuperNotCalledException e) {  
  29.             throw e;  
  30.   
  31.         } catch (Exception e) {  
  32.             }  
  33.         }  
  34.         r.paused = true;  
  35.   
  36.         // Notify any outstanding on paused listeners  
  37.         ArrayList<OnActivityPausedListener> listeners;  
  38.         synchronized (mOnPauseListeners) {  
  39.             listeners = mOnPauseListeners.remove(r.activity);  
  40.         }  
  41.         int size = (listeners != null ? listeners.size() : 0);  
  42.         for (int i = 0; i < size; i++) {  
  43.             listeners.get(i).onPaused(r.activity);  
  44.         }  
  45.   
  46.         return !r.activity.mFinished && saveState ? r.state : null;  
  47.     }  

执行完onPause方法后,会通知ActivityManagerService,执行activityPausedactivityPaused方法。

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

  1. public final void activityPaused(IBinder token) {  
  2.     final long origId = Binder.clearCallingIdentity();  
  3.     synchronized(this) {  
  4.         ActivityStack stack = ActivityRecord.getStackLocked(token);  
  5.         if (stack != null) {  
  6.             stack.activityPausedLocked(token, false);//调用ActivityStack中activityPausedLocked()方法。  
  7.         }  
  8.     }  
  9.     Binder.restoreCallingIdentity(origId);  
  10. }  
/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
  1. final void activityPausedLocked(IBinder token, boolean timeout) {  
  2.         final ActivityRecord r = isInStackLocked(token);  
  3.         if (r != null) {//移除超时处理消息  
  4.             mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);  
  5.             if (mPausingActivity == r) {  
  6.                 //调用completePauseLocked()方法。  
  7.                 completePauseLocked(true);  
  8.             } else {  
  9.                 ......  
  10.             }  
  11.         }  
  12.     }  

activityPausedLocked主要就是移除之前的暂停超时处理消息,并且去掉用completePauseLocked方法,进行下一步操作。

  1. private void completePauseLocked(boolean resumeNext) {  
  2.         ActivityRecord prev = mPausingActivity;  
  3.         //prev本例为Launcher的ActivityRecord。  
  4.         if (prev != null) {  
  5.             prev.state = ActivityState.PAUSED;//状态改为PAUSED。  
  6.             if (prev.finishing) {  
  7.                 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);  
  8.             } else if (prev.app != null) {  
  9.                 if (prev.waitingVisible) {  
  10.                     prev.waitingVisible = false;  
  11.                     mStackSupervisor.mWaitingVisibleActivities.remove(prev);  
  12.                     if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(  
  13.                             TAG, "Complete pause, no longer waiting: " + prev);  
  14.                 }  
  15.                 if (prev.configDestroy) {  
  16.                     destroyActivityLocked(prev, true"pause-config");  
  17.                 } else if (!hasVisibleBehindActivity()) {  
  18.                     //加入到mStoppingActivities列表中  
  19.                     mStackSupervisor.mStoppingActivities.add(prev);  
  20.                     if (mStackSupervisor.mStoppingActivities.size() > 3 ||  
  21.                             prev.frontOfTask && mTaskHistory.size() <= 1) {  
  22.                         mStackSupervisor.scheduleIdleLocked();//由scheduleIdleLocked处理stop。  
  23.                     } else {  
  24.                         mStackSupervisor.checkReadyForSleepLocked();  
  25.                     }  
  26.                 }  
  27.             } else {  
  28.                 prev = null;  
  29.             }  
  30.             mPausingActivity = null;//以处理pause操作,置空。  
  31.         }  
  32.   
  33.         if (resumeNext) {//true  
  34.             final ActivityStack topStack = mStackSupervisor.getFocusedStack();  
  35.             if (!mService.isSleepingOrShuttingDown()) {//满足  
  36.                 mStackSupervisor.resumeTopActivitiesLocked(topStack, prev, null);//调用resumeTopActivitiesLocked,本例中prev仍是Launcher。  
  37.             } else {  
  38.                 mStackSupervisor.checkReadyForSleepLocked();  
  39.                 ActivityRecord top = topStack.topRunningActivityLocked(null);  
  40.                 if (top == null || (prev != null && top != prev)) {  
  41.                     mStackSupervisor.resumeTopActivitiesLocked(topStack, nullnull);  
  42.                 }  
  43.             }  
  44.         }  
  45.   
  46.         if (prev != null) {  
  47.             prev.resumeKeyDispatchingLocked();  
  48.             ......  
  49.     }  

completePauseLocked主要功能:将要暂停的Activity状态更改为PAUSED,将mPausingActivity置为空,调用resumeTopActivitiesLocked方法,resumeTopActivitiesLocked方法内部会调用到resumeTopActivityInnerLocked()方法。此时为第二次调用此方法。

/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

  1. final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {  
  2.         if (ActivityManagerService.DEBUG_LOCKSCREEN) mService.logLockScreen("");  
  3.         //这是第二次进入到这个方法里,省略第一次进来代码  
  4.         ......  
  5.   
  6.         if (mService.isSleeping() && mLastNoHistoryActivity != null &&  
  7.                 !mLastNoHistoryActivity.finishing) {  
  8.             requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED,  
  9.                     null"no-history"false);  
  10.             mLastNoHistoryActivity = null;  
  11.         }  
  12.   
  13.         if (prev != null && prev != next) {  
  14.             if (!prev.waitingVisible && next != null && !next.nowVisible) {  
  15.                 prev.waitingVisible = true;  
  16.                 mStackSupervisor.mWaitingVisibleActivities.add(prev);  
  17.                 if (DEBUG_SWITCH) Slog.v(  
  18.                         TAG, "Resuming top, waiting visible to hide: " + prev);  
  19.             } else {  
  20.                 if (prev.finishing) {  
  21.                     mWindowManager.setAppVisibility(prev.appToken, false);  
  22.                 } else {//满足else  
  23.                     ......//打印log  
  24.                 }  
  25.             }  
  26.         }  
  27.   
  28.         // Launching this app's activity, make sure the app is no longer  
  29.         // considered stopped.  
  30.         try {//确保应用非stop状态。  
  31.             AppGlobals.getPackageManager().setPackageStoppedState(  
  32.                     next.packageName, false, next.userId); /* TODO: Verify if correct userid */  
  33.         } catch (RemoteException e1) {  
  34.         } catch (IllegalArgumentException e) {  
  35.         }  
  36.   
  37.         // We are starting up the next activity, so tell the window manager  
  38.         // that the previous one will be hidden soon.  This way it can know  
  39.         // to ignore it when computing the desired screen orientation.  
  40.         boolean anim = true;  
  41.         if (prev != null) {  
  42.             if (prev.finishing) {  
  43.                 ......  
  44.             } else {  
  45.                 //准备切换动画。  
  46.                 if (mNoAnimActivities.contains(next)) {  
  47.                     anim = false;  
  48.                     mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);  
  49.                 } else {  
  50.                     mWindowManager.prepareAppTransition(prev.task == next.task  
  51.                             ? AppTransition.TRANSIT_ACTIVITY_OPEN  
  52.                             : next.mLaunchTaskBehind  
  53.                                     ? AppTransition.TRANSIT_TASK_OPEN_BEHIND  
  54.                                     : AppTransition.TRANSIT_TASK_OPEN, false);  
  55.                 }  
  56.             }  
  57.             }  
  58.         } else {  
  59.            ......  
  60.         }  
  61.   
  62.         Bundle resumeAnimOptions = null;  
  63.         if (anim) {  
  64.             ActivityOptions opts = next.getOptionsForTargetActivityLocked();  
  65.             if (opts != null) {  
  66.                 resumeAnimOptions = opts.toBundle();  
  67.             }  
  68.             next.applyOptionsLocked();  
  69.         } else {  
  70.             next.clearOptionsLocked();  
  71.         }  
  72.   
  73.         ActivityStack lastStack = mStackSupervisor.getLastStack();  
  74.         //next.app为要启动的activity的ProcessRecord,此为第一次启动,故为空  
  75.         if (next.app != null && next.app.thread != null) {  
  76.             ......  
  77.         } else {  
  78.             // Whoops, need to restart this activity!  
  79.             if (!next.hasBeenLaunched) {  
  80.                 next.hasBeenLaunched = true;  
  81.             } else {  
  82.                 if (SHOW_APP_STARTING_PREVIEW) {//切换动画  
  83.                     mWindowManager.setAppStartingWindow(  
  84.                             next.appToken, next.packageName, next.theme,  
  85.                             mService.compatibilityInfoForPackageLocked(  
  86.                                     next.info.applicationInfo),  
  87.                             next.nonLocalizedLabel,  
  88.                             next.labelRes, next.icon, next.logo, next.windowFlags,  
  89.                             nulltrue);  
  90.                 }  
  91.             }//调用startSpecificActivityLocked()方法。  
  92.             mStackSupervisor.startSpecificActivityLocked(next, truetrue);  
  93.         }  
  94.   
  95.         if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();  
  96.         return true;  
  97.     }  

resumeTopActivityInnerLocked第二次调用,跳过执行第一次进入时的代码。与第一次进入最大区别就是:此时mResumedActivity为null,即Launcher已经进入暂停状态。接下来看startSpecificActivityLocked()方法。

/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

  1. void startSpecificActivityLocked(ActivityRecord r,  
  2.             boolean andResume, boolean checkConfig) {  
  3.         // Is this activity's application already running?  
  4.         //第一次进入,此时ProcessRecord为null  
  5.         ProcessRecord app = mService.getProcessRecordLocked(r.processName,  
  6.                 r.info.applicationInfo.uid, true);  
  7.   
  8.         r.task.stack.setLaunchTime(r);  
  9.   
  10.         if (app != null && app.thread != null) {  
  11.             ......  
  12.         }  
  13.   
  14.         mService.startProcessLocked(r.processName, r.info.applicationInfo, true0,  
  15.                 "activity", r.intent.getComponent(), falsefalsetrue);  
  16.     }  

startSpecificActivityLocked方法,查询ProcessRecord,调用startProcessLocked()方法。

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

  1. final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,  
  2.             boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,  
  3.             boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,  
  4.             String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {  
  5.         long startTime = SystemClock.elapsedRealtime();  
  6.         ProcessRecord app;  
  7.         if (!isolated) {  
  8.             app = getProcessRecordLocked(processName, info.uid, keepIfLarge);  
  9.             checkTime(startTime, "startProcess: after getProcessRecord");  
  10.         } else {  
  11.             app = null;  
  12.         }  
  13.   
  14.         if (app != null && app.pid > 0) {  
  15.             ......//app为null  
  16.         }  
  17.   
  18.         String hostingNameStr = hostingName != null  
  19.                 ? hostingName.flattenToShortString() : null;  
  20.   
  21.         ......  
  22.   
  23.         if (app == null) {  
  24.             app = newProcessRecordLocked(info, processName, isolated, isolatedUid);//创建一个新的ProcessRecord。  
  25.             if (app == null) {  
  26.                 return null;  
  27.             }  
  28.             app.crashHandler = crashHandler;  
  29.             mProcessNames.put(processName, app.uid, app);//将ProcessRecord存入mProcessNames。  
  30.             if (isolated) {  
  31.                 mIsolatedProcesses.put(app.uid, app);  
  32.             }  
  33.         } else {  
  34.             // If this is a new package in the process, add the package to the list  
  35.             app.addPackage(info.packageName, info.versionCode, mProcessStats);  
  36.             checkTime(startTime, "startProcess: added package to existing proc");  
  37.         }  
  38.   
  39.         ......  
  40.         //调用startProcessLocked()。  
  41.         startProcessLocked(  
  42.                 app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);  
  43.         checkTime(startTime, "startProcess: done starting proc!");  
  44.         return (app.pid != 0) ? app : null;  
  45.     }  

startProcessLocked方法,首先查询是否有mProcessNames是否有该进程名对应的ProcessRecord信息,如果有直接复用,本例不存在。创建一个新的ProcessRecord,并存入mProcessNames。然后调用重载startProcessLocedd()方法。

 private final void startProcessLocked(ProcessRecord app, String hostingType,
            String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
        long startTime = SystemClock.elapsedRealtime();
        //app.pid未分配为0
        if (app.pid > 0 && app.pid != MY_PID) {
            ......
        }

        ......
        try {
            int uid = app.uid;

            int[] gids = null;
            int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
            if (!app.isolated) {
                int[] permGids = null;
                try {
                    final PackageManager pm = mContext.getPackageManager();
                    //通过packageManager获取应用程序组id
                    permGids = pm.getPackageGids(app.info.packageName);

                     ......
                } catch (PackageManager.NameNotFoundException e) {
                }

                /*
                 * Add shared application and profile GIDs so applications can share some
                 * resources like shared libraries and access user-wide resources
                 */
                if (permGids == null) {
                    gids = new int[2];
                } else {
                    gids = new int[permGids.length + 2];
                    System.arraycopy(permGids, 0, gids, 2, permGids.length);
                }
                gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
                gids[1] = UserHandle.getUserGid(UserHandle.getUserId(uid));
            }
           ......
            int debugFlags = 0;
            //debug相关
            if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
              ......
            }
            ......
            String instructionSet = null;
            if (app.info.primaryCpuAbi != null) {
                instructionSet = VMRuntime.getInstructionSet(app.info.primaryCpuAbi);
            }

            app.gids = gids;
            app.requiredAbi = requiredAbi;
            app.instructionSet = instructionSet;

            boolean isActivityProcess = (entryPoint == null);
            if (entryPoint == null) entryPoint = "android.app.ActivityThread";
            //创建进程,本质是fork出一个子进程,然后在子进程中调用android.app.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);
            ......
            app.setPid(startResult.pid);
            app.usingWrapper = startResult.usingWrapper;
            app.removed = false;
            app.killed = false;
            app.killedByAm = false;
            synchronized (mPidsSelfLocked) {
                //将应用程序信息存入mPidsSelfLocked中,以pid为键
                this.mPidsSelfLocked.put(startResult.pid, app);
                if (isActivityProcess) {//超时处理
                    Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
                    msg.obj = app;
                    mHandler.sendMessageDelayed(msg, startResult.usingWrapper
                            ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
                }
            }
        } catch (RuntimeException e) {
        }
    }

startProcessLocked方法中,查询当前应用程序的组id,然后调用Process.start方法创建应用程序进程,入口点为android.app.ActivityThread的main方法。创建完毕后,程序有了自己的pid,将对应的processRecord存入mPidsSelfLocked中。最后发送超时处理。下面进入应用程序启动阶段。

/frameworks/base/core/java/android/app/ActivityThread.java

public static void main(String[] args) {
        SamplingProfilerIntegration.start();

        ......

        Process.setArgV0("<pre-initialized>");//设置临时进程名

        Looper.prepareMainLooper();//准备looper消息循环
        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        Looper.loop();//loop循环

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

main方法中,首先设置临时的进程名,准备消息循环,调用了ActivityThread的attach方法。

private void attach(boolean system) {
        sCurrentActivityThread = this;
        mSystemThread = system;
        if (!system) {//system为fasle。
            ViewRootImpl.addFirstDrawHandler(new Runnable() {
                @Override
                public void run() {
                    ensureJitEnabled();
                }
            });
            android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                    UserHandle.myUserId());//设置DDMS中临时现实的进程名。
            RuntimeInit.setApplicationObject(mAppThread.asBinder());
            final IActivityManager mgr = ActivityManagerNative.getDefault();
            try {//获取ActivityManagerService的代理对象,调用attachApplication方法。
                mgr.attachApplication(mAppThread);
            } catch (RemoteException ex) {
                // Ignore
            }
           .......
            });
        } else {
           ......
        }
        ......
        });
    }

attach方法中,设置里DDMS中临时显示的名字,然后调用了ActivityManagerService中的attachApplication方法。跟踪attachApplication方法,又调用到了attachApplicationLocked()方法。

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

    private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid) {

        ProcessRecord app;
        //pid为Settings的pid,满足条件
        if (pid != MY_PID && pid >= 0) {
            synchronized (mPidsSelfLocked) {
                app = mPidsSelfLocked.get(pid);
            }
        } else {
            app = null;
        }

        if (app == null) {//不满足
           ......
        }

        // If this application record is still attached to a previous
        // process, clean it up now.
        if (app.thread != null) {
            handleAppDiedLocked(app, true, true);
        }

        final String processName = app.processName;
        try {
            AppDeathRecipient adr = new AppDeathRecipient(
                    app, pid, thread);//监控进程的退出
            thread.asBinder().linkToDeath(adr, 0);
            app.deathRecipient = adr;
        } catch (RemoteException e) {
        }
        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;
        app.killedByAm = false;

        mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);//移除attach之前创建的超时信息。

        boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
        //获取应用的ContentProvider
        List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null;

        try {
            ......//调用bindApplication()方法。
            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(app.isolated),
                    mCoreSettingsObserver.getCoreSettingsLocked());
            updateLruProcessLocked(app, false, null);
            app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
        } catch (Exception e) {
        }

        // Remove this record from the list of starting applications.
        mPersistentStartingProcesses.remove(app);
        mProcessesOnHold.remove(app);

        boolean badApp = false;
        boolean didSomething = false;

        // See if the top visible activity is waiting to run in this process...
        if (normalMode) {
            try {//调用attachApplicationLocked()方法,启动Activity
                if (mStackSupervisor.attachApplicationLocked(app)) {
                    didSomething = true;
                }
            } catch (Exception e) {
            }
        }
        ......

        if (!didSomething) {
            updateOomAdjLocked();
        }

        return true;
    }

attachApplicationLocked方法中,首先在mPidsSelfLocked中找到对应的ProcessRecord,然后去赋值。移除超时消息,调用bindApplication()方法,调用attachApplicationLocked()方法启动Activity。

/frameworks/base/core/java/android/app/ActivityThread.java

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) {
            ......
            setCoreSettings(coreSettings);//SettingsProvider数据库监听。
            IPackageManager pm = getPackageManager();
            android.content.pm.PackageInfo pi = null;
            try {
                pi = pm.getPackageInfo(appInfo.packageName, 0, UserHandle.myUserId());
            } catch (RemoteException e) {
            }
           ......

            AppBindData data = new AppBindData();
            data.processName = processName;
            data.appInfo = appInfo;
            ......
            sendMessage(H.BIND_APPLICATION, data);
        }
bindApplication()方法中,利用消息循环发送消息BIND_APPLICATION。调用到handleBindApplication()方法。

private void handleBindApplication(AppBindData data) {
        mBoundApplication = data;
        mConfiguration = new Configuration(data.config);
        mCompatConfiguration = new Configuration(data.config);
        ......

        // 设置进程名跟DDMS名称。
        Process.setArgV0(data.processName);
        android.ddm.DdmHandleAppName.setAppName(data.processName,
                                                UserHandle.myUserId());

        ......
        //创建对应的context。      
        final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
        if (!Process.isIsolated()) {
            final File cacheDir = appContext.getCacheDir();
            //临时文件
            if (cacheDir != null) {
                // Provide a usable directory for temporary files
                System.setProperty("java.io.tmpdir", cacheDir.getAbsolutePath());
    
                setupGraphicsSupport(data.info, cacheDir);
            } else {
            }
        }

        ......
        /**
         * Initialize the default http proxy in this process for the reasons we set the time zone.
         */
        IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
        if (b != null) {
            // In pre-boot mode (doing initial launch to collect password), not
            // all system is up.  This includes the connectivity service, so don't
            // crash if we can't get it.
            IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
            try {
                final ProxyInfo proxyInfo = service.getDefaultProxy();
                Proxy.setHttpProxySystemProperty(proxyInfo);
            } catch (RemoteException e) {}
        }

        if (data.instrumentationName != null) {
            ......
        } else {
            mInstrumentation = new Instrumentation();
        }

        // Allow disk access during application and provider setup. This could
        // block processing ordered broadcasts, but later processing would
        // probably end up doing the same disk access.
        final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
        try {
            //创建Application
            Application app = data.info.makeApplication(data.restrictedBackupMode, null);
            mInitialApplication = app;

            // don't bring up providers in restricted mode; they may depend on the
            // app's custom Application class
            if (!data.restrictedBackupMode) {
                List<ProviderInfo> providers = data.providers;
                if (providers != null) {//查询安装应用providers。
                    installContentProviders(app, providers);
                    mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
                }
            }

            // Do this after providers, since instrumentation tests generally start their
            // test thread at this point, and we don't want that racing.
            try {
                mInstrumentation.onCreate(data.instrumentationArgs);//调用Instrumentation的onCreate方法。
            }
            catch (Exception e) {
            }
            try {
                mInstrumentation.callApplicationOnCreate(app);//调用Application的onCreate方法。
                } catch (Exception e) {
                }
            }
        } finally {
            StrictMode.setThreadPolicy(savedPolicy);
        }
    }

handleBindApplication方法中,设置进程名,创建应用的context,创建对应的Application,查询安装ContentProvider,调用Instrumentation的onCreate方法。调用Application的onCreate方法。下面进入attachApplicationLocked方法。

/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
        final String processName = app.processName;
        boolean didSomething = false;
        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);
                if (hr != null) {
                    if (hr.app == null && app.uid == hr.info.applicationInfo.uid
                            && processName.equals(hr.processName)) {
                        try {
                            if (realStartActivityLocked(hr, app, true, true)) {//加载Activity。
                                didSomething = true;
                            }
                        } catch (RemoteException e) {
                        }
                    }
                }
            }
        }
        if (!didSomething) {
            ensureActivitiesVisibleLocked(null, 0);
        }
        return didSomething;
    }

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

        ......

        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);
        mService.updateOomAdjLocked();

        final ActivityStack stack = r.task.stack;
        try {
            if (app.thread == null) {
                throw new RemoteException();
            }
            List<ResultInfo> results = null;
            List<ReferrerIntent> newIntents = null;
            if (andResume) {
                results = r.results;
                newIntents = r.newIntents;
            }

            ......
            // 加载Activity生命周期
            app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                    System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
                    r.compat, r.launchedFromPackage, r.task.voiceInteractor, app.repProcState,
                    r.icicle, r.persistentState, results, newIntents, !andResume,
                    mService.isNextTransitionForward(), profilerInfo);

            if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
                if (app.processName.equals(app.info.packageName)) {
                    if (mService.mHeavyWeightProcess != null
                            && mService.mHeavyWeightProcess != app) {
                    }
                    mService.mHeavyWeightProcess = app;
                    Message msg = mService.mHandler.obtainMessage(
                            ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
                    msg.obj = r;
                    mService.mHandler.sendMessage(msg);
                }
            }

        } catch (RemoteException e) {
        }
        if (andResume) {
            stack.minimalResumeActivityLocked(r);//在调用完Activity生命周期后调用此方法,方法内会调用到completeResumeLocked()方法。
        } else {
            r.state = ActivityState.STOPPED;
            r.stopped = true;
        }
        ......

        return true;
    }


scheduleLaunchActivity调用了ActivityThread.java中的方法,通过消息机制最终调用到了handleLaunchActivity()方法。

/frameworks/base/core/java/android/app/ActivityThread.java

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();
        mSomeActivitiesChanged = true;

        ......
        //加载onCreate()等方法。

        Activity a = performLaunchActivity(r, customIntent);

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            Bundle oldState = r.state;
            //onResume方法。
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed);

            if (!r.activity.mFinished && r.startsNotResumed) {
                try {
                    r.activity.mCalled = false;
                    mInstrumentation.callActivityOnPause(r.activity);
                    if (r.isPreHoneycomb()) {
                        r.state = oldState;
                    }
                    if (!r.activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onPause()");
                    }

                } catch (SuperNotCalledException e) {
                    throw e;

                } catch (Exception e) {
                }
                r.paused = true;
            }
        } else {
            try {//出错直接finishActivity
                ActivityManagerNative.getDefault()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
            } catch (RemoteException ex) {
                // Ignore
            }
        }
    }

handleLaunchActivity方法主要是加载Activity的生命周期,onCreate,onStart,onResume等。

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

        ......

        if (r.activityInfo.targetActivity != null) {
            component = new ComponentName(r.activityInfo.packageName,
                    r.activityInfo.targetActivity);
        }

        Activity activity = null;
        try {
            java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
            //通过反射机制加载创建Activity
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            ......
            }
        } catch (Exception e) {
        }

        try {
            //创建Application
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (activity != null) {
                //创建context
                Context appContext = createBaseContextForActivity(r, activity);
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                //将各种信息附加到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);

                ......
                //调用onCreate()方法。
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                if (!activity.mCalled) {
                    throw new SuperNotCalledException(
                        "Activity " + r.intent.getComponent().toShortString() +
                        " did not call through to super.onCreate()");
                }
                r.activity = activity;
                r.stopped = true;
                if (!r.activity.mFinished) {
                    activity.performStart();//调用onStart()方法。
                    r.stopped = false;
                }
                if (!r.activity.mFinished) {
                    if (r.isPersistable()) {
                        if (r.state != null || r.persistentState != null) {//回调onRestoreInstanceState()方法。
                            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()) {//回调onPostCreate()方法。
                        mInstrumentation.callActivityOnPostCreate(activity, r.state,
                                r.persistentState);
                    } else {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state);
                    }
                    if (!activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onPostCreate()");
                    }
                }
            }
            r.paused = true;

            mActivities.put(r.token, r);

        } catch (SuperNotCalledException e) {
            throw e;

        } catch (Exception e) {
        }

        return activity;
    }

handleLaunchActivity主要是通过反射加载Activity对象,然后调用生命周期onCreate onStart 等方法。onResume()方法实在handleResumeActivity()这个方法中调用的。

final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();
        mSomeActivitiesChanged = true;

        // 加载onResume等生命周期方法。
        ActivityClientRecord r = performResumeActivity(token, clearHide);

        if (r != null) {
            final Activity a = r.activity;

            final int forwardBit = isForward ?
                    WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;

            // If the window hasn't yet been added to the window manager,
            // and this guy didn't finish itself or start another activity,
            // then go ahead and add the window.
            boolean willBeVisible = !a.mStartedActivity;
            ......

            // Tell the activity manager we have resumed.
            if (reallyResume) {
                try {//通知ActivityManagerService resume完毕
                    ActivityManagerNative.getDefault().activityResumed(token);
                } catch (RemoteException ex) {
                }
            }

        } else {
            // If an exception was thrown when trying to resume, then
            // just end this activity.
            try {
                ActivityManagerNative.getDefault()
                    .finishActivity(token, Activity.RESULT_CANCELED, null, false);
            } catch (RemoteException ex) {
            }
        }
    }

handleResumeActivity方法主要是调用了performResumedActivity()方法,加载onResume等生命周期方法,最后通知remsum完毕。

public final ActivityClientRecord performResumeActivity(IBinder token,
            boolean clearHide) {
        ActivityClientRecord r = mActivities.get(token);
        if (r != null && !r.activity.mFinished) {
            if (clearHide) {
                r.hideForNow = false;
                r.activity.mStartedActivity = false;
            }
            try {
                r.activity.mFragments.noteStateNotSaved();
                if (r.pendingIntents != null) {
                    deliverNewIntents(r, r.pendingIntents);//调用生命周期onNewIntent方法。
                    r.pendingIntents = null;
                }
                if (r.pendingResults != null) {
                    deliverResults(r, r.pendingResults);//调用生命周期onActivityResult方法。
                    r.pendingResults = null;
                }
                r.activity.performResume();//调用生命周期onResume方法。

                r.paused = false;
                r.stopped = false;
                r.state = null;
                r.persistentState = null;
            } catch (Exception e) {
            }
        }
        return r;
    }

   final void performResume() {
        performRestart();//如果当前Activity处于stop状态,依次调用Activity生命周期的onRestart和onStart方法。

        mFragments.execPendingActions();

        mLastNonConfigurationInstances = null;

        mCalled = false;
        // mResumed is set by the instrumentation
        mInstrumentation.callActivityOnResume(this);//调用Activity生命周期的onResume方法。
        ......
        mCalled = false;

        mFragments.dispatchResume();
        mFragments.execPendingActions();

        onPostResume();//调用onPostResume方法。
        if (!mCalled) {
            throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onPostResume()");
        }
    }

以上调用到了Activity生命周期的onResume方法,调用完成后会回到ActivityStackSupervisor.java中的realStartActivityLocked()方法中,继续执行,调用到stack.minimalResumeActivityLocked(r);


void minimalResumeActivityLocked(ActivityRecord r) {
        r.state = ActivityState.RESUMED;
        r.stopped = false;
        mResumedActivity = r;//将mResumeActivity赋值为要启动的Activity,本例为Settings。
        r.task.touchActiveTime();
        mService.addRecentTaskLocked(r.task);//加入到Recent列表
        completeResumeLocked(r);
        mStackSupervisor.checkReadyForSleepLocked();
        setLaunchTime(r);
    }

minimalResumeActivityLocked首先将状态置为RESUMED状态,将将mResumeActivity赋值为要启动的Activity,加入到Recent列表,然后点用到了completeResumeLocedk()方法。

private void completeResumeLocked(ActivityRecord next) {
        ......

        // schedule an idle timeout in case the app doesn't do it for us.
        //onResume方法调用后,会向应用程序主线程加入IDLE状态处理器,ActivityManagerService通过IDLE_TIMEOUT_MSG消息监控。
        mStackSupervisor.scheduleIdleTimeoutLocked(next);

        mStackSupervisor.reportResumedActivityLocked(next);

        next.resumeKeyDispatchingLocked();
        mNoAnimActivities.clear();
        ......
        }
    }


至此,启动一个Activity的详细过程就分析的差不多了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值