Android App启动流程分析

Android App启动流程分析

  • android 系统启动后 看到的桌面就是一个APP Activity为 Launcher 此时系统已经把我们要用的各种系统服务都跑起来了

    /**
    * Default launcher application.
    */
    public final class Launcher extends Activity
    implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
    View.OnTouchListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {

    setContentView(R.layout.launcher);
    }

    }

  • 在源码这个目录下 \android-6.0.0_r1\packages\apps\Launcher2\src\com\android\launcher2 找到图标的点击事件

    /**
     * Launches the intent referred by the clicked shortcut.
     *
     * @param v The view representing the clicked shortcut.
     */
    public void onClick(View v) {
        // Make sure that rogue clicks don't get through while allapps is launching, or after the
        // view has detached (it's possible for this to happen if the view is removed mid touch).
        if (v.getWindowToken() == null) {  //防止恶意点击
            return;
        }
    
        if (!mWorkspace.isFinishedSwitchingState()) {
            return;
        }
    
        Object tag = v.getTag();
        if (tag instanceof ShortcutInfo) { //应用图标
            // Open shortcut
            final Intent intent = ((ShortcutInfo) tag).intent;// 通过图标获取intent
            int[] pos = new int[2];
            v.getLocationOnScreen(pos);
            intent.setSourceBounds(new Rect(pos[0], pos[1],
                    pos[0] + v.getWidth(), pos[1] + v.getHeight()));
    
            boolean success = startActivitySafely(v, intent, tag); //我们顺着这个方法往下看
    
            if (success && v instanceof BubbleTextView) {
                mWaitingForResume = (BubbleTextView) v;
                mWaitingForResume.setStayPressed(true);
            }
        } else if (tag instanceof FolderInfo) {//如果快捷方式是文件夹之类的图标
            if (v instanceof FolderIcon) {
                FolderIcon fi = (FolderIcon) v;
                handleFolderClick(fi);
            }
        } else if (v == mAllAppsButton) {
            if (isAllAppsVisible()) {
                showWorkspace(true);
            } else {
                onClickAllAppsButton(v);
            }
        }
    }
    
  • startAcitivitySafely(…)方法如下

    boolean startActivitySafely(View v, Intent intent, Object tag) {
    boolean success = false;
    try {
        success = startActivity(v, intent, tag);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
        Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
    }
    return success;
    

    }

  • 再看startActivity(v, intent, tag);

    boolean startActivity(View v, Intent intent, Object tag) {
           intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    
           try {
               // Only launch using the new animation if the shortcut has not opted out (this is a
             //使用动画
               boolean useLaunchAnimation = (v != null) &&
                       !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
               UserHandle user = (UserHandle) intent.getParcelableExtra(ApplicationInfo.EXTRA_PROFILE);
               获取LAUNCHER_APPS_SERVICE服务
               LauncherApps launcherApps = (LauncherApps)
                       this.getSystemService(Context.LAUNCHER_APPS_SERVICE);
               if (useLaunchAnimation) {
                   ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
                           v.getMeasuredWidth(), v.getMeasuredHeight());
                //这一点和Android的多用户安全机制有关 
                //假如是单用户情境,就会相对简单了。因为此时只有一个用户,而该用户始终有权限直接访问自己的数据。
                   if (user == null || user.equals(android.os.Process.myUserHandle())) {
                       // Could be launching some bookkeeping activity
                       startActivity(intent, opts.toBundle());//A
                   } else {
                       launcherApps.startMainActivity(intent.getComponent(), user, 
                               intent.getSourceBounds(),
                               opts.toBundle());
                   }
               } else {
                   if (user == null || user.equals(android.os.Process.myUserHandle())) {
                       startActivity(intent);
                   } else {
                       launcherApps.startMainActivity(intent.getComponent(), user,
                               intent.getSourceBounds(), null);
                   }
               }
               return true;
           } catch (SecurityException e) {
               Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
               Log.e(TAG, "Launcher does not have the permission to launch " + intent +
                       ". Make sure to create a MAIN intent-filter for the corresponding activity " +
                       "or use the exported attribute for this activity. "
                       + "tag="+ tag + " intent=" + intent, e);
           }
           return false;
       }
    

-调用父类的Activity的方法 startActivity

    @Override
public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        startActivityForResult(intent, -1, options);
    } else {
        // Note we want to go through this call for compatibility with
        // applications that may have overridden the method.
        startActivityForResult(intent, -1);
    }
}

- 最终调到Activity 的startActivityForResult()三个参数的方法

    public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
        if (mParent == null) {
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            if (ar != null) {
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
            if (requestCode >= 0) {
                // If this start is requesting a result, we can avoid making
                // the activity visible until the result is received.  Setting
                // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
                // activity hidden during this time, to avoid flickering.
                // This can only be done when a result is requested because
                // that guarantees we will get information back when the
                // activity is finished, no matter what happens to it.
                mStartedActivity = true;
            }

            cancelInputsAndStartExitTransition(options);
            // TODO Consider clearing/flushing other event sources and events for child windows.
        } else {
            if (options != null) {
                mParent.startActivityFromChild(this, intent, requestCode, options);
            } else {
                // Note we want to go through this method for compatibility with
                // existing applications that may have overridden it.
                mParent.startActivityFromChild(this, intent, requestCode);
            }
        }
}

- 接下来调用了Instrumentation 的execStartActivity(…)方法 ,
- Instrumentation类位于F:\android-6.0.0_r1_系统源码\android-6.0.0_r1\frameworks\base\core\java\android\app

         public ActivityResult execStartActivity(
                Context who, IBinder contextThread, IBinder token, String target,
                Intent intent, int requestCode, Bundle options) {
                IApplicationThread whoThread = (IApplicationThread) contextThread;
                //The main thread of the Context from which the activity is being started. UI线程
                if (mActivityMonitors != null) {
                    synchronized (mSync) {
                        final int N = mActivityMonitors.size();
                        for (int i=0; i<N; i++) {
                            final ActivityMonitor am = mActivityMonitors.get(i);
                            if (am.match(who, null, intent)) {
                                am.mHits++;
                                if (am.isBlocking()) {
                                    return requestCode >= 0 ? am.getResult() : null;
                                }
                                break;
                            }
                        }
                    }
                }
                try {
                    intent.migrateExtraStreamToClipData();
                    intent.prepareToLeaveProcess();
                    //最主要的在这
                    int result = ActivityManagerNative.getDefault()
                        .startActivity(whoThread, who.getBasePackageName(), intent,
                                intent.resolveTypeIfNeeded(who.getContentResolver()),
                                token, target, requestCode, 0, null, options);
                    checkStartActivityResult(result, intent);
                } catch (RemoteException e) {
                    throw new RuntimeException("Failure from system", e);
                }
                return null;
}

