美文网首页Android开发Android开发经验谈
【Android】一张图看懂Activity的启动流程

【Android】一张图看懂Activity的启动流程

作者: 寒小枫 | 来源:发表于2019-03-07 20:33 被阅读9次

    在Android中,Activity这家伙可以说是非常重要的,无时无刻不在和它打交道,本篇不讲解activity的基本使用,而是对Activity的启动流程做个记录,但不深入分析源码实现细节,开始之前,先上一张图来总体感受一下Activity的启动流程:

    Activity的启动流程图.png
    就像我们平时启动一个Activity那样,我们从startActivity(intent)开始。

    startActivity

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

    嗯,最终调用了startActivityForResult,这个我们也很熟悉:

        public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
            startActivityForResult(intent, requestCode, null);
        }
    
        public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
                @Nullable Bundle options) {
            if (mParent == null) {
                options = transferSpringboardActivityOptions(options);
                //核心代码
                Instrumentation.ActivityResult ar =
                    mInstrumentation.execStartActivity(
                        this, mMainThread.getApplicationThread(), mToken, this,
                        intent, requestCode, options);
            } else {
                if (options != null) {
                    mParent.startActivityFromChild(this, intent, requestCode, options);
                } else {
                    mParent.startActivityFromChild(this, intent, requestCode);
                }
            }
        }
    
    

    核心代码就是mInstrumentation.execStartActivity,activity的启动过程委托给了Instrumentation类,看看execStartActivity的参数,mMainThread.getApplicationThread()返回的是ApplicationThread对象,它是ActivityThread的内部类,继承自IApplicationThread.Stub,这个是不是很面熟,它是IBinder对象,用来远程调用ActivityManagerService里的方法.

    Instrumentation

    接着看下execStartActivity方法:

        public ActivityResult execStartActivity(
                Context who, IBinder contextThread, IBinder token, Activity target,
                Intent intent, int requestCode, Bundle options) {
            ···
            try {
                //此处开始IPC过程,远程调用ActivityManagerService(AMS)的startActivity
                int result = ActivityManager.getService()
                    .startActivity(whoThread, who.getBasePackageName(), intent,
                            intent.resolveTypeIfNeeded(who.getContentResolver()),
                            token, target != null ? target.mEmbeddedID : null,
                            requestCode, 0, null, options);
                checkStartActivityResult(result, intent);
            } 
            ···
            return null;
        }
    

    上面ActivityManager.getService()返回的是IActivityManager接口,它是aidl定义的接口类,用于进程间通信,它的实现类就是ActivityManagerService,接着看startActivity方法。

    ActivityManagerService

        @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);
            return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                    resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                    profilerInfo, null, null, bOptions, false, userId, null, null,
                    "startActivityAsUser");
        }
    

    这里启动请求又委托给了ActivityStarter类,ActivityStarter封装了一个activity启动的过程,看下它的startActivityMayWait方法:

        final int startActivityMayWait() {
                ···
                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, reason);
                ···
                return res;
            }
        }
    
        int startActivityLocked() {
            //这里又调用了自身的startActivity方法
            mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                    aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                    callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                    options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                    container, inTask);
            return mLastStartActivityResult;
        }
    
        private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
            //此处省略一大堆代码
            return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,
                    options, inTask, outActivity);
        }
    
        private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity) {
            int result = START_CANCELED;
            try {
                mService.mWindowManager.deferSurfaceLayout();
                //接着调用startActivityUnchecked
                result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                        startFlags, doResume, options, inTask, outActivity);
            } finally {
                // 如果启动 Activity 没有成功, 从 task 中移除 Activity       
                if (!ActivityManager.isStartResultSuccessful(result)
                        && mStartActivity.getTask() != null) {
                    mStartActivity.getTask().removeActivity(mStartActivity);
                }
                mService.mWindowManager.continueSurfaceLayout();
            }
            return result;
        }
    

    然后调用了startActivityUnchecked方法:

        private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity) {
            //初始化状态
            setInitialState();
            //计算launch flags
            computeLaunchingTaskFlags();
            //计算源task
            computeSourceStack();
            // 获取是否存在可以复用的 Activity,根据 flags 和 launchMode
            ActivityRecord reusedActivity = getReusableIntentActivity();
    
            if (reusedActivity != null) {
                  //存在可复用的 Activity,则走此逻辑
            }
    
            if (mStartActivity.packageName == null) {
                return START_CLASS_NOT_FOUND;
            }
    
            // 如果启动的 Activity 与当前 Task 顶部的 Activity 相同,判断是否需要继续启动新的 Activity
            final boolean dontStart = top != null && mStartActivity.resultTo == null
                    && top.realActivity.equals(mStartActivity.realActivity)
                    && top.userId == mStartActivity.userId
                    && top.app != null && top.app.thread != null
                    && ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
                    || mLaunchSingleTop || mLaunchSingleTask);
            if (dontStart) {
                //传递一个新的 Intent 到 onNewIntent
                top.deliverNewIntentLocked(
                        mCallingUid, mStartActivity.intent, mStartActivity.launchedFromPackage);
                return START_DELIVERED_TO_TOP;
            }
            ······
            if (mDoResume) {
                final ActivityRecord topTaskActivity =
                        mStartActivity.getTask().topRunningActivityLocked();
                if (!mTargetStack.isFocusable()
                        || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                        && mStartActivity != topTaskActivity)) {
                    mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
                    mWindowManager.executeAppTransition();
                } else {
                    //恢复目标Task
                    mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                            mOptions);
                }
            } else {
                mTargetStack.addRecentActivityLocked(mStartActivity);
            }
    
            return START_SUCCESS;
        }
    

    此时执行流程从ActivityStarter转移到了ActivityStackSupervisor类的resumeFocusedStackTopActivityLocked方法:

    boolean resumeFocusedStackTopActivityLocked(
                ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
            if (targetStack != null && isFocusedStack(targetStack)) {
                //然后又转移到了ActivityStack类
                return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
            }
            return false;
        }
    

    ActivityStack

        boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
            boolean result = false;
            try {
                mStackSupervisor.inResumeTopActivity = true;
                //调用自身resumeTopActivityInnerLocked
                result = resumeTopActivityInnerLocked(prev, options);
            } finally {
                mStackSupervisor.inResumeTopActivity = false;
            }
    
            return result;
        }
    
        private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
            ······ 
            mStackSupervisor.startSpecificActivityLocked(next, true, true);
            ······
            return true;
        }
    

    ActivityStackSuperVisor

    此时流程走到了ActivityStackSuperVisor类,调用了startSpecificActivityLocked方法:

    void startSpecificActivityLocked(ActivityRecord r,
                boolean andResume, boolean checkConfig) {
    
            if (app != null && app.thread != null) {
                try {
                    realStartActivityLocked(r, app, andResume, checkConfig);
                    return;
                } 
            }
        }
    
        final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
                boolean andResume, boolean checkConfig) throws RemoteException {
            ······
            try {
                //此处调用了ApplicationThread类,它是ActivityThread的内部类
                app.thread.scheduleLaunchActivity();
            } catch (RemoteException e) {
                throw e;
            }
            ······
            return true;
        }
    
    

    ActivityThread

    Activity启动到现在终于走到了ActivityThread类中,此时调用了ActivityThread的内部类ApplicationThread的scheduleLaunchActivity方法,我们来看下:

        private class ApplicationThread extends IApplicationThread.Stub {
            private static final String DB_INFO_FORMAT = "  %8s %8s %14s %14s  %s";
    
            private int mLastProcessState = -1;
    
            public final void schedulePauseActivity(IBinder token, boolean finished,
                    boolean userLeaving, int configChanges, boolean dontReport) {
                int seq = getLifecycleSeq();
                sendMessage(finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,token,(userLeaving ? USER_LEAVING : 0) | (dontReport ? DONT_REPORT : 0),configChanges,seq);
            }
    
            public final void scheduleStopActivity(IBinder token, boolean showWindow,
                    int configChanges) {
                int seq = getLifecycleSeq();
                sendMessage(showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,token, 0, configChanges, seq);
            }
    
            public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
                sendMessage(showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,token);
            }
    
            public final void scheduleResumeActivity(IBinder token, int processState,
                    boolean isForward, Bundle resumeArgs) {
                sendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0, 0, seq);
            }
    
            @Override
            public final void scheduleLaunchActivity() {
                ······
                sendMessage(H.LAUNCH_ACTIVITY, r);
            }
            ······
        }
    

    可以看到ApplicationThread里面很多熟悉的方法,stop,pauseActivity等等,而这些方法的内部基本都是sendMessage的方式发送了一个消息,我们来具体看下scheduleLaunchActivity方法:

            @Override
            public final void scheduleLaunchActivity() {
                //通过Handler发送消息LAUNCH_ACTIVITY
                sendMessage(H.LAUNCH_ACTIVITY, r);
            }
    

    看下H是什么鬼?

    private class H extends Handler {
            public static final int LAUNCH_ACTIVITY         = 100;
            public static final int PAUSE_ACTIVITY          = 101;
            public static final int STOP_ACTIVITY_SHOW      = 103;
            public static final int STOP_ACTIVITY_HIDE      = 104;
            public static final int SHOW_WINDOW             = 105;
            public static final int HIDE_WINDOW             = 106;
            public static final int RESUME_ACTIVITY         = 107;
            ······
            String codeToString(int code) {
                if (DEBUG_MESSAGES) {
                    switch (code) {
                        case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
                        case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
                        case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
                        case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
                        case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
                        case SHOW_WINDOW: return "SHOW_WINDOW";
                    }
                }
                return Integer.toString(code);
            }
            public void handleMessage(Message msg) {
                if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
                switch (msg.what) {
                    case LAUNCH_ACTIVITY: {
                        final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
                        r.packageInfo = getPackageInfoNoCheck(
                                r.activityInfo.applicationInfo, r.compatInfo);
                        handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
                    } break;
                    case PAUSE_ACTIVITY: {
                        SomeArgs args = (SomeArgs) msg.obj;
                        handlePauseActivity((IBinder) args.arg1, false,
                                (args.argi1 & USER_LEAVING) != 0, args.argi2,
                                (args.argi1 & DONT_REPORT) != 0, args.argi3);
                        maybeSnapshot();
                    } break;
                    case STOP_ACTIVITY_SHOW: {
                        SomeArgs args = (SomeArgs) msg.obj;
                        handleStopActivity((IBinder) args.arg1, true, args.argi2, args.argi3);
                    } break;
                    case RESUME_ACTIVITY:
                        SomeArgs args = (SomeArgs) msg.obj;
                        handleResumeActivity((IBinder) args.arg1, true, args.argi1 != 0, true,
                                args.argi3, "RESUME_ACTIVITY");
                        break;
                    case DESTROY_ACTIVITY:
                        handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
                                msg.arg2, false);
                        break;
                }
            }
        }
    

    你们有看错H就是ActivityThread类定义的Handler对象,用于接收ApplicationThread发送来的handler消息,对Activity的生命周期等进行处理,可以看到上面发送的LAUNCH_ACTIVITY最终执行了handleLaunchActivity方法:

        private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
            //关键代码,里面进行了Activity的创建。onCreate和onStart的调用
            Activity a = performLaunchActivity(r, customIntent);
    
            if (a != null) {
                r.createdConfig = new Configuration(mConfiguration);
                reportSizeConfigurations(r);
                Bundle oldState = r.state;
                //关键方法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 {
                    ActivityManager.getService()
                        .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                                Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
                } catch (RemoteException ex) {
                    throw ex.rethrowFromSystemServer();
                }
            }
        }
    

    先来看下performLaunchActivity里面到底干了啥:

        private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
      
            //创建上下文Context         --->A
            ContextImpl appContext = createBaseContextForActivity(r);
            Activity activity = null;
            try {
                java.lang.ClassLoader cl = appContext.getClassLoader();
                //创建Activity对象         --->B
                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) {
            }
    
            try {
                //获取Application对象            --->C
                Application app = r.packageInfo.makeApplication(false, mInstrumentation);
    
                if (activity != null) {
                    //关键方法,activity的attach方法      --->D
                    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, r.configCallback);
    
                    if (customIntent != null) {
                        activity.mIntent = customIntent;
                    }
                   
                    //调用onCreate方法           --->E
                    if (r.isPersistable()) {
                        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                    } else {
                        mInstrumentation.callActivityOnCreate(activity, r.state);
                    }
                    //调用onStart方法         --->F
                    if (!r.activity.mFinished) {
                        activity.performStart();
                        r.stopped = false;
                    }
                    //调用onRestoreInstanceState方法
                    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);
                        }
                    }
                }
                r.paused = true;
    
                mActivities.put(r.token, r);
    
            } catch (SuperNotCalledException e) {
                throw e;
            } 
    
            return activity;
        }
    
    

    A处代码创建了上下文ContextImpl,它是Context的子类,B处代码Instrumentation的newActivity方法创建了Activity对象:

        public Activity newActivity(ClassLoader cl, String className,
                Intent intent)
                throws InstantiationException, IllegalAccessException,
                ClassNotFoundException {
            return (Activity)cl.loadClass(className).newInstance();
        }
    

    C处的代码调用了LoadedApk类中的makeApplication方法:

        public Application makeApplication(boolean forceDefaultAppClass,
                Instrumentation instrumentation) {
            //已存在,直接返回,所以Application是单例
            if (mApplication != null) {
                return mApplication;
            }
            //没有就创建
            Application app = null;
             app = mActivityThread.mInstrumentation.newApplication(
                        cl, appClass, appContext);
            mApplication = app;
    
            if (instrumentation != null) {
                try {
                    //调用Application的onCreate方法
                    instrumentation.callApplicationOnCreate(app);
                } catch (Exception e) {
                }
            }
    
            return app;
        }
    

    D处调用了activity的attach方法,这个大家应该很熟悉吧,简单回顾一下:

    final void attach() {
            //创建PhoneWindow对象
            mWindow = new PhoneWindow(this, window, activityConfigCallback);
            //绑定WindowManager到mWindow对象上
            mWindow.setWindowManager(
                    (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
                    mToken, mComponent.flattenToString(),
                    (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
            mWindowManager = mWindow.getWindowManager();
        }
    

    E处调用了Instrumentation类的callActivityOnCreate方法,这里就是调用Activity onCreate方法的地方了:

        public void callActivityOnCreate(Activity activity, Bundle icicle) {
            prePerformCreate(activity);
            activity.performCreate(icicle);
            postPerformCreate(activity);
        }
    
        //接着调用Activity的performCreate方法:
        final void performCreate(Bundle icicle) {
            restoreHasCurrentPermissionRequest(icicle);
            //终于看到它了
            onCreate(icicle);
            mActivityTransitionState.readState(icicle);
            performCreateCommon();
        }
    
    

    F处调用了Activity的performStart()方法:

        final void performStart() {
            //调用了Instrumentation的callActivityOnStart方法
            mInstrumentation.callActivityOnStart(this);
            ·····
        }
    
        //Instrumentation的callActivityOnStart代码,最终调用了Activity的onStart方法
        public void callActivityOnStart(Activity activity) {
            activity.onStart();
        }
    

    再次回到handleLaunchActivity方法,执行完performLaunchActivity会去执行handleResumeActivity方法:

        final void handleResumeActivity() {
            //执行performResumeActivity
            r = performResumeActivity(token, clearHide, reason);
        }
    
        public final ActivityClientRecord performResumeActivity(IBinder token,
                boolean clearHide, String reason) {
            ActivityClientRecord r = mActivities.get(token);
            if (r != null && !r.activity.mFinished) {
                try {
                    //这里最终调用了Activity的onResume()方法
                    r.activity.performResume();  
                } catch (Exception e) {
                    
                }
            }
            return r;
        }
    

    至此,Activity终于从startActivity经过层层调用执行了我们熟悉的onCreate,onStart,onResume方法,不多说了,现在Activity已经起来了,那么onPause是什么时候调用的呢?

    1.onPause是什么时候调用的呢?

    我们在上面的分析Activity的启动流程的时候,说到了ActivityStack类里的一个方法resumeTopActivityUncheckedLocked,它内部调用了startPausingLocked方法:

    final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
                ActivityRecord resuming, boolean pauseImmediately) {
            
            ActivityRecord prev = mResumedActivity;
            if (prev.app != null && prev.app.thread != null) {
                try {
                    //关键代码schedulePauseActivity
                    prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
                            userLeaving, prev.configChangeFlags, pauseImmediately);
                } catch (Exception e) {
                }
            }
        }
    

    看prev.app.thread.schedulePauseActivity,这里的thread是IApplicationThread类型,这个熟悉吧,它的实现类就是ActivityThread的内部类ApplicationThread,调用了它的schedulePauseActivity:

        public final void schedulePauseActivity(IBinder token, boolean finished,
                    boolean userLeaving, int configChanges, boolean dontReport) {
                int seq = getLifecycleSeq();
                sendMessage(H.PAUSE_ACTIVITY);
            }
    

    到这里就和上面流程同一套路了,就不继续跟踪代码了,感兴趣的可以继续跟踪代码查看。

    2.App进程是何时启动的?

    在上面的分析过程中,ActivityStackSuperVisor这个类大家应该见过吧,它有一个startSpecificActivityLocked方法如下:

    void startSpecificActivityLocked();
            if (app != null && app.thread != null) {
                try {
                    // 如果进程已存在,则通知进程启动组件
                    realStartActivityLocked(r, app, andResume, checkConfig);
                    return;
                } catch (RemoteException e) {
                    Slog.w(TAG, "Exception when starting activity "
                            + r.intent.getComponent().flattenToShortString(), e);
                }
            }
            //注意这里,如果进程不存在,则进行创建进程的操作
            mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                    "activity", r.intent.getComponent(), false, false, true);
        }
    
    

    这里的mService就是AMS,调用了它的startProcessLocked方法:

        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,null , null, null ,null );
        }
    
    
        final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
                boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
                boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
                String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
            long startTime = SystemClock.elapsedRealtime();
            ProcessRecord app;
            //继续跟踪代码
            startProcessLocked(
                    app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);
            return (app.pid != 0) ? app : null;
        }
    
    private final void startProcessLocked(ProcessRecord app, String hostingType,
                String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
                ProcessStartResult startResult;
                if (hostingType.equals("webview_service")) {
                    startResult = startWebView(entryPoint,
                            app.processName, uid, uid, gids, debugFlags, mountExternal,
                            app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                            app.info.dataDir, null, entryPointArgs);
                } else {
                    //这里就是具体创建进程的地方了,有兴趣的可以继续追踪代码查看
                    startResult = Process.start(entryPoint,
                            app.processName, uid, uid, gids, debugFlags, mountExternal,
                            app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                            app.info.dataDir, invokeWith, entryPointArgs);
                }
        }
    
    

    Process.start就是具体创建进程的地方了,有兴趣的可以继续追踪代码查看。

    3.onStop方法是何时调用的?

    如果我们从ActivityA启动ActivityB,onStop方法是何时调用的呢?其实也隐藏在上面的代码中,在handleResumeActivity方法中有这个一段代码:

        final void handleResumeActivity(IBinder token,
                boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
            //执行新启动Activity的onResume方法
            r = performResumeActivity(token, clearHide, reason);
    
            if (r != null) {
                final Activity a = r.activity;
                if (!r.onlyLocalRequest) {
                    r.nextIdle = mNewActivities;
                    mNewActivities = r;
                    //注意这里的代码
                    Looper.myQueue().addIdleHandler(new Idler());
                }
                r.onlyLocalRequest = false;
            } else {
                try {
                    ActivityManager.getService()
                        .finishActivity(token, Activity.RESULT_CANCELED, null,
                                Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
                } 
            }
        }
    

    Looper.myQueue().addIdleHandler(new Idler()),这一句代码我们跟踪下,看看它干了啥,看着好像很简单,往MessageQueue中add了一个addIdleHandler对象,看下Idler这个类:

      private class Idler implements MessageQueue.IdleHandler {
            @Override
            public final boolean queueIdle() {
                ActivityClientRecord a = mNewActivities;
                boolean stopProfiling = false;
    
                if (a != null) {
                    IActivityManager am = ActivityManager.getService();
                    ActivityClientRecord prev;
                    do {
                        if (a.activity != null && !a.activity.mFinished) {
                            try {
                                //注意这一句
                                am.activityIdle(a.token, a.createdConfig, stopProfiling);
                            } catch (RemoteException ex) {
                                throw ex.rethrowFromSystemServer();
                            }
                        }
                        prev = a;
                        a = a.nextIdle;
                        prev.nextIdle = null;
                    } while (a != null);
                }
                return false;
            }
        }
    

    am.activityIdle,调用了AMS的activityIdle:

        @Override
        public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
            final long origId = Binder.clearCallingIdentity();
            synchronized (this) {
                ActivityStack stack = ActivityRecord.getStackLocked(token);
                if (stack != null) {
                    ActivityRecord r =
                            mStackSupervisor.activityIdleInternalLocked(token, false ,false , config);
                }
            }
            Binder.restoreCallingIdentity(origId);
        }
    
        //继续跟踪mStackSupervisor.activityIdleInternalLocked
        final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
                boolean processPausingActivities, Configuration config) {
            ········
            for (int i = 0; i < NS; i++) {
                r = stops.get(i);
                final ActivityStack stack = r.getStack();
                if (stack != null) {
                    if (r.finishing) {
                        //finish的逻辑
                        stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
                    } else {
                         //看这里
                        stack.stopActivityLocked(r);
                    }
                }
            }
            return r;
        }
    
        //继续追踪ActivityStack的stopActivityLocked方法:
        final void stopActivityLocked(ActivityRecord r) {
            if (r.app != null && r.app.thread != null) {
                adjustFocusedActivityStackLocked(r, "stopActivity");
                r.resumeKeyDispatchingLocked();
                try {
                    r.stopped = false;
                    r.state = STOPPING;
                    if (!r.visible) {
                        r.setVisible(false);
                    }
                    //这里大家应该就熟悉了吧
                    r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
                    if (mService.isSleepingOrShuttingDownLocked()) {
                        r.setSleeping(true);
                    }
                    Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
                    mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
                } catch (Exception e) {
                    r.stopped = true;
                    r.state = STOPPED;
                    if (r.deferRelaunchUntilPaused) {
                        destroyActivityLocked(r, true, "stop-except");
                    }
                }
            }
        }
    
    

    最后执行到了ApplicationThread类的scheduleStopActivity,发送sendMessage消息,交给ActivityThread去处理stop的逻辑,其他生命周期逻辑大同小异,此处不再列举。

    本文主要是熟悉Activity启动的整体流程,并未涉及太多细节,希望能给需要的人一些帮助,有错误欢迎指出。

    参考链接:
    1.https://juejin.im/entry/5abdcdea51882555784e114d
    2.从源码的角度看Activity是如何启动的
    3.App 启动过程
    4.Android开发艺术探索

    相关文章

      网友评论

        本文标题:【Android】一张图看懂Activity的启动流程

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