美文网首页
APP&Activity 启动流程(基于Android10)

APP&Activity 启动流程(基于Android10)

作者: 孙大硕 | 来源:发表于2021-08-14 13:48 被阅读0次

    Activity 启动流程听起来非常复杂,但实际上很多东西我们没必要完全掌握,只需要去大概理解原理和流程就行。

    名词解释
    zygote 意思为受精卵 为所有进程的父进程

    1. 流程的发起

    从startActivity开始看起

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

    最终调用的是 startActivityForResult

    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);
                if (ar != null) {
                    mMainThread.sendActivityResult(
                        mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                        ar.getResultData());
                }
              ...
            }
        }
    

    在这个方法里看到了久仰大名的Instrumentation 这个类是Application和Activity生命周期的关键,然后去看 execStartActivity

    int result = ActivityTaskManager.getService()
                    .startActivity(whoThread, who.getBasePackageName(), intent,
                            intent.resolveTypeIfNeeded(who.getContentResolver()),
                            token, target != null ? target.mEmbeddedID : null,
                            requestCode, 0, null, options);
    

    只挑了里面的关键部分,又看到了不得了的东西 ActivityTaskManager.getService(),看着好像另一个大名鼎鼎的ActivityManagerService 啊,看一下getService方法

     public static IActivityTaskManager getService() {
            return IActivityTaskManagerSingleton.get();
        }
    
        @UnsupportedAppUsage(trackingBug = 129726065)
        private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
                new Singleton<IActivityTaskManager>() {
                    @Override
                    protected IActivityTaskManager create() {
                        final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                        return IActivityTaskManager.Stub.asInterface(b);
                    }
                };
    

    但是这里拿到的不是ActivityManagerService
    而是**ActivityTaskManagerService **,然后再去调用它的 startActivityAsUser

      private int startActivityAsUser(IApplicationThread caller, String callingPackage,
                @Nullable String callingFeatureId, Intent intent, String resolvedType,
                IBinder resultTo, String resultWho, int requestCode, int startFlags,
                ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
            assertPackageMatchesCallingUid(callingPackage);
            enforceNotIsolatedCaller("startActivityAsUser");
    
            userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
                    Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
    
            // TODO: Switch to user app stacks here.
            return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
                    .setCaller(caller)
                    .setCallingPackage(callingPackage)
                    .setCallingFeatureId(callingFeatureId)
                    .setResolvedType(resolvedType)
                    .setResultTo(resultTo)
                    .setResultWho(resultWho)
                    .setRequestCode(requestCode)
                    .setStartFlags(startFlags)
                    .setProfilerInfo(profilerInfo)
                    .setActivityOptions(bOptions)
                    .setUserId(userId)
                    .execute();
    
        }
    

    到了这一层感觉就看不懂了,不知道的东西太多,就不深入探究了

    这就是第一步过程,应用进程调用ATMS系统进程发起打开Activity的请求,ATMS 是10.0才有的,分担了一些AMS的工作,其内部也有很多是调用AMS完成的。用一张图表示

    image.png

    从先在开始启动流程就进入到系统进程中了。

    2. 系统进程对创建Activity的处理

    2.1 ATMS 发起打开Activity或者是创建进程的请求

    image.png

    ActivityTaskManagerService 最终会执行 ActivityStarter.execute方法

    int execute() {
            try {
                // TODO(b/64750076): Look into passing request directly to these methods to allow
                // for transactional diffs and preprocessing.
                if (mRequest.mayWait) {
                    return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                            mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
                            mRequest.intent, mRequest.resolvedType,
                            mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                            mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                            mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                            mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                            mRequest.inTask, mRequest.reason,
                            mRequest.allowPendingRemoteAnimationRegistryLookup,
                            mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
                } else {
                    return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
                            mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
                            mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                            mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
                            mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
                            mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
                            mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
                            mRequest.outActivity, mRequest.inTask, mRequest.reason,
                            mRequest.allowPendingRemoteAnimationRegistryLookup,
                            mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
                }
            } finally {
                onExecutionComplete();
            }
        }
    

    上面这个分叉最终都会走到 startActivity
    里面又调用了startActivityUnchecked方法,之后调用RootActivityContainer的resumeFocusedStacksTopActivities方法。RootActivityContainer是Android10新增的类,分担了之前ActivityStackSupervisor的部分功能。接着跳转到ActivityStack的resumeTopActivityUncheckedLocked方法然后又调用resumeTopActivityInnerLocked,中间没有什么逻辑需要看的,所以就跳过了,直接看resumeTopActivityInnerLocked:

        private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
            ...
            boolean pausing = getDisplay().pauseBackStacks(userLeaving, next, false);
            if (mResumedActivity != null) {
                if (DEBUG_STATES) Slog.d(TAG_STATES,
                        "resumeTopActivityLocked: Pausing " + mResumedActivity);
                 // 暂停上一个Activity
                pausing |= startPausingLocked(userLeaving, false, next, false);
            }
            ...
            //这里next.attachedToProcess(),只有启动了的Activity才会返回true
            if (next.attachedToProcess()) {
                ...
                
                try {
                    final ClientTransaction transaction =
                            ClientTransaction.obtain(next.app.getThread(), next.appToken);
                    ...
                    //启动了的Activity就发送ResumeActivityItem事务给客户端了,后面会讲到
                    transaction.setLifecycleStateRequest(
                            ResumeActivityItem.obtain(next.app.getReportedProcState(),
                                    getDisplay().mDisplayContent.isNextTransitionForward()));
                    mService.getLifecycleManager().scheduleTransaction(transaction);
                   ....
                } catch (Exception e) {
                    ....
                    mStackSupervisor.startSpecificActivityLocked(next, true, false);
                    return true;
                }
                ....
            } else {
                ....
                if (SHOW_APP_STARTING_PREVIEW) {
                        //这里就是 冷启动时 出现白屏 的原因了:取根activity的主题背景 展示StartingWindow
                        next.showStartingWindow(null , false ,false);
                    }
                // 继续当前Activity,普通activity的正常启动 关注这里即可
                mStackSupervisor.startSpecificActivityLocked(next, true, true);
            }
            return true;
        }
    

    这里先暂停上个Activity,然后再进入到 ActivityStackSupervisor.startSpecificActivityLocked方法中

        void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
            // Is this activity's application already running?
            final WindowProcessController wpc =
                    mService.getProcessController(r.processName, r.info.applicationInfo.uid);
    
            boolean knownToBeDead = false;
            if (wpc != null && wpc.hasThread()) {
                try {
                    realStartActivityLocked(r, wpc, andResume, checkConfig);
                    return;
                } catch (RemoteException e) {
                    Slog.w(TAG, "Exception when starting activity "
                            + r.intent.getComponent().flattenToShortString(), e);
                }
                knownToBeDead = true;
            }
    
            ...
            
            try {
                if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
                    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
                            + r.processName);
                }
                // 上面的wpc != null && wpc.hasThread()不满足的话,说明没有进程,就会取创建进程
                final Message msg = PooledLambda.obtainMessage(
                        ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
                        r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
                mService.mH.sendMessage(msg);
            } finally {
                Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
            }
        }
    
    

    这里 会先判断进程有没创建,创建的话会进入 realStartActivityLocked,没开启的话会调用 ActivityManagerInternal.startProgress,下面我们先看进程以已经创建的情况

    2.2 在当前进程开启Activity

    当前进程指的是APP进程,不是系统进程
    进入realStartActivityLocked

        boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
                boolean andResume, boolean checkConfig) throws RemoteException {
        
                ...
    
                    // Create activity launch transaction.
                    final ClientTransaction clientTransaction = ClientTransaction.obtain(
                            proc.getThread(), r.appToken);
    
                    final DisplayContent dc = r.getDisplay().mDisplayContent;
                    clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                            System.identityHashCode(r), r.info,
                            // TODO: Have this take the merged configuration instead of separate global
                            // and override configs.
                            mergedConfiguration.getGlobalConfiguration(),
                            mergedConfiguration.getOverrideConfiguration(), r.compat,
                            r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
                            r.icicle, r.persistentState, results, newIntents,
                            dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                                    r.assistToken));
    
                    // Set desired final state.
                    final ActivityLifecycleItem lifecycleItem;
                    if (andResume) {
                        lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
                    } else {
                        lifecycleItem = PauseActivityItem.obtain();
                    }
                    clientTransaction.setLifecycleStateRequest(lifecycleItem);
    
                    // Schedule transaction.
                    mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    
                    ...
    
            return true;
        }
    
    

    中间有段代码如上,通过 ClientTransaction.obtain( proc.getThread(), r.appToken)获取了clientTransaction,其中参数proc.getThread()是IApplicationThread,就是前面提到的ApplicationThread在系统进程的代理。

    ClientTransaction是包含一系列的待客户端处理的事务的容器,客户端接收后取出事务并执行。

    接着看,使用clientTransaction.addCallback添加了LaunchActivityItem实例:

        //都是用来发送到客户端的
        private List<ClientTransactionItem> mActivityCallbacks;
        
        public void addCallback(ClientTransactionItem activityCallback) {
            if (mActivityCallbacks == null) {
                mActivityCallbacks = new ArrayList<>();
            }
            mActivityCallbacks.add(activityCallback);
        }
    

    LaunchActivityItem看名字就像是启动Activity的,走到这里只是把
    LaunchActivityItem保存了起来,那再回到realStartActivityLocked 中,接着调用了mService.getLifecycleManager().scheduleTransaction(clientTransaction),mService是ActivityTaskManagerService,getLifecycleManager()方法获取的是ClientLifecycleManager实例,它的scheduleTransaction方法如下:

        void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            final IApplicationThread client = transaction.getClient();
            transaction.schedule();
            if (!(client instanceof Binder)) {
                transaction.recycle();
            }
        }
    

    看一下 ClientTransaction.schedule();

        public void schedule() throws RemoteException {
            mClient.scheduleTransaction(this);
        }
    
    

    这个Client 就是ApplicationThread 下面启动进程的时候会讲到这个东西就是系统进程给APP进程通信的媒介,所以这一步就又回到APP进程了。

    2.3 回到APP进程 进行创建Activity的后续操作

    ApplicationThread 的scheduleTransaction 调用的是ActivityThread 的scheduleTransaction,是在它的父类ClientTransactionHandler中实现的:

        void scheduleTransaction(ClientTransaction transaction) {
            transaction.preExecute(this);
            sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
        }
    

    这里发送了一个消息,最终由ActivityThread的H(一个Handler)处理,为什么要使用Handler呢,因为scheduleTransaction方法是被系统进程调用的,跨进程的方法调用都发生在Binder的线程池中
    所以在这里要发送到主线程执行
    最终是这样执行的:

    case EXECUTE_TRANSACTION:
                        final ClientTransaction transaction = (ClientTransaction) msg.obj;
                        mTransactionExecutor.execute(transaction);
                        if (isSystem()) {
                            // Client transactions inside system process are recycled on the client side
                            // instead of ClientLifecycleManager to avoid being cleared before this
                            // message is handled.
                            transaction.recycle();
                        }
                        break;
    

    又交给了mTransactionExecutor这个对象处理,但是最终还是交给了ActivityThread 的 handleLaunchActivity。

    下面就进入到另一个核心部分,创建Activity和Activity生命周期的管理

    2.4 创建Activity以及Activity生命周期的管理

    进入handleLaunchActivity

        public Activity handleLaunchActivity(ActivityClientRecord r,
                PendingTransactionActions pendingActions, Intent customIntent) {
            ...
            final Activity a = performLaunchActivity(r, customIntent);
            ...
            return a;
        }
    

    继续跟performLaunchActivity方法,这里就是activity 启动的核心实现了:

        /**  activity 启动的核心实现. */
        private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
            //1、从ActivityClientRecord获取待启动的Activity的组件信息
            ActivityInfo aInfo = r.activityInfo;
            if (r.packageInfo == null) {
                r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                        Context.CONTEXT_INCLUDE_CODE);
            }
    
            ComponentName component = r.intent.getComponent();
            if (component == null) {
                component = r.intent.resolveActivity(
                    mInitialApplication.getPackageManager());
                r.intent.setComponent(component);
            }
    
            if (r.activityInfo.targetActivity != null) {
                component = new ComponentName(r.activityInfo.packageName,
                        r.activityInfo.targetActivity);
            }
            //创建ContextImpl对象
            ContextImpl appContext = createBaseContextForActivity(r);
            Activity activity = null;
            try {
                //2、创建activity实例
                java.lang.ClassLoader cl = appContext.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) {
                ..
            }
            try {
                //3、创建Application对象(如果没有的话)
                Application app = r.packageInfo.makeApplication(false, mInstrumentation);
                ...
                if (activity != null) {
                    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;
                    }
                    appContext.setOuterContext(activity);
                    
                    //4、attach方法为activity关联上下文环境
                    activity.attach(appContext, this, getInstrumentation(), r.token,
                            r.ident, app, r.intent, r.activityInfo, title, r.parent,
                            r.embeddedID, r.lastNonConfigurationInstances, config,
                            r.referrer, r.voiceInteractor, window, r.configCallback,
                            r.assistToken);
    
                    if (customIntent != null) {
                        activity.mIntent = customIntent;
                    }
                    r.lastNonConfigurationInstances = null;
                    checkAndBlockForNetworkAccess();
                    activity.mStartedActivity = false;
                    int theme = r.activityInfo.getThemeResource();
                    if (theme != 0) {
                        activity.setTheme(theme);
                    }
    
                    activity.mCalled = false;
                    
                    //5、调用生命周期onCreate
                    if (r.isPersistable()) {
                        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                    } else {
                        mInstrumentation.callActivityOnCreate(activity, r.state);
                    }
                    if (!activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onCreate()");
                    }
                    r.activity = activity;
                }
                r.setState(ON_CREATE);
                
                synchronized (mResourcesManager) {
                    mActivities.put(r.token, r);
                }
    
            } 
            ...
    
            return activity;
        }
    

    performLaunchActivity主要完成以下事情:

    从ActivityClientRecord获取待启动的Activity的组件信息
    通过mInstrumentation.newActivity方法使用类加载器创建activity实例
    通过LoadedApk的makeApplication方法创建Application对象,内部也是通过mInstrumentation使用类加载器,创建后就调用了instrumentation.callApplicationOnCreate方法,也就是Application的onCreate方法。
    创建ContextImpl对象并通过activity.attach方法对重要数据初始化,关联了Context的具体实现ContextImpl,attach方法内部还完成了window创建,这样Window接收到外部事件后就能传递给Activity了。
    调用Activity的onCreate方法,是通过 mInstrumentation.callActivityOnCreate方法完成,Activity就创建完成了。
    那onStart 和 onResume是什么时候调用的呢
    我们再来重新看看在ActivityStackSupervisor的realStartActivityLocked方法:

        boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
                boolean andResume, boolean checkConfig) throws RemoteException {
                ...
                    // Create activity launch transaction.
                    final ClientTransaction clientTransaction = ClientTransaction.obtain(
                            proc.getThread(), r.appToken);
    
                    final DisplayContent dc = r.getDisplay().mDisplayContent;
                    clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                            System.identityHashCode(r), r.info,
                            mergedConfiguration.getGlobalConfiguration(),
                            mergedConfiguration.getOverrideConfiguration(), r.compat,
                            r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
                            r.icicle, r.persistentState, results, newIntents,
                            dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                                    r.assistToken));
    
                    // Set desired final state.
                    final ActivityLifecycleItem lifecycleItem;
                    //这里ResumeActivityItem
                    if (andResume) {
                        lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
                    } else {
                        lifecycleItem = PauseActivityItem.obtain();
                    }
                    clientTransaction.setLifecycleStateRequest(lifecycleItem);
    
                    // Schedule transaction.
                    mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    
                    ...
    
            return true;
        }
    

    可以看到里面有一个 ResumeActivityItem 然后调用了mService.getLifecycleManager().scheduleTransaction,这个刚才说了会调用到ActivityThread里的方法,其实最后调用了ActivityThread的handleResumeActivity方法:

        @Override
        public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
                String reason) {
            ...
            // performResumeActivity内部会走onStart、onResume
            final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
            if (r == null) {
                // We didn't actually resume the activity, so skipping any follow-up actions.
                return;
            }
            ...
            
            if (r.window == null && !a.mFinished && willBeVisible) {
                r.window = r.activity.getWindow();
                View decor = r.window.getDecorView();
                decor.setVisibility(View.INVISIBLE);
                ViewManager wm = a.getWindowManager();
                WindowManager.LayoutParams l = r.window.getAttributes();
                a.mDecor = decor;
                l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                l.softInputMode |= forwardBit;
                if (r.mPreserveWindow) {
                    a.mWindowAdded = true;
                    r.mPreserveWindow = false;
                    
                    ViewRootImpl impl = decor.getViewRootImpl();
                    if (impl != null) {
                        impl.notifyChildRebuilt();
                    }
                }
                ...
                
            if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
                if (r.newConfig != null) {
                    performConfigurationChangedForActivity(r, r.newConfig);
                    if (DEBUG_CONFIGURATION) {
                        Slog.v(TAG, "Resuming activity " + r.activityInfo.name + " with newConfig "
                                + r.activity.mCurrentConfig);
                    }
                    r.newConfig = null;
                }
                if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
                WindowManager.LayoutParams l = r.window.getAttributes();
                if ((l.softInputMode
                        & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
                        != forwardBit) {
                    l.softInputMode = (l.softInputMode
                            & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
                            | forwardBit;
                    if (r.activity.mVisibleFromClient) {
                        ViewManager wm = a.getWindowManager();
                        View decor = r.window.getDecorView();
                        wm.updateViewLayout(decor, l);
                    }
                }
    
                r.activity.mVisibleFromServer = true;
                mNumVisibleActivities++;
                if (r.activity.mVisibleFromClient) {
                    //添加window、设置可见
                    r.activity.makeVisible();
                }
            }
    
            r.nextIdle = mNewActivities;
            mNewActivities = r;
            if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
            Looper.myQueue().addIdleHandler(new Idler());
        }
    

    handleResumeActivity主要做了以下事情:

    1. 调用生命周期:通过performResumeActivity方法,内部调用生命周期onStart、onResume方法
    2. 设置视图可见:通过activity.makeVisible方法,添加window、设置可见。(所以视图的真正可见是在onResume方法之后)

    到这里一个Activity就真正显示出来了

    3 创建进程

    下面开始看进程不存在的情况,会调用ActivityManagerInternal::startProcess ActivityManagerInternal 是一个抽象类,具体的实现类时 AMS 中的 LocalService,具体代码就不看了,很复杂,最后AMS 会通过socket与Zygote进行通信去创建APP进程**,Zygote会fork一个进程出来

    为什么这里使用Socket与zygote进行通信呢,可以参考这篇文章为什么systemServer进程与zygote进程的通信是使用socket而不是binder?

    APP进程创建好之后 就会执行ActivityThread的main方,这就是Android 每个进程的入口方法

    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();
    
        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. 执行了Looper.prepareMainLooper(),这会在主线程中创建一个Looper,然后调用Looper.loop 开启无限循环,这就是Android 中消息机制的核心
    2. 创建了一个ActivityThread,并调用attach方法

    里面又创建了一个ActivityThread对象,因为main方法是static的,所以在调用的时候是不存在ActivityThread对象的,之前包括之后使用的所有ActivityThread都是在这创建出来的。然后调用了它的attach:

    image.png

    这个方法的主要目的是将APP进程中的 ApplicationThread 传递给AMS,之后AMS进程与APP进程的通信就靠它了。

    下面是ActivityManagerService的attachApplicationLocked:

    private final boolean attachApplicationLocked(IApplicationThread thread,
                int pid, int callingUid, long startSeq) {
    
                ...
                    //1、IPC操作,创建绑定Application
                    thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
                            null, null, null, testMode,
                            mBinderTransactionTrackingEnabled, enableTrackAllocation,
                            isRestrictedBackupMode || !normalMode, app.isPersistent(),
                            new Configuration(app.getWindowProcessController().getConfiguration()),
                            app.compat, getCommonServicesLocked(app.isolated),
                            mCoreSettingsObserver.getCoreSettingsLocked(),
                            buildSerial, autofillOptions, contentCaptureOptions);
                ...
                // 2、赋值IApplicationThread
                app.makeActive(thread, mProcessStats);
                ...
                
            // See if the top visible activity is waiting to run in this process...
            if (normalMode) {
                try {
                    //3、通过ATMS启动 根activity
                    didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
                } catch (Exception e) {
                    Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                    badApp = true;
                }
            }
            ...
    }
    

    AMS的attachApplicationLocked方法主要三件事:

    1. 调用IApplicationThread的bindApplication方法,IPC操作,创建绑定Application;
    2. 通过makeActive方法赋值IApplicationThread
    3. 通过ATMS启动 根activity

    先看一下第一个ApplicationThread.bindApplication:


    image.png image.png

    初始化了一大堆东西,最后发送了一条消息


    image.png

    ActivityThread 内部的Handler在收到这条消息之后调用了handleBindApplication方法创建了Instrumentation


    image.png

    然后又创建了Application


    image.png

    Application 最终还是在 Instrumentation中创建的

     public Application newApplication(ClassLoader cl, String className, Context context)
                throws InstantiationException, IllegalAccessException, 
                ClassNotFoundException {
            Application app = getFactory(context.getPackageName())
                    .instantiateApplication(cl, className);
            app.attach(context);
            return app;
        }
    

    创建完Application 会将外部创建的 ContextImpl 作为baseContext传递给Application,然后又通过Instrumentation 调用了 callApplicationOnCreate


    image.png

    第二件事就是将APP进程内的ApplicationThread保存下来

    再来看 根activity 的启动,回到上面AMS的attachApplicationLocked方法,调用了mAtmInternal.attachApplication方法,mAtmInternal是ActivityTaskManagerInternal实例,具体实现是在ActivityTaskManagerService的内部类LocalService,去看看:

    //ActivityTaskManagerService#LocalService
            public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
                synchronized (mGlobalLockWithoutBoost) {
                    return mRootActivityContainer.attachApplication(wpc);
                }
            }
    

    mRootActivityContainer是RootActivityContainer实例,看下它的attachApplication方法:

        boolean attachApplication(WindowProcessController app) throws RemoteException {
            final String processName = app.mName;
            boolean didSomething = false;
            for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
                final ActivityDisplay display = mActivityDisplays.get(displayNdx);
                final ActivityStack stack = display.getFocusedStack();
                if (stack != null) {
                    stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
                    final ActivityRecord top = stack.topRunningActivityLocked();
                    final int size = mTmpActivityList.size();
                    for (int i = 0; i < size; i++) {
                        final ActivityRecord activity = mTmpActivityList.get(i);
                        if (activity.app == null && app.mUid == activity.info.applicationInfo.uid
                                && processName.equals(activity.processName)) {
                            try {
                                if (mStackSupervisor.realStartActivityLocked(activity, app,
                                        top == activity /* andResume */, true /* checkConfig */)) {
                                    didSomething = true;
                                }
                            } 
                            ...
                        }
                    }
                }
            }
            if (!didSomething) {
                ensureActivitiesVisible(null, 0, false /* preserve_windows */);
            }
            return didSomething;
        }
    

    眼神好的人看到了realStartActivityLocked,这不又回到了2.2小节了吗,后面的流程就一样了。
    至此Activity启动流程就完成了

    总结

    Activity的启动总体是职责与操作系统中的进程管理和调度模块相类似,因此它在Android中非常一波三折,流程还是很长的

    先解释一下几个比较重要的类:

    1. **Instrumentation **负责 Application 和 四大组件生命周期调用
    2. ActivityTaskManagerService & ActivityMangerService 也就是常说的 ATMS 和 AMS, 是在系统进程中的实例,Android中最核心的服务之一,负责系统中四大组件的启动、切换、调度及应用进程的管理和调度等工作,其重要,它本身也是一个Binder的实现类。
    3. ApplicationThread 是ActivityThread的内部类,继承IApplicationThread.Stub,是一个IBinder,是ActiivtyThread和AMS通信的桥梁,AMS则通过代理调用此App进程的本地方法,运行在Binder线程池
    4. ActivityThread 应用的入口类,系统通过调用main函数,开启消息循环队列。ActivityThread所在线程被称为应用的主线程(UI线程)

    整个流程可以分为下面几部

    1. Activity调用startActivity 走到了 Instrumentation,然后Instrumentation 拿到ATMS 调用ATMS 的startActivity 进入了系统进程内
    2. 然后ATMS 和 AMS 一连串的调用到了ActivityStackSupervisor 的
      startSpecificActivityLocked,在这里先判断Activity所在的进程有没有被创建,如果没创建就走到 LocalService.startProgress 创建进程,如果已经创建了进程就直接到第6步
    3. 创建完进程之后 会通过反射调用ActivityThread的main方法进入Android的主线程 创建无限循环的Looper,然后创建一个ActivityThread 实例,调用attach方法,里面又调用了AMS的 attachApplicationLocked,将APP进程中的ApplicationThread传递给AMS 用于两个进程绑定,从这开始又进入了系统进程(这一步才开始APP进程与系统进程的交互,前面的都是启动Activity的那个进程和系统进程的交互)
    4. AMS 进行了一系列准备工作 然后又调用了ActivityThread 的 bindApplication方法,这个方法里会调用Instrumentation创建Application,调用Application的attachBaseContext和onCreate方法,Application就创建完毕了
    5. 再调用ActivityThread .bindApplication创建完APP进程的Application之后,调用了AMS中的attachApplication,里面又调用了ActivityStackSupervisor.realStartActivityLocked 方法
      6.从 realStartActivityLocked 开始真正的开启Activity启动,在这之前会先pause上一个Activity,然后创建LacunchActivityItem和 ResumeLauncherActivity,然后将LacunchActivityItem通ApplicationThread发送给APP进程的ActivityThread
    6. 这一步开始又回到了APP进程,ActivityThread通过Handler来处理事件,最后调用到了自己的performLaunchActivity方法,然后通过Instrumentation的newActivity方法反射创建了Activity实例,然后调用activity.attach进行方法关联Context 初始化window等方法,然后调用Activity的onCreate方法,到这一步Activity就创建完毕了
      8.在第6步中创建了ResumeActivityItem,同样的也会调用到APP进程中的ActivityThread 中的方法,这次调用的是 handleResumeActivity,调用performResumeActivity里面主要是通过Instrumentation调用了onStart和onResume方法,performResumeActivity调用完毕后才将dcorview 添加到window上,所以view真正是的可见是在onResume之后的。对Activity来说,在onResume之前 只是创建了Window并把Window显示出来了,但是并没有添加实质性的可以看到的View。所以就不明白官方对生命周期的描述 onStart代表Activity可见,onResume代表Activity已经获取到焦点

    题外话

    Activity启动完成了,但是View的三大流程什么时候开始的呢?

    本文参考了大佬的文章
    源码可以在Code Search查看

    相关文章

      网友评论

          本文标题:APP&Activity 启动流程(基于Android10)

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