- F:\android-6.0.0_r1_系统源码\android-6.0.0_r1\frameworks\base\core\java\android\app目录下的
-首先,调用ActivityManagerNative.getDefault()方法实际调用的是asInterface(IBinder obj)方法,
-也就意味着我们使用的其实是ActivityManagerProxy,而ActivityManagerProxy则是ActivityManagerService的代理,详见下面的代码:

    private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
    protected IActivityManager create() {
        IBinder b = ServiceManager.getService("activity");
        if (false) {
            Log.v("ActivityManager", "default service binder = " + b);
        }
        IActivityManager am = asInterface(b);
        if (false) {
            Log.v("ActivityManager", "default service = " + am);
        }
        return am;
    }
};

class ActivityManagerProxy implements IActivityManager
{
public ActivityManagerProxy(IBinder remote)
{
mRemote = remote;
}

    public IBinder asBinder()
    {
        return mRemote;
    }

    public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
                             String resolvedType, IBinder resultTo, String resultWho, int requestCode,
                                             int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
        // 创建两个Parcel对象,data用于传输启动Activity需要的数据,reply用于获取
        // 启动Activity操作执行后系统返回的响应
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IActivityManager.descriptor);
        // caller 就是Launcher提供的ApplicationThread(也就是前面提到的whoThread)
        data.writeStrongBinder(caller != null ? caller.asBinder() : null);
        // 记录启动新Activity的应用的包名,也就是Launcher的包名
        data.writeString(callingPackage);
        intent.writeToParcel(data, 0);
        data.writeString(resolvedType);
        // 将resultTo这个IBinder对象写入data,实际写入的就是前面的参数——IBinder token
        // 而这个token是什么,我们暂时不管
        data.writeStrongBinder(resultTo);
        data.writeString(resultWho);
        data.writeInt(requestCode);
        data.writeInt(startFlags);
        if (profilerInfo != null) {
            data.writeInt(1);
            profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
        } else {
            data.writeInt(0);
        }
        if (options != null) {
            data.writeInt(1);
            options.writeToParcel(data, 0);
        } else {
            data.writeInt(0);
        }
        mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
        reply.readException();
        int result = reply.readInt();
        reply.recycle();
        data.recycle();
        return result;
    }
    ……省略余下代码……
}
  • ActivityManagerProxy是AMS的代理,那么调用mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0)实际上就是通过Binder驱动建立Launcher所在的进程与系统进程的通信,并把我们写入data的数据通过Binder传递给AMS。这里是有binder通信,不懂的可以网上找找 非常多

        public final class ActivityManagerService extends ActivityManagerNative
    implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    
              @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) {
            enforceNotIsolatedCaller("startActivity");
            userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
                    false, ALLOW_FULL_ONLY, "startActivity", null);
            // TODO: Switch to user app stacks here.
            return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
                    resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                    profilerInfo, null, null, options, false, userId, null, null);
        }
    }
    

-走到这里 ActivityStackSupervisord的startActivityMayWait(..)方法
F:\android-6.0.0_r1_系统源码\android-6.0.0_r1\frameworks\base\services\core\java\com\android\server\am
这个方法中执行了启动Activity的一些其他逻辑判断,在经过判断逻辑之后调用startActivityLocked方法

ActivityStackSupervisor是AMS重要的实现,是Android系统Activity的栈管理器,管理着两个重要的Activity栈,实际上Android 早期不是这样的,4.4以前只有一个mHistory 来管理所有的 activity;目前的栈架构是Android4.4之后采用的,当然这个是Android系统默认的栈架构,高通和MTK等芯片产商为了增加新feature有可能在这里新增一个或者多个栈,比如Multi-window的实现,就有可能需要增加栈来管理更复杂的Activity。**

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, boolean ignoreTargetSecurity, int userId,
        IActivityContainer iContainer, TaskRecord inTask) {
    ...

    // Collect information about the target of the Intent.
    //收集要开启的Activity的信息 
    ActivityInfo aInfo =
            resolveActivity(intent, resolvedType, startFlags, profilerInfo, userId);

    ActivityContainer container = (ActivityContainer)iContainer;
    synchronized (mService) {
    //传过来的iContainer = null 走下面
        if (container != null && container.mParentActivity != null &&
                container.mParentActivity.state != RESUMED) {
            // Cannot start a child activity if the parent is not resumed.
            return ActivityManager.START_CANCELED;
        }
       ...
        int res = startActivityLocked(caller, intent, resolvedType, aInfo,
                voiceSession, voiceInteractor, resultTo, resultWho,
                requestCode, callingPid, callingUid, callingPackage,
                realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity,
                componentSpecified, null, container, inTask);

      ...
        return res;
    }
}

-* 这个方法中主要构造了ActivityManagerService端的Activity对象–>ActivityRecord,并根据Activity的启动模式执行了相关逻辑。然后调用了startActivityUncheckedLocked方法:*

 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 ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[]   outActivity,
                   ActivityContainer container, TaskRecord inTask) {
               int err = ActivityManager.START_SUCCESS;
               ...
            ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
                       intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,
                       requestCode, componentSpecified, voiceSession != null, this, container, options);
            ...
            err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
            startFlags, true, options, inTask);
            ...
            return err;
            }

-执行了不同启动模式不同栈的处理,并最后调用了startActivityLocked的重载方法:

    final int startActivityUncheckedLocked(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags,
        boolean doResume, Bundle options, TaskRecord inTask) {
        ...
        targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
        ...
        }

