• APP启动流程三(源码30)之APP进程启动及Activity启动


    接上篇 APP启动流程二(源码30)之APP进程创建

    App进程启动

    ActivityThread.main()

    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);
    
    • 1
    • 2

    ActivityThread.attach()

    RuntimeInit.setApplicationObject(mAppThread.asBinder());
    final IActivityManager mgr = ActivityManager.getService();
    try {
        //跨进程通信,通过Binder调用AMS的方法
        //mAppThread:ApplicationThread,ActivityThread的内部类
        mgr.attachApplication(mAppThread, startSeq);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    AMS.attachApplication–>AMS.attachApplicationLocked()

    AMS.attachApplicationLocked()

    //创建Application
    thread.bindApplication(processName, appInfo, providerList, 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,
    app.mDisabledCompatChanges);
    
    // See if the top visible activity is waiting to run in this process...
    if (normalMode) {
        try {
            //ActivityTaskManagerService.attachApplication
            didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
            badApp = true;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    ApplicationThread.bindApplication()

    AppBindData data = new AppBindData();
    data.processName = processName;
    data.appInfo = appInfo;
    data.providers = providerList.getList();
    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;
    data.buildSerial = buildSerial;
    data.autofillOptions = autofillOptions;
    data.contentCaptureOptions = contentCaptureOptions;
    data.disabledCompatChanges = disabledCompatChanges;
    sendMessage(H.BIND_APPLICATION, data);
    
    
    public void handleMessage(Message msg) {
        if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
        switch (msg.what) {
            case BIND_APPLICATION:
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
                AppBindData data = (AppBindData)msg.obj;
                handleBindApplication(data);
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                break;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    ActivityThread.handleBindApplication()

    //获取LoadedApk对象
    data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
    //创建App级别的ContextImpl
    final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
    mInstrumentation = new Instrumentation();
    //通过反射创建目标应用Application对象
    app = data.info.makeApplication(data.restrictedBackupMode, null);
    //调用Application.onCreate()
    mInstrumentation.callApplicationOnCreate(app);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    LoadedApk.makeApplication()

    app = mActivityThread.mInstrumentation.newApplication( cl, appClass, appContext);
    instrumentation.callApplicationOnCreate(app);                    
    
    • 1
    • 2

    Instrumentation.newApplication()

    Application app = getFactory(context.getPackageName()).instantiateApplication(cl, className);
    app.attach(context);
    
    • 1
    • 2

    Application.attach()

    final void attach(Context context) {
        attachBaseContext(context);
        mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
    }
    
    • 1
    • 2
    • 3
    • 4

    Instrumentation.callApplicationOnCreate()

    public void callApplicationOnCreate(Application app) {
        app.onCreate(); //Application.onCreate()
    }
    
    • 1
    • 2
    • 3

    ActivityTaskManagerService.attachApplication()

    RootWindowContainer.attach()–>RootWindowContainer.startActivityForAttachedApplicationIfNeeded()–>ActivityStackSupervisor.realStartActivityLocked()(APP进程创建后直接调用此方法,见方法ActivityStackSupervisor.startSpecificActivity)

    ActivityStackSupervisor.realStartActivityLocked()

    // Create activity launch transaction.
    //初始化ClientTransaction.mClient=proc.getThread()=IApplicationThread 
    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.getSavedState(), r.getPersistentSavedState(), results, newIntents,
            dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
            r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));
    
    // Set desired final state.
    final ActivityLifecycleItem lifecycleItem;
    if (andResume) {
        lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
    } else {
        lifecycleItem = PauseActivityItem.obtain();
    }
    clientTransaction.setLifecycleStateRequest(lifecycleItem);
    
    // Schedule transaction.
    //ClientLifecycleManager.scheduleTransaction()
    mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    ClientLifecycleManager.scheduleTransaction()

    final IApplicationThread client = transaction.getClient();
    //mClient.scheduleTransaction(this)-->ApplicationThread.scheduleTransaction()
    //ApplicationThread是ActivityThread的内部类
    transaction.schedule();
    
    • 1
    • 2
    • 3
    • 4

    ApplicationThread.scheduleTransaction()

     @Override
    public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        //ActivityThread extends ClientTransactionHandler
        ActivityThread.this.scheduleTransaction(transaction);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    ClientTransactionHandler.scheduleTransaction()

    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
    
    • 1
    • 2
    • 3
    • 4

    ActivityThread.handleMessage()

    public void handleMessage(Message msg) {
        switch (msg.what) {
            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();
                }
                // TODO(lifecycler): Recycle locally scheduled transactions.
            break;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    TransactionExecutor.execute(transaction)

    //-->Activity.onCreate()
    executeCallbacks(transaction);
    executeLifecycleState(transaction);
    
    • 1
    • 2
    • 3

    TransactionExecutor.executeCallbacks(transaction)

    public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
        if (callbacks == null || callbacks.isEmpty()) {
            // No callbacks to execute, return early.
            return;
        }
        
        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            //LaunchActivityItem.obtain() = LaunchActivityItem
            final ClientTransactionItem item = callbacks.get(i);
            if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Resolving callback: " + item);
            final int postExecutionState = item.getPostExecutionState();
            final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,item.getPostExecutionState());
            if (closestPreExecutionState != UNDEFINED) {
                cycleToPath(r, closestPreExecutionState, transaction);
            }
        
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            if (r == null) {
                // Launch activity request will create an activity record.
                r = mTransactionHandler.getActivityClient(token);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    LaunchActivityItem.execute()

    //client = ActivityThread
    public void execute(ClientTransactionHandler client, IBinder token,PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
        ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                mPendingResults, mPendingNewIntents, mIsForward,
                mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
        //ActivityThread.handleLaunchActivity()-->performLaunchActivity()
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    ActivityThread.handleLaunchActivity()

    //创建Activity的context
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        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) {
        if (!mInstrumentation.onException(activity, e)) {
            throw new RuntimeException(
                "Unable to instantiate activity " + component
                + ": " + e.toString(), e);
        }
    }
    //创建PhoneWindow及WindowManager
    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 (r.isPersistable()) {
        //Activity.onCreate()
        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
    } else {
        mInstrumentation.callActivityOnCreate(activity, r.state);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    TransactionExecutor.executeLifecycleState()

    private void executeLifecycleState(ClientTransaction transaction) {
        //ResumeActivityItem 或 PauseActivityItem
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        if (lifecycleItem == null) {
            // No lifecycle request, return early.
            return;
        }
    
        final IBinder token = transaction.getActivityToken();
        final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
        if (DEBUG_RESOLVER) {
            Slog.d(TAG, tId(transaction) + "Resolving lifecycle state: "
                    + lifecycleItem + " for activity: "
                    + getShortActivityName(token, mTransactionHandler));
        }
    
        if (r == null) {
            // Ignore requests for non-existent client records for now.
            return;
        }
    
        // Cycle to the state right before the final requested state.
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
    
        // Execute the final transition with proper parameters.
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    TransactionExecutor.cycleToPath()

    private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,ClientTransaction transaction) {
        //finish = ON_RESUME=3
        //start = ON_CREATE = 1
        final int start = r.getLifecycleState();
        if (DEBUG_RESOLVER) {
            Slog.d(TAG, tId(transaction) + "Cycle activity: "
                    + getShortActivityName(r.token, mTransactionHandler)
                    + " from: " + getStateName(start) + " to: " + getStateName(finish)
                    + " excludeLastState: " + excludeLastState);
        }
        //path = ON_START
        final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
        // ActivityThread.handleStartActivity()-->Activity.onStart()
        performLifecycleSequence(r, path, transaction);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    ResumeActivityItem.execute()

    @Override
    public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
        //ActivityThread.handleResumeActivity()-->Activity.performResume()
        client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward, "RESUME_ACTIVITY");
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    Activity.performResume()

    final void performResume(boolean followedByPause, String reason) {
        dispatchActivityPreResumed();
        //onStop后才会走Activity.onRestart()-->Activity.onStart(),第一次打开不走这
        performRestart(true /* start */, reason);
    
        mFragments.execPendingActions();
    
        mLastNonConfigurationInstances = null;
    
        if (mAutoFillResetNeeded) {
            // When Activity is destroyed in paused state, and relaunch activity, there will be
            // extra onResume and onPause event,  ignore the first onResume and onPause.
            // see ActivityThread.handleRelaunchActivity()
            mAutoFillIgnoreFirstResumePause = followedByPause;
            if (mAutoFillIgnoreFirstResumePause && DEBUG_LIFECYCLE) {
                Slog.v(TAG, "autofill will ignore first pause when relaunching " + this);
            }
        }
    
        mCalled = false;
        // mResumed is set by the instrumentation
        //Activity.onResume()
        mInstrumentation.callActivityOnResume(this);
        EventLogTags.writeWmOnResumeCalled(mIdent, getComponentName().getClassName(), reason);
        if (!mCalled) {
            throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onResume()");
        }
    
        // invisible activities must be finished before onResume() completes
        if (!mVisibleFromClient && !mFinished) {
            Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
            if (getApplicationInfo().targetSdkVersion
                    > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
                throw new IllegalStateException(
                        "Activity " + mComponent.toShortString() +
                        " did not call finish() prior to onResume() completing");
            }
        }
    
        // Now really resume, and install the current status bar and menu.
        mCalled = false;
    
        mFragments.dispatchResume();
        mFragments.execPendingActions();
    
        onPostResume();
        if (!mCalled) {
            throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onPostResume()");
        }
        dispatchActivityPostResumed();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    Activity生命周期:onCreate()-->onStart()-->onResume()

  • 相关阅读:
    墨西哥专线清关有什么要求?
    RK3568笔记三:部署ResNet50模型
    【Unity】物理引擎、生命周期物理阶段、刚体、碰撞体、触发器、物理材质
    小程序自定义组件以及组件传值的简单总结
    @vue/cli3--使用图形化界面创建项目--方法/实例
    Explain信息中Extra字段解释
    win10解决你当前无权访问该文件夹,拒绝你访问该文件夹
    软信天成:助力某制造企业建设产品主数据管理平台案例分享
    SpringMVC——SpringMVC框架的基础知识概括
    DM3730 X-load 分析
  • 原文地址:https://blog.csdn.net/Super_666/article/details/126249157