当前位置:网站首页>Activity creation process details

Activity creation process details

2022-06-23 22:22:00 Great inventor

Create a process

ActivityThread As the main thread management class of the main application , We all come from main Method analysis .main The main function of the method is to create ActivityThread And related , establish Looper The loop does not let the program exit .

public static void main(String[] args) {
        ...
        // Create... For the main thread loop object , We use... In the main thread Handler It can be used without initialization , Because initialization is done here .
        Looper.prepareMainLooper();
        ...
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        // Start an endless loop to get messages 
        Looper.loop();
    }

Next let's analyze ActivityThread Of attach Method , Calling attach The first parameter passed is false, We can see that it passes through AMS Cross process call attachApplication Method .

 private void attach(boolean system, long startSeq) {
        if (!system) {
             ...
            final IActivityManager mgr = ActivityManager.getService();
            try {
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        }
        ...
    }

Next we need to go framework see AMS Only the source code can know what has been done inside ,

Finally called. attachApplicationLocked Method , Then call back to the main process ApplicationThread Of bindApplication Go inside the way .

//frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
 private final boolean attachApplicationLocked(IApplicationThread thread,
                                                  int pid, int callingUid, long startSeq) {
        ...
        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);
        ...
        didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
        ...
    }

We continue to analyze the main process ActivityThread,AMS Tell it to create Application, And data synchronization between the two processes .

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 services, Bundle coreSettings,
                String buildSerial, AutofillOptions autofillOptions,
                ContentCaptureOptions contentCaptureOptions) {
            ...
            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;
            data.buildSerial = buildSerial;
            data.autofillOptions = autofillOptions;
            data.contentCaptureOptions = contentCaptureOptions;
            sendMessage(H.BIND_APPLICATION, data);//1
        }

We can see the first point from the above code , stay ApplicationThread adopt H Class is inheritance Handler, By sending a message to the main thread management class ActivityThread Perform binding Application, call handleBindApplication Method . establish LoadedApk Object and used to create Application.

    private void handleBindApplication(AppBindData data) {
        // Set the process name 
        Process.setArgV0(data.processName);
        // establish LoadedApk example 
        data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
        app = data.info.makeApplication(data.restrictedBackupMode, null);
    }
  public Application makeApplication(boolean forceDefaultAppClass,
                                       Instrumentation instrumentation) {
        //1
        if (mApplication != null) {
            return mApplication;
        }
        Application app = null;
        try {
            ClassLoader cl = getClassLoader();
            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
            //2
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
            appContext.setOuterContext(app);
        } catch (Exception e) {
        }
        mApplication = app;
        if (instrumentation != null) {
            //3
            instrumentation.callApplicationOnCreate(app);
        }
        return app;
    }

From the above code, we can see that ,

1: If any have been created Applicaiton Object and return .

2: establish Application object , And with appContext Establish relational relationships , And call attach Method

3: adopt instrumentation Calls to perform onCreate Method

And then we're going back to AMS Code inside and method attachApplicationLocked, See how the jump is performed Activity Of .

//frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
      public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
        synchronized (mGlobalLockWithoutBoost) {
            return mRootActivityContainer.attachApplication(wpc);
      }

We can see the following code realStartActivityLocked, This is what we really initiated Activity Methods , Then we continue to analyze the code .

//frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java
        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 {
                            // Perform jump 
                            if (mStackSupervisor.realStartActivityLocked(activity, app,
                                    top == activity /* andResume */, true /* checkConfig */)) {
                                didSomething = true;
                            }
                        } catch (RemoteException e) {
                           }
                    }
                }
            }
        }
        return didSomething;
    }

The main function of the following code is , Send instructions to the application process to create Activity,LaunchActivityItem Represents a creation task .

//frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
 boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
                                    boolean andResume, boolean checkConfig) throws RemoteException {
        // Start command 
     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.  Cross process calls to application processes 
        mService.getLifecycleManager().scheduleTransaction(clientTransaction);
        return true;
    }

So he began to execute the order until ,

//ClientLifecycleManager.java
 void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();
        if (!(client instanceof Binder)) {
            transaction.recycle();
        }
    }
//ClientTransaction.java
public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }

The above code mClient It's all ApplicationThread, So we know , Real... Will be created soon Activity 了 , Let's continue to analyze , We are here ApplicationThread This in this class scheduleTransaction Method .

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

The above code shows , Finally, the execution of the agency has come to ActivityThread, Then, by sending a message to the main thread management to execute the creation Activity,ActivityThread Inherited ClientTransactionHandler.

    //TransactionExecutor.java
    public void execute(ClientTransaction transaction) {
        executeCallbacks(transaction);
       // Before the execution pauses, this method is called 
        executeLifecycleState(transaction);
    }
    public void executeCallbacks(ClientTransaction transaction) {
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
        }
    }

After the above code performance , We are here LaunchActivityItem This class .

@Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
        // And  ActivityRecord  Information synchronization   token Information communication 
        ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                mPendingResults, mPendingNewIntents, mIsForward,
                mProfilerInfo, client, mAssistToken);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }

Here we start to create ActivityClientRecord To record Activity Information about , And through token And AMS Of ActivityRecord Corresponding Association . Continue to look at handleLaunchActivity Source code , as follows .

    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        final Activity a = performLaunchActivity(r, customIntent);
        return a;
    }
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
        } catch (Exception e) {
        }
        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            if (activity != null) {
                appContext.setOuterContext(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 (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                r.activity = activity;
            }
        } catch (SuperNotCalledException e) {
            throw e;
        } catch (Exception e) {
        }
        return activity;
    }
原网站

版权声明
本文为[Great inventor]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/202112151541452519.html