-startActivityLocked方法主要执行初始化了windowManager服务,然后调用resumeTopActivitiesLocked方法:

     final void startActivityLocked(ActivityRecord r, boolean newTask,
        boolean doResume, boolean keepCurTransition, Bundle options) {
        ...
        if (doResume) {
        mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
}

-你好

    boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
                Bundle targetOptions) {
           ...

            for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
                final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
                for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
                    final ActivityStack stack = stacks.get(stackNdx);
                    if (stack == targetStack) {
                        // Already started above.
                        continue;
                    }
                    if (isFrontStack(stack)) {
                        stack.resumeTopActivityLocked(null);
                    }
                }
            }
            return result;
        }

调用resumeTopActivityLocked(…)

 final boolean resumeTopActivityLocked(ActivityRecord prev) {
        return resumeTopActivityLocked(prev, null);
    }
 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
       if (mStackSupervisor.inResumeTopActivity) {
           // Don't even start recursing.
           return false;
       }

       boolean result = false;
       try {
           // Protect against recursion.
           mStackSupervisor.inResumeTopActivity = true;
           if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
               mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
               mService.updateSleepIfNeededLocked();
           }
           result = resumeTopActivityInnerLocked(prev, options);
       } finally {
           mStackSupervisor.inResumeTopActivity = false;
       }
       return result;
   }

