美文网首页
通过源码分析Activity和Applicaiton的启动流程(

通过源码分析Activity和Applicaiton的启动流程(

作者: Coder_Sven | 来源:发表于2020-04-08 17:14 被阅读0次

    1.1 startActivity分析

    public void startActivity(Intent intent) {
            this.startActivity(intent, null);
        }
    
    public void startActivity(Intent intent, @Nullable Bundle options) {
            if (options != null) {
                startActivityForResult(intent, -1, options);
            } else {
                //[见1.2]
                startActivityForResult(intent, -1);
            }
        }
    

    1.2 startActivityForResult

     public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
                @Nullable Bundle options) {
            if (mParent == null) {
                options = transferSpringboardActivityOptions(options);
                //[见1.3]
                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) {
                    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);
                }
            }
        }
    

    1.3 execStartActivity

    [—>Instrumentation.java]

     public ActivityResult execStartActivity(
                Context who, IBinder contextThread, IBinder token, Activity target,
                Intent intent, int requestCode, Bundle options) {
            IApplicationThread whoThread = (IApplicationThread) contextThread;
            Uri referrer = target != null ? target.onProvideReferrer() : null;
            if (referrer != null) {
                intent.putExtra(Intent.EXTRA_REFERRER, referrer);
            }
            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(who);
                //见[1.4]
                int result = ActivityManagerNative.getDefault()
                    .startActivity(whoThread, who.getBasePackageName(), intent,
                            intent.resolveTypeIfNeeded(who.getContentResolver()),
                            token, target != null ? target.mEmbeddedID : null,
                            requestCode, 0, null, options);
                checkStartActivityResult(result, intent);
            } catch (RemoteException e) {
                throw new RuntimeException("Failure from system", e);
            }
            return null;
        }
    

    1.4 ActivityManagerNative.getDefault()

    static public IActivityManager getDefault() {
            return gDefault.get();
        }
        
      private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
            protected IActivityManager create() {
            //这一步返回的是系统服务ActivityManagerService
                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;
            }
        };
        
        static public IActivityManager asInterface(IBinder obj) {
            if (obj == null) {
                return null;
            }
            IActivityManager in =
                (IActivityManager)obj.queryLocalInterface(descriptor);
            if (in != null) {
                return in;
            }
    
            return new ActivityManagerProxy(obj);
        }
    

    1.5 上面返回的是一个IActivityManager对象,IActivityManager是一个接口,只调用startActivity方法,具体的实现方法在 ActivityManagerProxy类中

    [—>ActivityManagerNative.ActivityManagerProxy.java]

      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 = Parcel.obtain();
            Parcel reply = Parcel.obtain();
            data.writeInterfaceToken(IActivityManager.descriptor);
            data.writeStrongBinder(caller != null ? caller.asBinder() : null);
            data.writeString(callingPackage);
            intent.writeToParcel(data, 0);
            data.writeString(resolvedType);
            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);
            }
            //amp其实都是执行在client进程中的,当执行到下面这个方法时它就通完binder传输数据到另一个进程了,另一个进程在接受到数据后进行相应的操作了 [见1.6]
            mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
            reply.readException();
            int result = reply.readInt();
            reply.recycle();
            data.recycle();
            return result;
        }
    

    mRemote在[1.4]中可以知道是ActivityManagerService,这里通过Binder通信,客户端调用transact方法,服务端会回调客户端的onTransact()方法。

    1.6 ActivityManagerService.onTransact

    public final class ActivityManagerService extends ActivityManagerNative
            implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
                
                .............
                
                    @Override
        public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
                throws RemoteException {
            if (code == SYSPROPS_TRANSACTION) {
                // We need to tell all apps about the system property change.
                ArrayList<IBinder> procs = new ArrayList<IBinder>();
                synchronized(this) {
                    final int NP = mProcessNames.getMap().size();
                    for (int ip=0; ip<NP; ip++) {
                        SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
                        final int NA = apps.size();
                        for (int ia=0; ia<NA; ia++) {
                            ProcessRecord app = apps.valueAt(ia);
                            if (app.thread != null) {
                                procs.add(app.thread.asBinder());
                            }
                        }
                    }
                }
    
                int N = procs.size();
                for (int i=0; i<N; i++) {
                    Parcel data2 = Parcel.obtain();
                    try {
                        procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
                    } catch (RemoteException e) {
                    }
                    data2.recycle();
                }
            }
            try {
            //见[1.7]
                return super.onTransact(code, data, reply, flags);
            } catch (RuntimeException e) {        
                throw e;
            }
        }
                
                
            }
    

    因为ActivityManagerService继承了ActivityManagerNative,所以上面的super.onTransact(code, data, reply, flags);调用的是ActivityManagerNative中的方法。

    1.7 ActivityManagerNative.onTransact

     @Override
        public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
                throws RemoteException {
            switch (code) {
            case START_ACTIVITY_TRANSACTION:
            {
                data.enforceInterface(IActivityManager.descriptor);
                IBinder b = data.readStrongBinder();
                IApplicationThread app = ApplicationThreadNative.asInterface(b);
                String callingPackage = data.readString();
                Intent intent = Intent.CREATOR.createFromParcel(data);
                String resolvedType = data.readString();
                IBinder resultTo = data.readStrongBinder();
                String resultWho = data.readString();
                int requestCode = data.readInt();
                int startFlags = data.readInt();
                ProfilerInfo profilerInfo = data.readInt() != 0
                        ? ProfilerInfo.CREATOR.createFromParcel(data) : null;
                Bundle options = data.readInt() != 0
                        ? Bundle.CREATOR.createFromParcel(data) : null;
                        //见[1.8]
                int result = startActivity(app, callingPackage, intent, resolvedType,
                        resultTo, resultWho, requestCode, startFlags, profilerInfo, options);
                reply.writeNoException();
                reply.writeInt(result);
                return true;
            }
            
            .......
            
            
            }
    

    ActivityManagerNative是一个抽象类实现了IActivityManager接口,但是它只是调用了startActivity等方法,真正的实现方法在子类ActivityManagerService中完成。

    1.8 ActivityManagerService.startActivity

     @Override
        public final int startActivity(IApplicationThread caller, String callingPackage,
                Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
                int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
            return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                    resultWho, requestCode, startFlags, profilerInfo, bOptions,
                    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 bOptions, int userId) {
            enforceNotIsolatedCaller("startActivity");
            userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
                    userId, false, ALLOW_FULL_ONLY, "startActivity", null);
            // TODO: Switch to user app stacks here.
            //见[1.9]
            return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                    resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                    profilerInfo, null, null, bOptions, false, userId, null, null);
        }
        
    

    1.9 ActivityStarter.startActivityMayWait

     final int startActivityMayWait(IApplicationThread caller, int callingUid,
                String callingPackage, Intent intent, String resolvedType,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                IBinder resultTo, String resultWho, int requestCode, int startFlags,
                ProfilerInfo profilerInfo, IActivityManager.WaitResult outResult, Configuration config,
                Bundle bOptions, boolean ignoreTargetSecurity, int userId,
                IActivityContainer iContainer, TaskRecord inTask) {
            ...
         
            // Save a copy in case ephemeral needs it
            final Intent ephemeralIntent = new Intent(intent);
            // Don't modify the client's object!
            intent = new Intent(intent);
            //解析Intent所带的信息
            ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId);
            if (rInfo == null) {
               ...
            }
            // Collect information about the target of the Intent.
            ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
    
            ActivityOptions options = ActivityOptions.fromBundle(bOptions);
            ActivityStackSupervisor.ActivityContainer container =
                    (ActivityStackSupervisor.ActivityContainer)iContainer;
            synchronized (mService) {
                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;
                }
                ....
    
                final ActivityStack stack;
                if (container == null || container.mStack.isOnHomeDisplay()) {
                    stack = mSupervisor.mFocusedStack;
                } else {
                    stack = container.mStack;
                }
                stack.mConfigWillChange = config != null && mService.mConfiguration.diff(config) != 0;
                if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
                        "Starting activity when config will change = " + stack.mConfigWillChange);
    
                final long origId = Binder.clearCallingIdentity();
    
                if (aInfo != null &&
                        (aInfo.applicationInfo.privateFlags
                                & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
                    ...
                }
    
                final ActivityRecord[] outRecord = new ActivityRecord[1];
                //见[1.10]
                int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
                        aInfo, rInfo, voiceSession, voiceInteractor,
                        resultTo, resultWho, requestCode, callingPid,
                        callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                        options, ignoreTargetSecurity, componentSpecified, outRecord, container,
                        inTask);
    
                Binder.restoreCallingIdentity(origId);
    
                if (stack.mConfigWillChange) {
                    ...
                }
    
                if (outResult != null) {
                  ...
                }
    
                final ActivityRecord launchedActivity = mReusedActivity != null
                        ? mReusedActivity : outRecord[0];
                mSupervisor.mActivityMetricsLogger.notifyActivityLaunched(res, launchedActivity);
                return res;
            }
        }
    

    1.10 ActivityStarter.startActivityLocked

        final int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
                String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
                String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
                ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
                ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
                TaskRecord inTask) {
                    
                    ......
                    try {
                mService.mWindowManager.deferSurfaceLayout();
                //见[1.11]
                err = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                        true, options, inTask);
            } finally {
                mService.mWindowManager.continueSurfaceLayout();
            }
            postStartActivityUncheckedProcessing(r, err, stack.mStackId, mSourceRecord, mTargetStack);
            return err;
                    
                    
                }
    

    1.11 ActivityStarter.startActivityUnchecked

       private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask) {
                    .....
                    //mTargetStack 是一个ActivityStack对象。见[1.12]
                     mTargetStack.startActivityLocked(mStartActivity, newTask, mKeepCurTransition, mOptions);
                     if (mDoResume) {//是true,立即显示
                if (!mLaunchTaskBehind) {
                    mService.setFocusedActivityLocked(mStartActivity, "startedActivity");
                }
                final ActivityRecord topTaskActivity = mStartActivity.task.topRunningActivityLocked();
                if (!mTargetStack.isFocusable()
                        || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                        && mStartActivity != topTaskActivity)) {//activity不可见的时候
                    // If the activity is not focusable, we can't resume it, but still would like to
                    // make sure it becomes visible as it starts (this will also trigger entry
                    // animation). An example of this are PIP activities.
                    // Also, we don't want to resume activities in a task that currently has an overlay
                    // as the starting activity just needs to be in the visible paused state until the
                    // over is removed.
                    mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
                    // Go ahead and tell window manager to execute app transition for this activity
                    // since the app transition will not be triggered through the resume channel.
                    mWindowManager.executeAppTransition();
                } else {
                 //见[1.13]
                    mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                            mOptions);
                }
            } else {
                mTargetStack.addRecentActivityLocked(mStartActivity);
            }
           
            mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);
    
            mSupervisor.handleNonResizableTaskIfNeeded(
                    mStartActivity.task, preferredLaunchStackId, mTargetStack.mStackId);
                    return START_SUCCESS;
                }
    

    1.12 ActivityStack.startActivityLocked

        final void startActivityLocked(ActivityRecord r, boolean newTask, boolean keepCurTransition,
                ActivityOptions options) {
            TaskRecord rTask = r.task;
            final int taskId = rTask.taskId;
            // mLaunchTaskBehind tasks get placed at the back of the task stack.
            if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {
                // Last activity in task had been removed or ActivityManagerService is reusing task.
                // Insert or replace.
                // Might not even be in.
                insertTaskAtTop(rTask, r);
                mWindowManager.moveTaskToTop(taskId);
            }
            TaskRecord task = null;
            if (!newTask) {
                // If starting in an existing task, find where that is...
                boolean startIt = true;
                for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
                    task = mTaskHistory.get(taskNdx);
                    if (task.getTopActivity() == null) {
                        // All activities in task are finishing.
                        continue;
                    }
                    if (task == r.task) {
                        // Here it is!  Now, if this is not yet visible to the
                        // user, then just add it without starting; it will
                        // get started when the user navigates back to it.
                        if (!startIt) {
                            if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "
                                    + task, new RuntimeException("here").fillInStackTrace());
                            task.addActivityToTop(r);
                            r.putInHistory();
                            addConfigOverride(r, task);
                            if (VALIDATE_TOKENS) {
                                validateAppTokensLocked();
                            }
                            ActivityOptions.abort(options);
                            return;
                        }
                        break;
                    } else if (task.numFullscreen > 0) {
                        startIt = false;
                    }
                }
            }
    
            // Place a new activity at top of stack, so it is next to interact
            // with the user.
    
            // If we are not placing the new activity frontmost, we do not want
            // to deliver the onUserLeaving callback to the actual frontmost
            // activity
            if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) {
                mStackSupervisor.mUserLeaving = false;
                if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING,
                        "startActivity() behind front, mUserLeaving=false");
            }
    
            task = r.task;
    
            // Slot the activity into the history stack and proceed
            if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task,
                    new RuntimeException("here").fillInStackTrace());
            task.addActivityToTop(r);
            task.setFrontOfTask();
    
            r.putInHistory();
            if (!isHomeStack() || numActivities() > 0) {
                // We want to show the starting preview window if we are
                // switching to a new task, or the next activity's process is
                // not currently running.
                boolean showStartingIcon = newTask;
                ProcessRecord proc = r.app;
                if (proc == null) {
                    proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
                }
                if (proc == null || proc.thread == null) {
                    showStartingIcon = true;
                }
                if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
                        "Prepare open transition: starting " + r);
                if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
                    mWindowManager.prepareAppTransition(TRANSIT_NONE, keepCurTransition);
                    mNoAnimActivities.add(r);
                } else {
                    mWindowManager.prepareAppTransition(newTask
                            ? r.mLaunchTaskBehind
                                    ? TRANSIT_TASK_OPEN_BEHIND
                                    : TRANSIT_TASK_OPEN
                            : TRANSIT_ACTIVITY_OPEN, keepCurTransition);
                    mNoAnimActivities.remove(r);
                }
                addConfigOverride(r, task);
                boolean doShow = true;
                if (newTask) {
                    // Even though this activity is starting fresh, we still need
                    // to reset it to make sure we apply affinities to move any
                    // existing activities from other tasks in to it.
                    // If the caller has requested that the target task be
                    // reset, then do so.
                    if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
                        resetTaskIfNeededLocked(r, r);
                        doShow = topRunningNonDelayedActivityLocked(null) == r;
                    }
                } else if (options != null && options.getAnimationType()
                        == ActivityOptions.ANIM_SCENE_TRANSITION) {
                    doShow = false;
                }
                if (r.mLaunchTaskBehind) {
                    // Don't do a starting window for mLaunchTaskBehind. More importantly make sure we
                    // tell WindowManager that r is visible even though it is at the back of the stack.
                    mWindowManager.setAppVisibility(r.appToken, true);
                    ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
                } else if (SHOW_APP_STARTING_PREVIEW && doShow) {
                    // Figure out if we are transitioning from another activity that is
                    // "has the same starting icon" as the next one.  This allows the
                    // window manager to keep the previous window it had previously
                    // created, if it still had one.
                    ActivityRecord prev = r.task.topRunningActivityWithStartingWindowLocked();
                    if (prev != null) {
                        // We don't want to reuse the previous starting preview if:
                        // (1) The current activity is in a different task.
                        if (prev.task != r.task) {
                            prev = null;
                        }
                        // (2) The current activity is already displayed.
                        else if (prev.nowVisible) {
                            prev = null;
                        }
                    }
                    r.showStartingWindow(prev, showStartingIcon);
                }
            } else {
                // If this is the first activity, don't do any fancy animations,
                // because there is nothing for it to animate on top of.
                addConfigOverride(r, task);
                ActivityOptions.abort(options);
                options = null;
            }
            if (VALIDATE_TOKENS) {
                validateAppTokensLocked();
            }
        }
    

    1.13 startActivityLocked方法走完之后回到1.11里面的 mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,mOptions)方法

    [—>ActivityStackSupervisor.java]

        boolean resumeFocusedStackTopActivityLocked() {
            return resumeFocusedStackTopActivityLocked(null, null, null);
        }
    
        boolean resumeFocusedStackTopActivityLocked(
                ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
            if (targetStack != null && isFocusedStack(targetStack)) {
                //见[1.14]
                return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
            }
            final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
            if (r == null || r.state != RESUMED) {
                mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
            }
            return false;
        }
    

    1.14 ActivityStack.resumeTopActivityUncheckedLocked

    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions 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();
                }
                //见[1.15]
                result = resumeTopActivityInnerLocked(prev, options);
            } finally {
                mStackSupervisor.inResumeTopActivity = false;
            }
            return result;
        }
    

    1.15 ActivityStack.resumeTopActivityInnerLocked

     private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    
            // 找到第一个没有finish的栈顶Activity
            final ActivityRecord next = topRunningActivityLocked();
            ...
            final TaskRecord prevTask = prev != null ? prev.task : null;
            if (next == null) {
                // 没有更多Activity只有桌面Activity,只启动Launcher界面
                final String reason = "noMoreActivities";
                final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack()
                        ? HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
                if (!mFullscreen && adjustFocusToNextFocusableStackLocked(returnTaskType, reason)) {
                    return mStackSupervisor.resumeFocusedStackTopActivityLocked(
                            mStackSupervisor.getFocusedStack(), prev, null);
                }
    
                ActivityOptions.abort(options);
                return isOnHomeDisplay() &&
                        mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, reason);
            }
    
            next.delayedResume = false;
    
            ......
    
            ActivityStack lastStack = mStackSupervisor.getLastStack();
            //进程已经存在的情况
            if (next.app != null && next.app.thread != null) {
                // If the previous activity is translucent, force a visibility update of
                // the next activity, so that it's added to WM's opening app list, and
                // transition animation can be set up properly.
                // For example, pressing Home button with a translucent activity in focus.
                // Launcher is already visible in this case. If we don't add it to opening
                // apps, maybeUpdateTransitToWallpaper() will fail to identify this as a
                // TRANSIT_WALLPAPER_OPEN animation, and run some funny animation.
                final boolean lastActivityTranslucent = lastStack != null
                        && (!lastStack.mFullscreen
                        || (lastStack.mLastPausedActivity != null
                        && !lastStack.mLastPausedActivity.fullscreen));
    
                // This activity is now becoming visible.
                if (!next.visible || next.stopped || lastActivityTranslucent) {
                    mWindowManager.setAppVisibility(next.appToken, true);
                }
    
                // schedule launch ticks to collect information about slow apps.
                next.startLaunchTickingLocked();
    
                ActivityRecord lastResumedActivity =
                        lastStack == null ? null :lastStack.mResumedActivity;
                ActivityState lastState = next.state;
    
                mService.updateCpuStats();
    
                //设置Activity状态为Resume
                next.state = ActivityState.RESUMED;
                mResumedActivity = next;
                next.task.touchActiveTime();
                mRecentTasks.addLocked(next.task);
                mService.updateLruProcessLocked(next.app, true, null);
                updateLRUListLocked(next);
                mService.updateOomAdjLocked();
    
                // Have the window manager re-evaluate the orientation of
                // the screen based on the new activity order.
                boolean notUpdated = true;
                if (mStackSupervisor.isFocusedStack(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);
                }
    
                if (notUpdated) {
                    // The configuration update wasn't able to keep the existing
                    // instance of the activity, and instead started a new one.
                    // We should be all done, but let's just make sure our activity
                    // is still at the top and schedule another run if something
                    // weird happened.
                    ActivityRecord nextNext = topRunningActivityLocked();
                    if (nextNext != next) {
                        mStackSupervisor.scheduleResumeTopActivities();
                    }
                    if (mStackSupervisor.reportResumedActivityLocked(next)) {
                        mNoAnimActivities.clear();
                        return true;
                    }
                    return false;
                }
    
                try {
                    // Deliver all pending results.
                    ArrayList<ResultInfo> a = next.results;
                    if (a != null) {
                        final int N = a.size();
                        if (!next.finishing && N > 0) {
                            next.app.thread.scheduleSendResult(next.appToken, a);
                        }
                    }
    
                    boolean allowSavedSurface = true;
                    if (next.newIntents != null) {
                        // Restrict saved surface to launcher start, or there is no intent at all
                        // (eg. task being brought to front). If the intent is something else,
                        // likely the app is going to show some specific page or view, instead of
                        // what's left last time.
                        for (int i = next.newIntents.size() - 1; i >= 0; i--) {
                            final Intent intent = next.newIntents.get(i);
                            if (intent != null && !ActivityRecord.isMainIntent(intent)) {
                                allowSavedSurface = false;
                                break;
                            }
                        }
                        next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
                    }
    
                    // Well the app will no longer be stopped.
                    // Clear app token stopped state in window manager if needed.
                    mWindowManager.notifyAppResumed(next.appToken, next.stopped, allowSavedSurface);
    
                    EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY, next.userId,
                            System.identityHashCode(next), next.task.taskId, next.shortComponentName);
    
                    next.sleeping = false;
                    mService.showUnsupportedZoomDialogIfNeededLocked(next);
                    mService.showAskCompatModeDialogLocked(next);
                    next.app.pendingUiClean = true;
                    next.app.forceProcessStateUpTo(mService.mTopProcessState);
                    next.clearOptionsLocked();
                    //触发onResume
                    next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState,
                            mService.isNextTransitionForward(), resumeAnimOptions);
    
                    mStackSupervisor.checkReadyForSleepLocked();
    
                } catch (Exception e) {
                    // Whoops, need to restart this activity!
                    next.state = lastState;
                    if (lastStack != null) {
                        lastStack.mResumedActivity = lastResumedActivity;
                    }
                    if (!next.hasBeenLaunched) {
                        next.hasBeenLaunched = true;
                    } else  if (SHOW_APP_STARTING_PREVIEW && lastStack != null &&
                            mStackSupervisor.isFrontStack(lastStack)) {
                        next.showStartingWindow(null, true);
                    }
                    mStackSupervisor.startSpecificActivityLocked(next, true, false);
                    return true;
                }
    
                // From this point on, if something goes wrong there is no way
                // to recover the activity.
                try {
                    completeResumeLocked(next);
                } catch (Exception e) {
                    // If any exception gets thrown, toss away this
                    // activity and try the next one.
                    requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
                            "resume-exception", true);
                    return true;
                }
            } else {
                // Whoops, need to restart this activity!
                if (!next.hasBeenLaunched) {
                    next.hasBeenLaunched = true;
                } else {
                    if (SHOW_APP_STARTING_PREVIEW) {
                        next.showStartingWindow(null, true);
                    }
                }
                //见[1.16]
                mStackSupervisor.startSpecificActivityLocked(next, true, true);
            }
    
            return true;
        }
    

    1.16 ActivityStackSupervisor.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);
                    }
                    //见[1.25]
                    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.
            }
            //当进程不存在则创建进程 见[1.17]
            mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                    "activity", r.intent.getComponent(), false, false, true);
        }
    

    1.17ActivityManagerService.startProcessLocked startProcessLocked 方法内部调用了Process.start,并且指定了android.app.ActivityThread作为入口,进程启动后,将调用android.app.ActivityThread的main方法

    private final void startProcessLocked(ProcessRecord app, String hostingType,
            String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
            // ...
            // Start the process.  It will either succeed and return a result containing
            // the PID of the new process, or else throw a RuntimeException.
            boolean isActivityProcess = (entryPoint == null);
            if (entryPoint == null) entryPoint = "android.app.ActivityThread";
            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);
            // ...
    }
    

    1.18ActivityThread.main

       public static void main(String[] args) {
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
            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());
    
            // Make sure TrustedCertificateStore looks in the right place for CA certificates
            final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
            TrustedCertificateStore.setDefaultUserDirectory(configDir);
    
            Process.setArgV0("<pre-initialized>");
    
            Looper.prepareMainLooper();
    
            //[见1.19]
            ActivityThread thread = new ActivityThread();
            thread.attach(false);
    
            if (sMainThreadHandler == null) {
                sMainThreadHandler = thread.getHandler();
            }
    
            if (false) {
                Looper.myLooper().setMessageLogging(new
                        LogPrinter(Log.DEBUG, "ActivityThread"));
            }
    
            // End of event ActivityThreadMain.
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            Looper.loop();
    
            throw new RuntimeException("Main thread loop unexpectedly exited");
        }
    

    1.19 ActivityThread.attach

       private void attach(boolean system) {
            sCurrentActivityThread = this;
            mSystemThread = system;
            if (!system) {
                ViewRootImpl.addFirstDrawHandler(new Runnable() {
                    @Override
                    public void run() {
                        ensureJitEnabled();
                    }
                });
                android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                        UserHandle.myUserId());
                RuntimeInit.setApplicationObject(mAppThread.asBinder());
                final IActivityManager mgr = ActivityManagerNative.getDefault();
                try {
                    //[见1.20]
                    mgr.attachApplication(mAppThread);
                } catch (RemoteException ex) {
                    throw ex.rethrowFromSystemServer();
                }
                // Watch for getting close to heap limit.
                BinderInternal.addGcWatcher(new Runnable() {
                    @Override public void run() {
                        if (!mSomeActivitiesChanged) {
                            return;
                        }
                        Runtime runtime = Runtime.getRuntime();
                        long dalvikMax = runtime.maxMemory();
                        long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
                        if (dalvikUsed > ((3*dalvikMax)/4)) {
                            if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
                                    + " total=" + (runtime.totalMemory()/1024)
                                    + " used=" + (dalvikUsed/1024));
                            mSomeActivitiesChanged = false;
                            try {
                                mgr.releaseSomeActivities(mAppThread);
                            } catch (RemoteException e) {
                                throw e.rethrowFromSystemServer();
                            }
                        }
                    }
                });
            } else {
                // Don't set application object here -- if the system crashes,
                // we can't display an alert, we just want to die die die.
                android.ddm.DdmHandleAppName.setAppName("system_process",
                        UserHandle.myUserId());
                try {
                    mInstrumentation = new Instrumentation();
                    ContextImpl context = ContextImpl.createAppContext(
                            this, getSystemContext().mPackageInfo);
                    mInitialApplication = context.mPackageInfo.makeApplication(true, null);
                    mInitialApplication.onCreate();
                } catch (Exception e) {
                    throw new RuntimeException(
                            "Unable to instantiate Application():" + e.toString(), e);
                }
            }
    
            // add dropbox logging to libcore
            DropBox.setReporter(new DropBoxReporter());
    
            ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    synchronized (mResourcesManager) {
                        // We need to apply this change to the resources
                        // immediately, because upon returning the view
                        // hierarchy will be informed about it.
                        if (mResourcesManager.applyConfigurationToResourcesLocked(newConfig, null)) {
                            updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
                                    mResourcesManager.getConfiguration().getLocales());
    
                            // This actually changed the resources!  Tell
                            // everyone about it.
                            if (mPendingConfiguration == null ||
                                    mPendingConfiguration.isOtherSeqNewer(newConfig)) {
                                mPendingConfiguration = newConfig;
    
                                sendMessage(H.CONFIGURATION_CHANGED, newConfig);
                            }
                        }
                    }
                }
                @Override
                public void onLowMemory() {
                }
                @Override
                public void onTrimMemory(int level) {
                }
            });
        }
    

    1.20 IActivityManager.attachApplication的具体实现是在ActivityManagerProxy中完成的

    [—>ActivityManagerProxy.java]

     public void attachApplication(IApplicationThread app) throws RemoteException
        {
            Parcel data = Parcel.obtain();
            Parcel reply = Parcel.obtain();
            data.writeInterfaceToken(IActivityManager.descriptor);
            data.writeStrongBinder(app.asBinder());
            //binder机制进行通信,回调ActivityManagerNative.onTransact方法[见1.21]
            mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0);
            reply.readException();
            data.recycle();
            reply.recycle();
        }
    

    1.21ActivityManagerNative.onTransact

     case ATTACH_APPLICATION_TRANSACTION: {
                data.enforceInterface(IActivityManager.descriptor);
                IApplicationThread app = ApplicationThreadNative.asInterface(
                        data.readStrongBinder());
                if (app != null) {
                    //见[1.22]
                    attachApplication(app);
                }
                reply.writeNoException();
                return true;
            }
    

    1.22 ActivityManagerNative中没有attachApplication方法的具体实现,真正的实现在ActivityManagerNative的子类ActivityManagerService中完成

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

    1.23 ActivityManagerService.attachApplicationLocked

        private final boolean attachApplicationLocked(IApplicationThread thread,
                int pid) {
            ...        
            //见[2.1]APPlication启动   
            thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
                    profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
                    app.instrumentationUiAutomationConnection, testMode,
                    mBinderTransactionTrackingEnabled, enableTrackAllocation,
                    isRestrictedBackupMode || !normalMode, app.persistent,
                    new Configuration(mConfiguration), app.compat,
                    getCommonServicesLocked(app.isolated),
                    mCoreSettingsObserver.getCoreSettingsLocked());
            ...
            if (normalMode) {
                 //[见1.24]
                if (mStackSupervisor.attachApplicationLocked(app)) {
                    didSomething = true;
                }
            }
            ... 
        }
    

    1.24 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 (!isFocusedStack(stack)) {
                        continue;
                    }
                    ActivityRecord hr = stack.topRunningActivityLocked();
                    if (hr != null) {
                        if (hr.app == null && app.uid == hr.info.applicationInfo.uid
                                && processName.equals(hr.processName)) {
                            try {
                            //真正的启动Activity[见1.25]
                                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, !PRESERVE_WINDOWS);
            }
            return didSomething;
        }
    

    1.25 ActivityStackSupervisor.realStartActivityLocked

     final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
                                              boolean andResume, boolean checkConfig) throws RemoteException {
    
            ...
    
            final ActivityStack stack = 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;
                }
                if (r.isHomeActivity()) {
                    // Home process is the root process of the task.
                    mService.mHomeProcess = task.mActivities.get(0).app;
                }
                mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
                        PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY);
                r.sleeping = false;
                r.forceNewConfig = false;
                mService.showUnsupportedZoomDialogIfNeededLocked(r);
                mService.showAskCompatModeDialogLocked(r);
                r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
                ProfilerInfo profilerInfo = null;
                if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
                   ...
                }
    
                ...
                //将该进程设置为前台进程
                app.forceProcessStateUpTo(mService.mTopProcessState);
                //见[1.26]
                app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                        System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
                        new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
                        task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
                        newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
    
                if ((app.info.privateFlags&ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
                    // This may be a heavy-weight process!  Note that the package
                    // manager will ensure that only activity can run in the main
                    // process of the .apk, which is the only thing that will be
                    // considered heavy-weight.
                    if (app.processName.equals(app.info.packageName)) {
                        mService.mHeavyWeightProcess = app;
                        Message msg = mService.mHandler.obtainMessage(
                                ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
                        msg.obj = r;
                        mService.mHandler.sendMessage(msg);
                    }
                }
    
            } catch (RemoteException e) {
                if (r.launchFailed) {
                    // This is the second time we failed -- finish activity
                    // and give up.
                    mService.appDiedLocked(app);
                    stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
                            "2nd-crash", false);
                    return false;
                }
    
                // This is the first time we failed -- restart process and
                // retry.
                app.activities.remove(r);
                throw e;
            }
            
            ......
    
            return true;
        }
    

    1.26上面的app.thread指的是IApplicationThread,IApplicationThread是一个接口,方法的具体实现在ApplicationThreadProxy类中

        class ApplicationThreadProxy implements IApplicationThread {
    
            ...
    
            public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                                                     ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
                                                     CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
                                                     int procState, Bundle state, PersistableBundle persistentState,
                                                     List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
                                                     boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) throws RemoteException {
                Parcel data = Parcel.obtain();
                data.writeInterfaceToken(IApplicationThread.descriptor);
                intent.writeToParcel(data, 0);
                data.writeStrongBinder(token);
                data.writeInt(ident);
                info.writeToParcel(data, 0);
                curConfig.writeToParcel(data, 0);
                if (overrideConfig != null) {
                    data.writeInt(1);
                    overrideConfig.writeToParcel(data, 0);
                } else {
                    data.writeInt(0);
                }
                compatInfo.writeToParcel(data, 0);
                data.writeString(referrer);
                data.writeStrongBinder(voiceInteractor != null ? voiceInteractor.asBinder() : null);
                data.writeInt(procState);
                data.writeBundle(state);
                data.writePersistableBundle(persistentState);
                data.writeTypedList(pendingResults);
                data.writeTypedList(pendingNewIntents);
                data.writeInt(notResumed ? 1 : 0);
                data.writeInt(isForward ? 1 : 0);
                if (profilerInfo != null) {
                    data.writeInt(1);
                    profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
                } else {
                    data.writeInt(0);
                }
                //见[1.27]        
                mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,
                        IBinder.FLAG_ONEWAY);
                data.recycle();
            }
            ....
    
        }
    

    1.27 ApplicationThreadProxy代理的是 ActivityThread.ApplicationThread类,上面的mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,IBinder.FLAG_ONEWAY)会回调ApplicationThread的父类ApplicationThreadNative的Ontransact方法。

    [—>ApplicationThreadNative.java]

       @Override
        public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
                throws RemoteException {
            switch (code) {
                case SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION:
                {
                    data.enforceInterface(IApplicationThread.descriptor);
                    Intent intent = Intent.CREATOR.createFromParcel(data);
                    IBinder b = data.readStrongBinder();
                    int ident = data.readInt();
                    ActivityInfo info = ActivityInfo.CREATOR.createFromParcel(data);
                    Configuration curConfig = Configuration.CREATOR.createFromParcel(data);
                    Configuration overrideConfig = null;
                    if (data.readInt() != 0) {
                        overrideConfig = Configuration.CREATOR.createFromParcel(data);
                    }
                    CompatibilityInfo compatInfo = CompatibilityInfo.CREATOR.createFromParcel(data);
                    String referrer = data.readString();
                    IVoiceInteractor voiceInteractor = IVoiceInteractor.Stub.asInterface(
                            data.readStrongBinder());
                    int procState = data.readInt();
                    Bundle state = data.readBundle();
                    PersistableBundle persistentState = data.readPersistableBundle();
                    List<ResultInfo> ri = data.createTypedArrayList(ResultInfo.CREATOR);
                    List<ReferrerIntent> pi = data.createTypedArrayList(ReferrerIntent.CREATOR);
                    boolean notResumed = data.readInt() != 0;
                    boolean isForward = data.readInt() != 0;
                    ProfilerInfo profilerInfo = data.readInt() != 0
                            ? ProfilerInfo.CREATOR.createFromParcel(data) : null;
                            //见[1.28]
                    scheduleLaunchActivity(intent, b, ident, info, curConfig, overrideConfig, compatInfo,
                            referrer, voiceInteractor, procState, state, persistentState, ri, pi,
                            notResumed, isForward, profilerInfo);
                    return true;
                }
                .......
            }
        }
    

    1.28 ApplicationThreadNative是一个实现了IApplicationThread接口的抽象类,具体实现方法在他的子类ActivityThread.ApplicationThread中完成

    [—>ActivityThread.ApplicationThread.java]

           @Override
            public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                    ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
                    CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
                    int procState, Bundle state, PersistableBundle persistentState,
                    List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
                    boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
    
                updateProcessState(procState, false);
    
                ActivityClientRecord r = new ActivityClientRecord();
    
                r.token = token;
                r.ident = ident;
                r.intent = intent;
                r.referrer = referrer;
                r.voiceInteractor = voiceInteractor;
                r.activityInfo = info;
                r.compatInfo = compatInfo;
                r.state = state;
                r.persistentState = persistentState;
    
                r.pendingResults = pendingResults;
                r.pendingIntents = pendingNewIntents;
    
                r.startsNotResumed = notResumed;
                r.isForward = isForward;
    
                r.profilerInfo = profilerInfo;
    
                r.overrideConfig = overrideConfig;
                updatePendingConfiguration(curConfig);
                //见[1.29]
                sendMessage(H.LAUNCH_ACTIVITY, r);
            }
    
    

    1.29 H.handleMessage

    [—>ActivityThread.H.java]

     private class H extends Handler {
            ....
            public void handleMessage(Message msg) {
                if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
                switch (msg.what) {
                    case LAUNCH_ACTIVITY: {
                        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                        final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
    
                        r.packageInfo = getPackageInfoNoCheck(
                                r.activityInfo.applicationInfo, r.compatInfo);
                                //见[1.30]
                        handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
                        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    } break;
                   ....
                }
                Object obj = msg.obj;
                if (obj instanceof SomeArgs) {
                    ((SomeArgs) obj).recycle();
                }
            }
    
        }
    

    1.30 handleLaunchActivity

    [—>ActivityThread.java]

       private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
            ....
            // Make sure we are running with the most recent config.
            handleConfigurationChanged(null, null);
            ....
            //见[1.31]
            Activity a = performLaunchActivity(r, customIntent);
    
            if (a != null) {
                r.createdConfig = new Configuration(mConfiguration);
                reportSizeConfigurations(r);
                Bundle oldState = r.state;
                //最终回调目标Activity的onStart,onResume.
                handleResumeActivity(r.token, false, r.isForward,
                        !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
    
                if (!r.activity.mFinished && r.startsNotResumed) {
                    performPauseActivityIfNeeded(r, reason);
    
                    if (r.isPreHoneycomb()) {
                        r.state = oldState;
                    }
                }
            } else {
                try {
                 //存在error则停止该Activity
                    ActivityManagerNative.getDefault()
                            .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                                    Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
                } catch (RemoteException ex) {
                    throw ex.rethrowFromSystemServer();
                }
            }
        }
    

    1.31 performLaunchActivity

     private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    
            ActivityInfo aInfo = r.activityInfo;
            if (r.packageInfo == null) {
                r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                        Context.CONTEXT_INCLUDE_CODE);
            }
    
            ComponentName component = r.intent.getComponent();
            if (component == null) {
                component = r.intent.resolveActivity(
                        mInitialApplication.getPackageManager());
                r.intent.setComponent(component);
            }
    
            if (r.activityInfo.targetActivity != null) {
                component = new ComponentName(r.activityInfo.packageName,
                        r.activityInfo.targetActivity);
            }
    
            Activity activity = null;
            try {//反射创建Activity
                java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
                activity = mInstrumentation.newActivity(
                        cl, component.getClassName(), r.intent);
                StrictMode.incrementExpectedActivityCount(activity.getClass());
                r.intent.setExtrasClassLoader(cl);
                r.intent.prepareToEnterProcess();
                if (r.state != null) {
                    r.state.setClassLoader(cl);
                }
            } catch (Exception e) {
                if (!mInstrumentation.onException(activity, e)) {
                    throw new RuntimeException(
                            "Unable to instantiate activity " + component
                                    + ": " + e.toString(), e);
                }
            }
    
            try {//创建application对象
                Application app = r.packageInfo.makeApplication(false, mInstrumentation);
    
                if (activity != null) {
                    Context appContext = createBaseContextForActivity(r, activity);
                    CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                    Configuration config = new Configuration(mCompatConfiguration);
                    if (r.overrideConfig != null) {
                        config.updateFrom(r.overrideConfig);
                    }
                    Window window = null;
                    if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                        window = r.mPendingRemoveWindow;
                        r.mPendingRemoveWindow = null;
                        r.mPendingRemoveWindowManager = null;
                    }
                    activity.attach(appContext, this, getInstrumentation(), r.token,
                            r.ident, app, r.intent, r.activityInfo, title, r.parent,
                            r.embeddedID, r.lastNonConfigurationInstances, config,
                            r.referrer, r.voiceInteractor, window);
    
                    if (customIntent != null) {
                        activity.mIntent = customIntent;
                    }
                    r.lastNonConfigurationInstances = null;
                    activity.mStartedActivity = false;
                    int theme = r.activityInfo.getThemeResource();
                    if (theme != 0) {
                        activity.setTheme(theme);
                    }
    
                    activity.mCalled = false;
                    if (r.isPersistable()) {
                        //回调Activity的Oncreate方法
                        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();
                        r.stopped = false;
                    }
                    if (!r.activity.mFinished) {
                        if (r.isPersistable()) {
                            if (r.state != null || r.persistentState != null) {
                                mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                                        r.persistentState);
                            }
                        } else if (r.state != null) {
                            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                        }
                    }
                    if (!r.activity.mFinished) {
                        activity.mCalled = false;
                        if (r.isPersistable()) {
                            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) {
                if (!mInstrumentation.onException(activity, e)) {
                    throw new RuntimeException(
                            "Unable to start activity " + component
                                    + ": " + e.toString(), e);
                }
            }
    
            return activity;
        }
    
    
    

    到此,正式进入activity的onCreate,onStart,onResume这些生命周期的方法

    APPlication的加载(从上面1.23开始进入到Application加载)

    2.1 IApplicationThread.bindApplication

    IApplicationThread真正的实现类是在ApplicationThreadNative#ApplicationThreadProxy

    [—>ApplicationThreadNative#ApplicationThreadProxy.java]

        public final void bindApplication(String packageName, ApplicationInfo info,
                List<ProviderInfo> providers, ComponentName testName, ProfilerInfo profilerInfo,
                Bundle testArgs, IInstrumentationWatcher testWatcher,
                IUiAutomationConnection uiAutomationConnection, int debugMode,
                boolean enableBinderTracking, boolean trackAllocation, boolean restrictedBackupMode,
                boolean persistent, Configuration config, CompatibilityInfo compatInfo,
                Map<String, IBinder> services, Bundle coreSettings) throws RemoteException {
            Parcel data = Parcel.obtain();
            data.writeInterfaceToken(IApplicationThread.descriptor);
            data.writeString(packageName);
            info.writeToParcel(data, 0);
            data.writeTypedList(providers);
            if (testName == null) {
                data.writeInt(0);
            } else {
                data.writeInt(1);
                testName.writeToParcel(data, 0);
            }
            if (profilerInfo != null) {
                data.writeInt(1);
                profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
            } else {
                data.writeInt(0);
            }
            data.writeBundle(testArgs);
            data.writeStrongInterface(testWatcher);
            data.writeStrongInterface(uiAutomationConnection);
            data.writeInt(debugMode);
            data.writeInt(enableBinderTracking ? 1 : 0);
            data.writeInt(trackAllocation ? 1 : 0);
            data.writeInt(restrictedBackupMode ? 1 : 0);
            data.writeInt(persistent ? 1 : 0);
            config.writeToParcel(data, 0);
            compatInfo.writeToParcel(data, 0);
            data.writeMap(services);
            data.writeBundle(coreSettings);
            //见[2.2]
            mRemote.transact(BIND_APPLICATION_TRANSACTION, data, null,
                    IBinder.FLAG_ONEWAY);
            data.recycle();
        }
    

    2.2 ApplicationThreadProxy代理的是 ActivityThread.ApplicationThread类,上面的mRemote.transact(BIND_APPLICATION_TRANSACTION, data, null,IBinder.FLAG_ONEWAY)会回调ApplicationThread的父类ApplicationThreadNative的Ontransact方法。

        @Override
        public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
                throws RemoteException {
            switch (code) {
                case BIND_APPLICATION_TRANSACTION: {
                    data.enforceInterface(IApplicationThread.descriptor);
                    String packageName = data.readString();
                    ApplicationInfo info =
                            ApplicationInfo.CREATOR.createFromParcel(data);
                    List<ProviderInfo> providers =
                            data.createTypedArrayList(ProviderInfo.CREATOR);
                    ComponentName testName = (data.readInt() != 0)
                            ? new ComponentName(data) : null;
                    ProfilerInfo profilerInfo = data.readInt() != 0
                            ? ProfilerInfo.CREATOR.createFromParcel(data) : null;
                    Bundle testArgs = data.readBundle();
                    IBinder binder = data.readStrongBinder();
                    IInstrumentationWatcher testWatcher = IInstrumentationWatcher.Stub.asInterface(binder);
                    binder = data.readStrongBinder();
                    IUiAutomationConnection uiAutomationConnection =
                            IUiAutomationConnection.Stub.asInterface(binder);
                    int testMode = data.readInt();
                    boolean enableBinderTracking = data.readInt() != 0;
                    boolean trackAllocation = data.readInt() != 0;
                    boolean restrictedBackupMode = (data.readInt() != 0);
                    boolean persistent = (data.readInt() != 0);
                    Configuration config = Configuration.CREATOR.createFromParcel(data);
                    CompatibilityInfo compatInfo = CompatibilityInfo.CREATOR.createFromParcel(data);
                    HashMap<String, IBinder> services = data.readHashMap(null);
                    Bundle coreSettings = data.readBundle();
                    //[见2.3]
                    bindApplication(packageName, info, providers, testName, profilerInfo, testArgs,
                            testWatcher, uiAutomationConnection, testMode, enableBinderTracking,
                            trackAllocation, restrictedBackupMode, persistent, config, compatInfo, services,
                            coreSettings);
                    return true;
                }
            }
        }
    

    2.3 ApplicationThreadNative没有实现bindApplication方法,真正的实现是在ApplicationThreadNative的子类ActivityThread#ApplicationThread

       public final void bindApplication(String processName, ApplicationInfo appInfo,
                    List<ProviderInfo> providers, ComponentName instrumentationName,
                    ProfilerInfo profilerInfo, Bundle instrumentationArgs,
                    IInstrumentationWatcher instrumentationWatcher,
                    IUiAutomationConnection instrumentationUiConnection, int debugMode,
                    boolean enableBinderTracking, boolean trackAllocation,
                    boolean isRestrictedBackupMode, boolean persistent, Configuration config,
                    CompatibilityInfo compatInfo, Map<String, IBinder> services, Bundle coreSettings) {
    
                if (services != null) {
                    // Setup the service cache in the ServiceManager
                    ServiceManager.initServiceCache(services);
                }
    
                setCoreSettings(coreSettings);
    
                AppBindData data = new AppBindData();
                data.processName = processName;
                data.appInfo = appInfo;
                data.providers = providers;
                data.instrumentationName = instrumentationName;
                data.instrumentationArgs = instrumentationArgs;
                data.instrumentationWatcher = instrumentationWatcher;
                data.instrumentationUiAutomationConnection = instrumentationUiConnection;
                data.debugMode = debugMode;
                data.enableBinderTracking = enableBinderTracking;
                data.trackAllocation = trackAllocation;
                data.restrictedBackupMode = isRestrictedBackupMode;
                data.persistent = persistent;
                data.config = config;
                data.compatInfo = compatInfo;
                data.initProfilerInfo = profilerInfo;
                //[见2.4]
                sendMessage(H.BIND_APPLICATION, data);
            }
    

    2.4 ActivityThread#H

        public void handleMessage(Message msg) {
         ...
            case BIND_APPLICATION:
            AppBindData data = (AppBindData) msg.obj;
            //[见2.5]
            handleBindApplication(data);
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            break;
         ...
        }
    

    2.5 ActivityThread.handleBindApplication

     private void handleBindApplication(AppBindData data) {
            ...
            mBoundApplication = data;
            mConfiguration = new Configuration(data.config);
            mCompatConfiguration = new Configuration(data.config);
    
            mProfiler = new Profiler();
            if (data.initProfilerInfo != null) {
                mProfiler.profileFile = data.initProfilerInfo.profileFile;
                mProfiler.profileFd = data.initProfilerInfo.profileFd;
                mProfiler.samplingInterval = data.initProfilerInfo.samplingInterval;
                mProfiler.autoStopProfiler = data.initProfilerInfo.autoStopProfiler;
            }
    
            // send up app name; do this *before* waiting for debugger
            Process.setArgV0(data.processName);
            android.ddm.DdmHandleAppName.setAppName(data.processName,
                    UserHandle.myUserId());
    
            if (data.persistent) {
                if (!ActivityManager.isHighEndGfx()) {
                    ThreadedRenderer.disable(false);
                }
            }
    
            if (mProfiler.profileFd != null) {
                mProfiler.startProfiling();
            }
    
            Message.updateCheckRecycle(data.appInfo.targetSdkVersion);
    
            TimeZone.setDefault(null);
    
            LocaleList.setDefault(data.config.getLocales());
    
            synchronized (mResourcesManager) {
                mResourcesManager.applyConfigurationToResourcesLocked(data.config, data.compatInfo);
                mCurDefaultDisplayDpi = data.config.densityDpi;
    
                // This calls mResourcesManager so keep it within the synchronized block.
                applyCompatConfiguration(mCurDefaultDisplayDpi);
            }
    
            data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
    
            ...
    
            // Instrumentation info affects the class loader, so load it before
            // setting up the app context.
            final InstrumentationInfo ii;
            if (data.instrumentationName != null) {
                try {
                    ii = new ApplicationPackageManager(null, getPackageManager())
                            .getInstrumentationInfo(data.instrumentationName, 0);
                } catch (PackageManager.NameNotFoundException e) {
                    throw new RuntimeException(
                            "Unable to find instrumentation info for: " + data.instrumentationName);
                }
    
                mInstrumentationPackageName = ii.packageName;
                mInstrumentationAppDir = ii.sourceDir;
                mInstrumentationSplitAppDirs = ii.splitSourceDirs;
                mInstrumentationLibDir = getInstrumentationLibrary(data.appInfo, ii);
                mInstrumentedAppDir = data.info.getAppDir();
                mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
                mInstrumentedLibDir = data.info.getLibDir();
            } else {
                ii = null;
            }
    
            final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
            updateLocaleListFromAppContext(appContext,
                    mResourcesManager.getConfiguration().getLocales());
    
            if (!Process.isIsolated() && !"android".equals(appContext.getPackageName())) {
                final File cacheDir = appContext.getCacheDir();
                if (cacheDir != null) {
                    // Provide a usable directory for temporary files
                    System.setProperty("java.io.tmpdir", cacheDir.getAbsolutePath());
                } else {
                    Log.v(TAG, "Unable to initialize \"java.io.tmpdir\" property "
                            + "due to missing cache directory");
                }
    
                final Context deviceContext = appContext.createDeviceProtectedStorageContext();
                final File codeCacheDir = deviceContext.getCodeCacheDir();
                if (codeCacheDir != null) {
                    setupGraphicsSupport(data.info, codeCacheDir);
                } else {
                    Log.e(TAG, "Unable to setupGraphicsSupport due to missing code-cache directory");
                }
            }
    
            NetworkSecurityConfigProvider.install(appContext);
    
            // Continue loading instrumentation.
            if (ii != null) {
                final ApplicationInfo instrApp = new ApplicationInfo();
                ii.copyTo(instrApp);
                instrApp.initForUser(UserHandle.myUserId());
                final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
                        appContext.getClassLoader(), false, true, false);
                final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
    
                try {
                    final ClassLoader cl = instrContext.getClassLoader();
                    mInstrumentation = (Instrumentation)
                            cl.loadClass(data.instrumentationName.getClassName()).newInstance();
                } catch (Exception e) {
                    throw new RuntimeException(
                            "Unable to instantiate instrumentation "
                                    + data.instrumentationName + ": " + e.toString(), e);
                }
    
                final ComponentName component = new ComponentName(ii.packageName, ii.name);
                mInstrumentation.init(this, instrContext, appContext, component,
                        data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
    
                if (mProfiler.profileFile != null && !ii.handleProfiling
                        && mProfiler.profileFd == null) {
                    mProfiler.handlingProfiling = true;
                    final File file = new File(mProfiler.profileFile);
                    file.getParentFile().mkdirs();
                    Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
                }
            } else {
                mInstrumentation = new Instrumentation();
            }
    
            if ((data.appInfo.flags & ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
                dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
            } else {
                dalvik.system.VMRuntime.getRuntime().clampGrowthLimit();
            }
    
            final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
            try {
                //[见2.6]
                Application app = data.info.makeApplication(data.restrictedBackupMode, null);
                mInitialApplication = app;
    
                if (!data.restrictedBackupMode) {
                    if (!ArrayUtils.isEmpty(data.providers)) {
                        installContentProviders(app, data.providers);
                        mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10 * 1000);
                    }
                }
    
                try {
                    mInstrumentation.onCreate(data.instrumentationArgs);
                } catch (Exception e) {
                    throw new RuntimeException(
                            "Exception thrown in onCreate() of "
                                    + data.instrumentationName + ": " + e.toString(), e);
                }
    
                try {
                    mInstrumentation.callApplicationOnCreate(app);
                } catch (Exception e) {
                    if (!mInstrumentation.onException(app, e)) {
                        throw new RuntimeException(
                                "Unable to create application " + app.getClass().getName()
                                        + ": " + e.toString(), e);
                    }
                }
            } finally {
                StrictMode.setThreadPolicy(savedPolicy);
            }
        }
    

    2.6 LoadedApk.makeApplication

        public Application makeApplication(boolean forceDefaultAppClass,
                                           Instrumentation instrumentation) {
            ...
            Application app = null;
    
            String appClass = mApplicationInfo.className;
            if (forceDefaultAppClass || (appClass == null)) {
                appClass = "android.app.Application";
            }
    
            try {
                java.lang.ClassLoader cl = getClassLoader();
                if (!mPackageName.equals("android")) {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
                            "initializeJavaContextClassLoader");
                    initializeJavaContextClassLoader();
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                }
                ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
                app = mActivityThread.mInstrumentation.newApplication(
                        cl, appClass, appContext);
                appContext.setOuterContext(app);
            } catch (Exception e) {
                if (!mActivityThread.mInstrumentation.onException(app, e)) {
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    throw new RuntimeException(
                            "Unable to instantiate application " + appClass
                                    + ": " + e.toString(), e);
                }
            }
            mActivityThread.mAllApplications.add(app);
            mApplication = app;
    
            if (instrumentation != null) {
                try {
                    //这个方法就会调用Application的Oncreate()方法
                    instrumentation.callApplicationOnCreate(app);
                } catch (Exception e) {
                    if (!instrumentation.onException(app, e)) {
                        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                        throw new RuntimeException(
                                "Unable to create application " + app.getClass().getName()
                                        + ": " + e.toString(), e);
                    }
                }
            }
    
            // Rewrite the R 'constants' for all library apks.
            SparseArray<String> packageIdentifiers = getAssets(mActivityThread)
                    .getAssignedPackageIdentifiers();
            final int N = packageIdentifiers.size();
            for (int i = 0; i < N; i++) {
                final int id = packageIdentifiers.keyAt(i);
                if (id == 0x01 || id == 0x7f) {
                    continue;
                }
    
                rewriteRValues(getClassLoader(), packageIdentifiers.valueAt(i), id);
            }
    
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    
            return app;
        }
    

    startActivity总结

    流程[1.1-1.5]:这几步流程都是运行在app进程中,startActivity最终调用的是ActivityManagerService服务的Client代表ActivityManagerProxy,通过这个类进入到system_server进程(AMS相应的Server端),调用server端的方法.

    流程[1.6-1.26]:运行在system_server系统进程中,是ActivityManagerService中最为复杂的部分

    流程[1.16]:当目标进程已存在则直接进入流程[1.25],当进程不存在(即通过Launcher界面点击启动)则创建进程,经过层层调用还是会进入流程[1.25];
    流程[1.26]:system_server进程利用的ApplicationThreadProxy(Binder Client),经过Binder通信,程序接下来进入目标进程。

    流程[1.27-1.31]:运行在目标进程,通过Handler消息机制,该进程中的Binder线程向主线程发送H.LAUNCH_ACTIVITY,最终会通过反射创建目标Activity,然后进入onCreate()生命周期。

    流程[2.1-2.6]:开始读取android清单文件,创建Application,并调用Application的onCreate方法

    启动流程:

    点击桌面App图标,Launcher进程采用Binder IPC向system_server进程发起startActivity请求;

    1,如果是冷启动,即应用进程不存在。

    ​ 1.1: system_server进程接收到请求后,向zygote进程发送创建进程的请求;

    ​ 1.2: Zygote进程fork出新的子进程,即App进程;

    ​ 1.3: App进程,通过Binder IPC向sytem_server进程发起attachApplication请求;

    ​ 1.4: system_server进程在收到请求后,进行一系列准备工作后通过binder IPC向App进程发送bindApplication请求,

    ​ 1.5: App进程的binder线程(ApplicationThread)在收到请求后,通过handler向主线程发送BIND_APPLICATION消息;

    ​ 1.6: 主线程在收到Message后,通过解析清单文件,反射创建目标Application,并回调Application.onCreate()方法。

    ​ 1.7: 回到1.4,创建完了应用进程之后,system_server再通过binder IPC向App进程发送scheduleLaunchActivity请求;

    ​ 1.8:App进程的binder线程(ApplicationThread)在收到请求后,通过handler向主线程发送LAUNCH_ACTIVITY消息;

    ​ 1.9:主线程在收到Message后,通过反射机制创建目标Activity,并回调Activity.onCreate()等方法。

    2,如果是热启动,即应用进程已经存在
    ​ 2.1,system_server进程在收到请求后,进行一系列准备工作后,再通过binder IPC向App进程发送scheduleLaunchActivity请求;
    ​ 2.2,App进程的binder线程(ApplicationThread)在收到请求后,通过handler向主线程发送LAUNCH_ACTIVITY消息;
    ​ 2.3,主线程在收到Message后,通过反射机制创建目标Activity,并回调Activity.onCreate()等方法。

    相关文章

      网友评论

          本文标题:通过源码分析Activity和Applicaiton的启动流程(

          本文链接:https://www.haomeiwen.com/subject/kdjtmhtx.html