-下面这个方法代码有点长resumeTopActivityInnerLocked()

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
     if (!mService.mBooting && !mService.mBooted) {
        // AMS未初始化
        return false;
    }    
    ActivityRecord parent = mActivityContainer.mParentActivity;
    if ((parent != null && parent.state != ActivityState.RESUMED) ||
            !mActivityContainer.isAttachedLocked()) {
        //如果parent没有resume,直接返回
        return false;
    }
    cancelInitializingActivities();

    // 寻找第一个栈顶没有结束的Activity
   // Find the first activity that is not finishing.
    final ActivityRecord next = topRunningActivityLocked(null);

    //用户离开标志
    final boolean userLeaving = mStackSupervisor.mUserLeaving;
    mStackSupervisor.mUserLeaving = false;

    final TaskRecord prevTask = prev != null ? prev.task : null;

    //如果next为null,启动Launcher界面
    if (next == null) {
        // There are no more activities!
        final String reason = "noMoreActivities";
        if (!mFullscreen) {
            //如果当前栈没有遮盖整个屏幕,将焦点移到下一个可见的任务栈的正在运行的Activity
            final ActivityStack stack = getNextVisibleStackLocked();
            if (adjustFocusToNextVisibleStackLocked(stack, reason)) {
                return mStackSupervisor.resumeTopActivitiesLocked(stack, prev, null);
            }
        }
        // Let's just start up the Launcher...
        ActivityOptions.abort(options);
        if (DEBUG_STATES) Slog.d(TAG_STATES,
                "resumeTopActivityLocked: No more activities go home");
        if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
        // Only resume home if on home display
        final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
                HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
        return isOnHomeDisplay() &&
                mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, reason);
    }
    next.delayedResume = false;


   /** mResumedActivity--系统当前激活的Activity组件
    *   mLastPausedActivity--上一次被中止的Activity组件
    *   mPausingActivity--正在被中止的Activity组件
    **/

    //如果栈顶的Activity已经是resumed,不做任何事
    if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
                mStackSupervisor.allResumedActivitiesComplete()) {
        mWindowManager.executeAppTransition();
        mNoAnimActivities.clear();
        ActivityOptions.abort(options);
        if (DEBUG_STATES) Slog.d(TAG_STATES,
                "resumeTopActivityLocked: Top activity resumed " + next);
        if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
        return false;
    }
    //判断下个任务,上一个任务,决定是否调转到home
    final TaskRecord nextTask = next.task;
    if (prevTask != null && prevTask.stack == this &&
            prevTask.isOverHomeStack() && prev.finishing && prev.frontOfTask) {
        if (DEBUG_STACK)  mStackSupervisor.validateTopActivitiesLocked();
        if (prevTask == nextTask) {
            prevTask.setFrontOfTask();
        } else if (prevTask != topTask()) {
            final int taskNdx = mTaskHistory.indexOf(prevTask) + 1;
            mTaskHistory.get(taskNdx).setTaskToReturnTo(HOME_ACTIVITY_TYPE);
        } else if (!isOnHomeDisplay()) {
            return false;
        } else if (!isHomeStack()){
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Launching home next");
            final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
                    HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
            return isOnHomeDisplay() &&
                    mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, "prevFinished");
        }
    }
    //如果系统要进入关机或者休眠状态,并且下一个Activity是上一次已经终止的Activity,直接返回
    if (mService.isSleepingOrShuttingDown()
            && mLastPausedActivity == next
            && mStackSupervisor.allPausedActivitiesComplete()) {
        mWindowManager.executeAppTransition();
        mNoAnimActivities.clear();
        ActivityOptions.abort(options);
        if (DEBUG_STATES) Slog.d(TAG_STATES,
                "resumeTopActivityLocked: Going to sleep and all paused");
        if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
        return false;
    } 
    //如果不确定是哪个用户打开的Activity,直接返回
    if (mService.mStartedUsers.get(next.userId) == null) {
        Slog.w(TAG, "Skipping resume of top activity " + next
                + ": user " + next.userId + " is stopped");
        if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
        return false;
    }
    //如果当前启动的Activity正在准备stop,终止这个操作
    mStackSupervisor.mStoppingActivities.remove(next);
    mStackSupervisor.mGoingToSleepActivities.remove(next);
    next.sleeping = false;
    mStackSupervisor.mWaitingVisibleActivities.remove(next);
    ......
    //如果有正在pause的Activity,直接返回
    if (!mStackSupervisor.allPausedActivitiesComplete()) {
        if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
                "resumeTopActivityLocked: Skip resume: some activity pausing.");
        if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
        return false;
    }
    ......
    boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
    boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
    //表示当前的Activity正在运行
    if (mResumedActivity != null) {
        if (DEBUG_STATES) Slog.d(TAG_STATES,
                "resumeTopActivityLocked: Pausing " + mResumedActivity);
        //*********************让当前运行的Activity进入pause状态*********************
        pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
        //先分析如何走当前Activity的OnPause()方法
    }
    if (pausing) {
        if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG_STATES,
                "resumeTopActivityLocked: Skip resume: need to start pausing");
        //将即将启动的Activity放到LRU list,因为直接杀死的话会造成资源浪费
        if (next.app != null && next.app.thread != null) {
            mService.updateLruProcessLocked(next.app, true, null);
        }
        if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
        return true;
    } 
    // If the most recent activity was noHistory but was only stopped rather
    // than stopped+finished because the device went to sleep, we need to make
    // sure to finish it as we're making a new activity topmost.
    if (mService.isSleeping() && mLastNoHistoryActivity != null &&
            !mLastNoHistoryActivity.finishing) {
        if (DEBUG_STATES) Slog.d(TAG_STATES,
                "no-history finish of " + mLastNoHistoryActivity + " on new resume");
        requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED,
                null, "resume-no-history", false);
        mLastNoHistoryActivity = null;
    }
    //
    if (prev != null && prev != next) {
        if (!mStackSupervisor.mWaitingVisibleActivities.contains(prev)
                && next != null && !next.nowVisible) {
            mStackSupervisor.mWaitingVisibleActivities.add(prev);
            if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
                    "Resuming top, waiting visible to hide: " + prev);
        } else {
            //隐藏上一个Activity的界面,必须在finish状态,不然报错
            if (prev.finishing) {
                mWindowManager.setAppVisibility(prev.appToken, false);
                if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
                        "Not waiting for visible to hide: " + prev + ", waitingVisible="
                        + mStackSupervisor.mWaitingVisibleActivities.contains(prev)
                        + ", nowVisible=" + next.nowVisible);
            } else {
                if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
                        "Previous already visible but still waiting to hide: " + prev
                        + ", waitingVisible="
                        + mStackSupervisor.mWaitingVisibleActivities.contains(prev)
                        + ", nowVisible=" + next.nowVisible);
            }
        }
    }
    //加载Activity,核实用户id是否正确
    try {
        AppGlobals.getPackageManager().setPackageStoppedState(
                next.packageName, false, next.userId); 
    } catch (RemoteException e1) {
    } catch (IllegalArgumentException e) {
        Slog.w(TAG, "Failed trying to unstop package "
                + next.packageName + ": " + e);
    }
    //打开动画,并且通知WindowManager关闭上一个Activity
    boolean anim = true;
    if (prev != null) {
        if (prev.finishing) {
            if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
                    "Prepare close transition: prev=" + prev);
            if (mNoAnimActivities.contains(prev)) {
                anim = false;
                mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
            } else {
                mWindowManager.prepareAppTransition(prev.task == next.task
                        ? AppTransition.TRANSIT_ACTIVITY_CLOSE
                        : AppTransition.TRANSIT_TASK_CLOSE, false);
            }
            mWindowManager.setAppWillBeHidden(prev.appToken);
            mWindowManager.setAppVisibility(prev.appToken, false);
        } else {
            if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
                    "Prepare open transition: prev=" + prev);
            if (mNoAnimActivities.contains(next)) {
                anim = false;
                mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
            } else {
                mWindowManager.prepareAppTransition(prev.task == next.task
                        ? AppTransition.TRANSIT_ACTIVITY_OPEN
                        : next.mLaunchTaskBehind
                                ? AppTransition.TRANSIT_TASK_OPEN_BEHIND
                                : AppTransition.TRANSIT_TASK_OPEN, false);
            }
        }
        if (false) {
            mWindowManager.setAppWillBeHidden(prev.appToken);
            mWindowManager.setAppVisibility(prev.appToken, false);
        }
    } else {
        if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare open transition: no previous");
        if (mNoAnimActivities.contains(next)) {
            anim = false;
            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
        } else {
            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_ACTIVITY_OPEN, false);
        }
    } 
    ......
    ActivityStack lastStack = mStackSupervisor.getLastStack();
    //如果Activity所在的进程已经存在
    if (next.app != null && next.app.thread != null) {
        if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Resume running: " + next);

        // 显示Activity
        mWindowManager.setAppVisibility(next.appToken, true);

        // 开始计时
        next.startLaunchTickingLocked();

        ActivityRecord lastResumedActivity =
                lastStack == null ? null :lastStack.mResumedActivity;
        ActivityState lastState = next.state;

        mService.updateCpuStats();   

        //设置Activity状态
        if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to RESUMED: " + next + " (in existing)");
        next.state = ActivityState.RESUMED;
        mResumedActivity = next;
        next.task.touchActiveTime();
        mRecentTasks.addLocked(next.task);
        mService.updateLruProcessLocked(next.app, true, null);
        updateLRUListLocked(next);
        mService.updateOomAdjLocked();
        //根据Activity设置屏幕方向
        boolean notUpdated = true;
        if (mStackSupervisor.isFrontStack(this)) {
            Configuration config = mWindowManager.updateOrientationFromAppTokens(
                    mService.mConfiguration,
                    next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
            if (config != null) {
                next.frozenBeforeDestroy = true;
            }
            notUpdated = !mService.updateConfigurationLocked(config, next, false, false);
        }
        //确保Activity保持在栈顶
        if (notUpdated) {
            ActivityRecord nextNext = topRunningActivityLocked(null);
            if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG_STATES,
                    "Activity config changed during resume: " + next
                    + ", new next: " + nextNext);
            if (nextNext != next) {
                // Do over!
                mStackSupervisor.scheduleResumeTopActivities();
            }
            if (mStackSupervisor.reportResumedActivityLocked(next)) {
                mNoAnimActivities.clear();
                if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
                return true;
            }
            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
            return false;
        }
        try {
            ......
            if (next.newIntents != null) {
                next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
            }

            ......
            //是否睡眠
            next.sleeping = false;
            //兼容模式提示框
            mService.showAskCompatModeDialogLocked(next);
            //清理UI资源
            next.app.pendingUiClean = true;
            //设置处理状态
            next.app.forceProcessStateUpTo(mService.mTopProcessState);
            //清理最近的选择
            next.clearOptionsLocked();
            //*********************resume目标Activity*********************
            next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState,
                    mService.isNextTransitionForward(), resumeAnimOptions);

            mStackSupervisor.checkReadyForSleepLocked();
            } catch (Exception e) {
                ......
        }
        //设置可见
        try {
            next.visible = true;
            completeResumeLocked(next);
        } catch (Exception e) {
            //出现意外,放弃操作,尝试下一个Activity
            Slog.w(TAG, "Exception thrown during resume of " + next, e);
            requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
                    "resume-exception", true);
            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
            return true;
        }
        next.stopped = false;

    }else {//Activity所在的进程不存在的情况
        // 重启Activity
        if (!next.hasBeenLaunched) {
            next.hasBeenLaunched = true;
        } else {
            if (SHOW_APP_STARTING_PREVIEW) {
                mWindowManager.setAppStartingWindow(
                        next.appToken, next.packageName, next.theme,
                        mService.compatibilityInfoForPackageLocked(
                                next.info.applicationInfo),
                        next.nonLocalizedLabel,
                        next.labelRes, next.icon, next.logo, next.windowFlags,
                        null, true);
            }
            if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Restarting: " + next);
        }
        if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);
        //*********************启动Activity*********************
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
    }

    if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
    return true;

   }

-首先让现在正在运行的Activity(从桌面点击就是Laucher或者第三方跳转前的Activity)调用startPausingLocked进入pause状态
调用链
ActivityStack.startPausingLocked()
IApplicationThread.schudulePauseActivity()
ActivityThread.sendMessage()
ActivityThread.H.sendMessage();
ActivityThread.H.handleMessage()
ActivityThread.handlePauseActivity()
ActivityThread.performPauseActivity()
Activity.performPause()
Activity.onPause()

    final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming,
        boolean dontWait) {
        ...
        prev.state = ActivityState.PAUSING;
        ...
         prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
                    userLeaving, prev.configChangeFlags, dontWait);
        ...
        }

- thread是一个IApplicationThread类型的对象,而在ActivityThread中也定义了一个ApplicationThread的类,其继承了IApplicationThread,并且都是Binder对象,不难看出这里的IAppcation是一个Binder的client端而ActivityThread中的ApplicationThread是一个Binder对象的server端,所以通过这里的thread.schedulePauseActivity实际上调用的就是ApplicationThread的schedulePauseActivity方法。

public interface IApplicationThread extends IInterface {
        void schedulePauseActivity(IBinder token, boolean finished, boolean userLeaving,
}

ActivityThread 的内部类 ApplicationThread方法schedulePauseActivity()

    public final class ActivityThread {
        final H mH = new H();       
        ...
        private class ApplicationThread extends ApplicationThreadNative {
            //第一步
              public final void schedulePauseActivity(IBinder token, boolean finished,
                        boolean userLeaving, int configChanges) {
                    queueOrSendMessage(
                            finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
                            token,
                            (userLeaving ? 1 : 0),
                            configChanges);
                }
                ...
         }
         //第二步
         private void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
                    synchronized (this) {
                        if (DEBUG_MESSAGES) Slog.v(
                            TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
                            + ": " + arg1 + " / " + obj);
                        Message msg = Message.obtain();
                        msg.what = what;
                        msg.obj = obj;
                        msg.arg1 = arg1;
                        msg.arg2 = arg2;
                        mH.sendMessage(msg);
                    }
         }
         private class H extends Handler {
                  //第三步
                  public void handleMessage(Message msg) {

                    switch (msg.what) { ...
                      case PAUSE_ACTIVITY:
                            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
                            handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
                            maybeSnapshot();
                            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                            break;
                             ...
                  }
         }
                 //④
                private void handlePauseActivity(IBinder token, boolean finished,
                        boolean userLeaving, int configChanges) {
                    ActivityClientRecord r = mActivities.get(token);
                          ...
                        performPauseActivity(token, finished, r.isPreHoneycomb());
                            try {
                                    ActivityManagerNative.getDefault().activityPaused(token);
                            } catch (RemoteException ex) {
                            }
                         ...
                }
                //⑤
                  final Bundle performPauseActivity(IBinder token, boolean finished,
                   boolean saveState) {
                               ActivityClientRecord r = mActivities.get(token);
                               return r != null ? performPauseActivity(r, finished, saveState) : null;
                }
    }

然后调用

final Bundle performPauseActivity(IBinder token, boolean finished,
                    boolean saveState) {
                ActivityClientRecord r = mActivities.get(token);
                return r != null ? performPauseActivity(r, finished, saveState) : null;
}

final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
        boolean saveState) {
    ...
    mInstrumentation.callActivityOnPause(r.activity);
    ...

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

- Instrumentation类的callActivityOnPause()

public void callActivityOnPause(Activity activity) {
    activity.performPause();
}
  • Activity performPause()

         final void performPause() {
                        mDoReportFullyDrawn = false;
                        mFragments.dispatchPause();
                        mCalled = false;
                        onPause();//当前Activity的OnPause生命周期方法
                        mResumed = false;
                        if (!mCalled && getApplicationInfo().targetSdkVersion
                                >= android.os.Build.VERSION_CODES.GINGERBREAD) {
                            throw new SuperNotCalledException(
                                    "Activity " + mComponent.toShortString() +
                                    " did not call through to super.onPause()");
                        }
                        mResumed = false;
        }
    
  • 也就是说我们在启动一个Activity的时候最先被执行的是栈顶的Activity的onPause方法。记住这点吧,面试的时候经常会问到类似的问题。然后回到我们的handlePauseActivity方法,在该方法的最后面执行了ActivityManagerNative.getDefault().activityPaused(token);方法,这是应用进程告诉服务进程,栈顶Activity已经执行完成onPause方法了,通过前面我们的分析,我们知道这句话最终会被ActivityManagerService的activityPaused方法执行。

  • 然后回到我们的handlePauseActivity方法,在该方法的最后面执行了
    ActivityManagerNative.getDefault().activityPaused(token);方法,这是应用进程告诉服务进程,栈顶Activity已经执行完成onPause方法了,通过前面我们的分析,我们知道这句话最终会被ActivityManagerService的activityPaused方法执行。

    public final void activityPaused(IBinder token) {
        final long origId = Binder.clearCallingIdentity();
        synchronized(this) {
            ActivityStack stack = ActivityRecord.getStackLocked(token);
            if (stack != null) {
                stack.activityPausedLocked(token, false);//①
            }
        }
        Binder.restoreCallingIdentity(origId);
    }
             @Override
        public final void activityPaused(IBinder token) {
            final long origId = Binder.clearCallingIdentity();
            synchronized(this) {
                ActivityStack stack = ActivityRecord.getStackLocked(token);
                if (stack != null) {
                    stack.activityPausedLocked(token, false);//②
                }
            }
            Binder.restoreCallingIdentity(origId);
        }
    

    再调用ActivityStack 的 activityPausedLocked()方法

      final void activityPausedLocked(IBinder token, boolean timeout) {
    if (DEBUG_PAUSE) Slog.v(TAG_PAUSE,
        "Activity paused: token=" + token + ", timeout=" + timeout);
    
    final ActivityRecord r = isInStackLocked(token);
    if (r != null) {
        mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
        if (mPausingActivity == r) {
            if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSED: " + r
                    + (timeout ? " (due to timeout)" : " (pause complete)"));
            completePauseLocked(true);
        } else {
            EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
                    r.userId, System.identityHashCode(r), r.shortComponentName,
                    mPausingActivity != null
                        ? mPausingActivity.shortComponentName : "(none)");
            if (r.finishing && r.state == ActivityState.PAUSING) {
                if (DEBUG_PAUSE) Slog.v(TAG,
                        "Executing finish of failed to pause activity: " + r);
                finishCurrentActivityLocked(r, FINISH_AFTER_VISIBLE, false);
            }
        }
    }
    

    }
    然后执行了completePauseLocked方法:

    private void completePauseLocked(boolean resumeNext) {
      ...
    
    if (resumeNext) {
        final ActivityStack topStack = mStackSupervisor.getFocusedStack();
        if (!mService.isSleepingOrShuttingDown()) {
            mStackSupervisor.resumeTopActivitiesLocked(topStack, prev, null);
        } else {
            mStackSupervisor.checkReadyForSleepLocked();
            ActivityRecord top = topStack.topRunningActivityLocked(null);
            if (top == null || (prev != null && top != prev)) {
                // If there are no more activities available to run,
                // do resume anyway to start something.  Also if the top
                // activity on the stack is not the just paused activity,
                // we need to go ahead and resume it to ensure we complete
                // an in-flight app switch.
                mStackSupervisor.resumeTopActivitiesLocked(topStack, null, null);
            }
        }
    }
    ...
    

    }
    调用链
    resumeTopActivitiesLocked –>
    ActivityStack.resumeTopActivityLocked() –>
    resumeTopActivityInnerLocked –>
    startSpecificActivityLocked

    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);
    
            r.task.stack.setLaunchTime(r);
    
            if (app != null && app.thread != null) {//已经启动好进程
                try {
                    if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                            || !"android".equals(r.info.packageName)) {
                        // Don't add this if it is a platform component that is marked
                        // to run in multiple processes, because this is actually
                        // part of the framework so doesn't make sense to track as a
                        // separate apk in the process.
                        app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
                                mService.mProcessStats);
                    }
                    realStartActivityLocked(r, app, andResume, checkConfig);
                    return;
                } catch (RemoteException e) {
                    Slog.w(TAG, "Exception when starting activity "
                            + r.intent.getComponent().flattenToShortString(), e);
                }
    
                // If a dead object exception was thrown -- fall through to
                // restart the application.
            }
            //未启动进程
            mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                    "activity", r.intent.getComponent(), false, false, true);
    }   
    

    判断一下需要启动的Activity所需要的应用进程是否已经启动,若启动的话,则直接调用realStartAtivityLocked方法,否则调用startProcessLocked方法,用于启动应用进程。

这里主要是实现了对栈顶Activity执行onPause方法,而这个方法首先判断需要启动的Activity所属的进程是否已经启动,若已经启动则直接调用启动Activity的方法,否则将先启动Activity的应用进程,然后在启动该Activity。

启动Activity所属的应用进程

ActivityManagerService.startProcessLocked()
Process.start()
ActivityThread.main()
ActivityThread.attach()
ActivityManagerNative.getDefault().attachApplication()
ActivityManagerService.attachApplication()

final ProcessRecord startProcessLocked(String processName,
        ApplicationInfo info, boolean knownToBeDead, int intentFlags,
        String hostingType, ComponentName hostingName, boolean allowWhileBooting,
        boolean isolated, boolean keepIfLarge) {
    return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
            hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
            null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
            null /* crashHandler */);
}


 private final void startProcessLocked(ProcessRecord app, String hostingType,
        String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
       ...
         checkTime(startTime, "startProcess: asking zygote to start proc");
        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);
        checkTime(startTime, "startProcess: returned from zygote!");
       ...
    }

F:\android-6.0.0_r1_系统源码\android-6.0.0_r1\frameworks\base\core\java\android\os\Process.start(…)

 public static final ProcessStartResult start(final String processClass,
                              final String niceName,
                              int uid, int gid, int[] gids,
                              int debugFlags, int mountExternal,
                              int targetSdkVersion,
                              String seInfo,
                              String abi,
                              String instructionSet,
                              String appDataDir,
                              String[] zygoteArgs) {
    try {
        return startViaZygote(processClass, niceName, uid, gid, gids,
                debugFlags, mountExternal, targetSdkVersion, seInfo,
                abi, instructionSet, appDataDir, zygoteArgs);
    } catch (ZygoteStartFailedEx ex) {
        Log.e(LOG_TAG,
                "Starting VM process through Zygote failed");
        throw new RuntimeException(
                "Starting VM process through Zygote failed", ex);
    }
}

然后调用了startViaZygote方法:

  private static ProcessStartResult startViaZygote(final String processClass,
                              final String niceName,
                              final int uid, final int gid,
                              final int[] gids,
                              int debugFlags, int mountExternal,
                              int targetSdkVersion,
                              String seInfo,
                              String abi,
                              String instructionSet,
                              String appDataDir,
                              String[] extraArgs)
                              throws ZygoteStartFailedEx {
    synchronized(Process.class) {
        ArrayList<String> argsForZygote = new ArrayList<String>();

        // --runtime-args, --setuid=, --setgid=,
        // and --setgroups= must go first
       ...
        return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
    }
}


 private static ProcessStartResult zygoteSendArgsAndGetResult(
        ZygoteState zygoteState, ArrayList<String> args)
        throws ZygoteStartFailedEx {
    try {
        /**
         * See com.android.internal.os.ZygoteInit.readArgumentList()
         * Presently the wire format to the zygote process is:
         * a) a count of arguments (argc, in essence)
         * b) a number of newline-separated argument strings equal to count
         *
         * After the zygote process reads these it will write the pid of
         * the child or -1 on failure, followed by boolean to
         * indicate whether a wrapper process was used.
         */
        final BufferedWriter writer = zygoteState.writer;
        final DataInputStream inputStream = zygoteState.inputStream;

        writer.write(Integer.toString(args.size()));
        writer.newLine();

        int sz = args.size();
        for (int i = 0; i < sz; i++) {
            String arg = args.get(i);
            if (arg.indexOf('\n') >= 0) {
                throw new ZygoteStartFailedEx(
                        "embedded newlines not allowed");
            }
            writer.write(arg);
            writer.newLine();
        }

        writer.flush();

        // Should there be a timeout on this?
        ProcessStartResult result = new ProcessStartResult();
        result.pid = inputStream.readInt();
        if (result.pid < 0) {
            throw new ZygoteStartFailedEx("fork() failed");
        }
        result.usingWrapper = inputStream.readBoolean();
        return result;
    } catch (IOException ex) {
        zygoteState.close();
        throw new ZygoteStartFailedEx(ex);
    }
}
以发现其最终调用了Zygote并通过socket通信的方式让Zygote进程fork除了一个新的进程,并根据我们刚刚传递的”android.app.ActivityThread”字符串,反射出该对象并执行ActivityThread的main方法。这样我们所要启动的应用进程这时候其实已经启动了,但是还没有执行相应的初始化操作。
为什么我们平时都将ActivityThread称之为ui线程或者是主线程,这里可以看出,应用进程被创建之后首先执行的是ActivityThread的main方法,所以我们将ActivityThread成为主线程。
public static void main(String[] args) {
    SamplingProfilerIntegration.start();

    // CloseGuard defaults to true and can be quite spammy.  We
    // disable it here, but selectively enable it later (via
    // StrictMode) on debug builds, but using DropBox, not logs.
    CloseGuard.setEnabled(false);

    Environment.initForCurrentUser();

    // Set the reporter for event logging in libcore
    EventLogger.setReporter(new EventLoggingReporter());

    Process.setArgV0("<pre-initialized>");

    Looper.prepareMainLooper();

    ActivityThread thread = new ActivityThread();
    thread.attach(false);//看看这个方法干了什么

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

    AsyncTask.init();

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

    Looper.loop();//开启主线程消息循环

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

ActivityThread attach()

   private void attach(boolean system) {
   ...
   //这里实际调用的是ActivityManagerService attachApplication()
    IActivityManager mgr = ActivityManagerNative.getDefault();
        try {
            mgr.attachApplication(mAppThread);
        } catch (RemoteException ex) {
            // Ignore
        }
    ...
      try {
            mInstrumentation = new Instrumentation();
            ContextImpl context = new ContextImpl();
            context.init(getSystemContext().mPackageInfo, null, this);
            Application app = Instrumentation.newApplication(Application.class, context);//①
            mAllApplications.add(app);
            mInitialApplication = app;
            app.onCreate();②
        } catch (Exception e) {
            throw new RuntimeException(
                    "Unable to instantiate Application():" + e.toString(), e);
        }
    ...
}

①处调用的方法

 static public Application newApplication(Class<?> clazz, Context context)
        throws InstantiationException, IllegalAccessException, 
        ClassNotFoundException {
    Application app = (Application)clazz.newInstance();
    app.attach(context);//
    return app;
}
/**
 * @hide
 */
 final void attach(Context context) {
    attachBaseContext(context);
    mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}

调用了Application域的attachBaseContext

 protected void attachBaseContext(Context base) {
        if (mBase != null) {
            throw new IllegalStateException("Base context already set");
        }
        mBase = base;
    }

②处调用的方法Application域的OnCreate()方法

接下来分析第一个Activity的生命周期方法分别都什么时候调用

ActivityManagerService.attachApplication(…)
ActivityManagerService.attachApplicationLocked(…)
ActivityStackSupervisor.attachApplicationLocked()
ActivityStackSupervisor.realStartActivityLocked()
IApplicationThread.scheduleLauncherActivity()
ActivityThread.sendMessage()
ActivityThread.H.sendMessage()
ActivityThread.H.handleMessage()
ActivityThread.handleLauncherActivity()
ActivityThread.performLauncherActivity()
Instrumentation.callActivityOnCreate()
Activity.onCreate()
ActivityThread.handleResumeActivity()
ActivityThread.performResumeActivity()
Activity.performResume()
Instrumentation.callActivityOnResume()
Activity.onResume()
ActivityManagerNative.getDefault().activityResumed(token)
AMS的attachApplicationLocked

@Override
public final void attachApplication(IApplicationThread thread) {
    synchronized (this) {
        int callingPid = Binder.getCallingPid();
        final long origId = Binder.clearCallingIdentity();
        attachApplicationLocked(thread, callingPid);
        Binder.restoreCallingIdentity(origId);
    }
}

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

    ...
    // See if the top visible activity is waiting to run in this process...
    if (normalMode) {
        try {
            if (mStackSupervisor.attachApplicationLocked(app)) {
                didSomething = true;
            }
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
            badApp = true;
        }
    }
    }
    ...

    return true;
}

调用ActivityStackSupervisor的attachApplicationLocked(…)

  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 {
                       //这里开启Activity
                        if (realStartActivityLocked(hr, app, true, true)) {
                            didSomething = true;
                        }
                    } catch (RemoteException e) {
                        Slog.w(TAG, "Exception in new application when starting activity "
                              + hr.intent.getComponent().flattenToShortString(), e);
                        throw e;
                    }
                }
            }
        }
    }
    if (!didSomething) {
        ensureActivitiesVisibleLocked(null, 0);
    }
    return didSomething;
}

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

    ...
        app.forceProcessStateUpTo(mService.mTopProcessState);
        app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
                new Configuration(stack.mOverrideConfig), r.compat, r.launchedFromPackage,
                task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
                newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
    ...
    return true;
}
app.thread.scheduleLaunchActivity(…)这个方法的调用和前面OnPause有点类似 是通过调用IApplicationThread的方法实现的,这里调用的是scheduleLauncherActivity方法,所以真正执行的是ActivityThread中的scheduleLauncherActivity,所以我们看一下ActivityThread中的scheduleLauncherActivity的实现
// we use token to identify this activity without having to send the
// activity itself back to the activity manager. (matters more with ipc)
 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
            ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
            Bundle state, List<ResultInfo> pendingResults,
            List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
            String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
        ActivityClientRecord r = new ActivityClientRecord();

        r.token = token;
        r.ident = ident;
        r.intent = intent;
        r.activityInfo = info;
        r.compatInfo = compatInfo;
        r.state = state;

        r.pendingResults = pendingResults;
        r.pendingIntents = pendingNewIntents;

        r.startsNotResumed = notResumed;
        r.isForward = isForward;

        r.profileFile = profileName;
        r.profileFd = profileFd;
        r.autoStopProfiler = autoStopProfiler;

        updatePendingConfiguration(curConfig);

        queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
    }

H的handlerMessage方法

      ...
       case LAUNCH_ACTIVITY: {
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                ActivityClientRecord r = (ActivityClientRecord)msg.obj;

                r.packageInfo = getPackageInfoNoCheck(
                        r.activityInfo.applicationInfo, r.compatInfo);
                handleLaunchActivity(r, null);
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            } break;
          ....

还是那套逻辑,ActivityThread接收到SystemServer进程的消息之后会通过其内部的Handler对象分发消息,经过一系列的分发之后调用了ActivityThread的handleLaunchActivity方法:

     private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    // If we are getting ready to gc after going to the background, well
    ...
    Activity a = performLaunchActivity(r, customIntent);
    ...
    handleResumeActivity(r.token, false, r.isForward,
                !r.activity.mFinished && !r.startsNotResumed);
    ....
}  

  private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
                    ...

            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);
                        }
                    }
                    ...

                    activity.mCalled = false;
                    if (r.isPersistable()) {//①
                       mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                    } else {
                       mInstrumentation.callActivityOnCreate(activity, r.state);
                    }
                    ...
                    if (!r.activity.mFinished) {
                                activity.performStart();//②
                                r.stopped = false;
                            }
                    ...
    return activity;
}        

①onCreate 生命周期

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

            /**
             * Perform calling of an activity's {@link Activity#onCreate}
             * method.  The default implementation simply calls through to that method.
             *  @param activity The activity being created.
             * @param icicle The previously frozen state (or null) to pass through to
             * @param persistentState The previously persisted state (or null)
             */
            public void callActivityOnCreate(Activity activity, Bundle icicle,
                    PersistableBundle persistentState) {
                prePerformCreate(activity);
                activity.performCreate(icicle, persistentState);
                postPerformCreate(activity);
            }

然后执行activity的performCreate方法

    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
            onCreate(icicle, persistentState);//生命周期方法
            mActivityTransitionState.readState(icicle);
            performCreateCommon();
        }

②OnStart 生命周期

一样的逻辑会走到这

 final void performStart() {
        mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
        mFragments.noteStateNotSaved();
        mCalled = false;
        mFragments.execPendingActions();
        mInstrumentation.callActivityOnStart(this);
        if (!mCalled) {
            throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onStart()");
        }
        mFragments.dispatchStart();
        mFragments.reportLoaderStart();
        mActivityTransitionState.enterReady(this);
    }

这个是Instrumentation的方法

    public void callActivityOnStart(Activity activity) {
    activity.onStart();
    }

接下来回到这个方法handleLaunchActivity()之后调用 handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed);

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

    ActivityClientRecord r = performResumeActivity(token, clearHide);
    ...
   }

ActivityThread的方法

public final ActivityClientRecord performResumeActivity(IBinder token,
                boolean clearHide) {
     ActivityClientRecord r = mActivities.get(token);    
     ...
     r.activity.performResume();
     ...       
}

Activity的performResume()

final void performResume() {
    performRestart();

    mFragments.execPendingActions();

    mLastNonConfigurationInstances = null;

    mCalled = false;
    // mResumed is set by the instrumentation
    mInstrumentation.callActivityOnResume(this);
    if (!mCalled) {
        throw new SuperNotCalledException(
            "Activity " + mComponent.toShortString() +
            " did not call through to super.onResume()");
    }

    // invisible activities must be finished before onResume() completes
    if (!mVisibleFromClient && !mFinished) {
        Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
        if (getApplicationInfo().targetSdkVersion
                > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
            throw new IllegalStateException(
                    "Activity " + mComponent.toShortString() +
                    " did not call finish() prior to onResume() completing");
        }
    }

    // Now really resume, and install the current status bar and menu.
    mCalled = false;

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

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

Instrumentation的方法

 public void callActivityOnResume(Activity activity) {
        activity.mResumed = true;
        activity.onResume();

        if (mActivityMonitors != null) {
            synchronized (mSync) {
                final int N = mActivityMonitors.size();
                for (int i=0; i<N; i++) {
                    final ActivityMonitor am = mActivityMonitors.get(i);
                    am.match(activity, activity, activity.getIntent());
                }
            }
        }
    }
至此我们就可以看到Activity的页面了
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值