Android应用启动源码梳理

更多文章可以访问我的博客Aengus | Blog

网上关于Android应用启动流程的介绍文章已经很多了,不乏一些讲的很清楚的文章,但是当自己着手去看源码时,发现部分源码在Android 10中已有部分变化,网上的文章介绍的函数执行顺序有一些变化,除此之外大部分文章重点放在了Binder机制等等,而自己去找这些文章的主要目的是在寻找应用启动整个流程中的关键函数,以及弄明白Application.onCreate()Activity.onCreate()到底是在哪被调用的以及调用顺序是什么,因此这些文章并不能提供十分有用的帮助。这篇文章不会涉及Binder机制、Zygote创建过程,而只会ActivityThread的主函数开始,一直到Activity.onCreate()被调用,不会在细节上细究,中间会有很多源码,希望对想弄清楚代码执行顺序的同学有所帮助。

Application.onCreate()

首先从ActivityThread.main()开始,其主要部分如下:

public final class ActivityThread extends ClientTransactionHandler {
    
    // ...
    
    public static void main(String[] args) {
        // ...
        Looper.prepareMainLooper();
        // ...
        ActivityThread thread = new ActivityThread();
        // 进入下面的方法
        thread.attach(false, startSeq);
        // ...
        Looper.loop();
    }
    
    private void attach(boolean system, long startSeq) {
        // ...
        sCurrentActivityThread = this;
        mSystemThread = system;
        if (!system) {
            final IActivityManager mgr = ActivityManager.getService();
            try {
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
            // ...
        }
        // ...
    }
}

其中调用了IActivityManager.attachApplication(),实际上调用的是ActivityManagerService.attachApplication(),也就是大名鼎鼎的AMS,其源码如下:

public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    
    @Override
    public final void attachApplication(IApplicationThread thread, long startSeq) {
        if (thread == null) {
            throw new SecurityException("Invalid application interface");
        }
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();
            final long origId = Binder.clearCallingIdentity();
            // 主要逻辑在这里面
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
            Binder.restoreCallingIdentity(origId);
        }
    }

    private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
            int pid, int callingUid, long startSeq) {
        // ...
        try {
            // ...
            if (app.isolatedEntryPoint != null) {
                thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
            } else if (instr2 != null) {
                thread.bindApplication(processName, appInfo, providerList,
                        instr2.mClass,
                        profilerInfo, instr2.mArguments,
                        instr2.mWatcher,
                        instr2.mUiAutomationConnection, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.isPersistent(),
                        new Configuration(app.getWindowProcessController().getConfiguration()),
                        app.compat, getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, autofillOptions, contentCaptureOptions,
                        app.mDisabledCompatChanges);
            } else {
                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);
            }
        } catch (Exception e) {
            // ...
        }
        // ...
    }
}

可以看到又调用了IApplicationThread.bindApplication(),实际上调用的是位于ActivityThread的内部类ApplicationThread.bindApplication() ,此方法的核心在于最后一句:

private class ApplicationThread extends IApplicationThread.Stub {
    @Override
    public final void bindApplication(String processName, ApplicationInfo appInfo,
            ProviderInfoList providerList, 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, long[] disabledCompatChanges) {
        // ...
        sendMessage(H.BIND_APPLICATION, data);
    }
}

此Handler对应的handleMessage()如下:

class H extends Handler {
    public void handleMessgae(Message msg) {
        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;
            // ...
        }
        // ...
    }
    
    private void handleBindApplication(AppBindData data) {
        // ...
        try {
            mInstrumentation.callApplicationOnCreate(app);
        } catch (Exception e) {
            if (!mInstrumentation.onException(app, e)) {
                throw new RuntimeException(
                    "Unable to create application " + app.getClass().getName()
                    + ": " + e.toString(), e);
            }
        }
        // ...
    }
}

可以看到此函数调用了Instrumentation.callApplicationOnCreate(),其实现就是调用Application.onCreate()

public class Instrumentation {
    public void callApplicationOnCreate(Application app) {
        app.onCreate();
    }
}

至此,Application.onCreate()调用完成。

Activity.onCreate()

让我们再回到ActivityManagerService.attachApplicationLocked()中,其调用完thread.bindApplication()后,继续往下执行,关于Activity启动的主要逻辑为下面这句:

private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
            int pid, int callingUid, long startSeq) {
    // ...
    if (normalMode) {
        try {
            didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
            badApp = true;
        }
    }
    // ...
}

调用了ActivityTaskManagerInternal.attachApplication()函数,实际上调用的则是ActivityTaskManagerService.attachApplication()

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
    public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
        synchronized (mGlobalLockWithoutBoost) {
            if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
                Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
            }
            try {
                return mRootWindowContainer.attachApplication(wpc);
            } finally {
                Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
            }
        }
    }
}

其中调用了RootWindowContainer.attachApplication(),此函数实现如下:

class RootWindowContainer extends WindowContainer implements DisplayManager.DisplayListener {
    
    boolean attachApplication(WindowProcessController app) throws RemoteException {
        final String processName = app.mName;
        boolean didSomething = false;
        for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
            final DisplayContent display = getChildAt(displayNdx);
            final ActivityStack stack = display.getFocusedStack();
            if (stack == null) {
                continue;
            }

            mTmpRemoteException = null;
            mTmpBoolean = false; // Set to true if an activity was started.
            final PooledFunction c = PooledLambda.obtainFunction(
                    RootWindowContainer::startActivityForAttachedApplicationIfNeeded, this,
                    PooledLambda.__(ActivityRecord.class), app, stack.topRunningActivity());
            stack.forAllActivities(c);
            c.recycle();
            if (mTmpRemoteException != null) {
                throw mTmpRemoteException;
            }
            didSomething |= mTmpBoolean;
        }
        if (!didSomething) {
            ensureActivitiesVisible(null, 0, false /* preserve_windows */);
        }
        return didSomething;
    }
}

核心在于RootWindowContainer::startActivityForAttachedApplicationIfNeeded,而此函数的核心则是:

private boolean startActivityForAttachedApplicationIfNeeded(ActivityRecord r,
            WindowProcessController app, ActivityRecord top) {
    // ...
    try {
        if (mStackSupervisor.realStartActivityLocked(r, app, top == r, true)) {
                mTmpBoolean = true;
        }
    } catch (RemoteException e) {
        // ...
        return true;
    }
    return false;
}

ActivityStackSupervisor.realStartActivityLocked(),其实现为:

public class ActivityStackSupervisor implements RecentTasks.Callbacks {
    boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {
        // ...
        // 创建Activity启动事务
        final ClientTransaction clientTransaction = ClientTransaction.obtain(proc.getThread(), r.appToken);
        // 此函数十分重要
        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.getSavedState(), r.getPersistentSavedState(), results, newIntents,
                dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));
        // ...
        mService.getLifecycleManager().scheduleTransaction(clientTransaction);
        // ...
    }
}

在此函数中,首先创建了Activity启动事务,并对其添加了启动回调,然后调用ClientLifecycleManager.scheduleTransaction执行事务:

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

此函数其实就是调用了事务的schedule()方法,其实现如下:

public class ClientTransaction implements Parcelable, ObjectPoolItem {
    
    private IApplicationThread mClient;
    
    public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }
    
    public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
        ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
        if (instance == null) {
            instance = new ClientTransaction();
        }
        instance.mClient = client;
        instance.mActivityToken = activityToken;

        return instance;
    }
}

可以看到ClientTransaction.mClientActivityStackSupervisor.realStartActivityLocked()中创建时被赋值,因此mClient.scheduleTransaction()实际上调用的是ApplicationThread.scheduleTransaction(),因此我们再回到ApplicationThread中:

public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    ActivityThread.this.scheduleTransaction(transaction);
}

在这里我们发现此函数调用的实际上是ActivityThread.scheduleTransaction(),而ActivityThread继承了抽象类ClientTransactionHandler,于是此函数的实现为:

public abstract class ClientTransactionHandler {
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
    
    abstract void sendMessage(int what, Object obj);
}

可以看到还是使用了sendMessage(),此函数对应的handleMessage()为:

public final class ActivityThread extends ClientTransactionHandler {
    
    // 注意这里创建mTransactionExecutor时将this传入
    private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
    
    class H extends Handler {
        public void handleMessgae(Message msg) {
            switch (msg.what) {
                // ...
                case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    mTransactionExecutor.execute(transaction);
                    if (isSystem()) {
                        transaction.recycle();
                    }
                    break;
                // ...
            }
            // ...
        }
    }
}

调用了TransactionExecutor.execute(),此函数的实现为:

public class TransactionExecutor {
    public void execute(ClientTransaction transaction) {
        // ...
        executeCallbacks(transaction);
        // ...
    }
    
    public void executeCallbacks(ClientTransaction transaction) {
        final List callbacks = transaction.getCallbacks();
        // ...
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            // ...
            item.execute(mTransactionHandler, token, mPendingActions);
            // ...
        }
    }
}

executeCallbacks()中,其首先获取了callbacks,然后对其中的所有元素调用execute()方法,这里的callbacks便是我们在ActivityStackSupervisor.realStartActivityLocked()中创建启动事务后,对其调用的addCallback()方法,事实上,addCallback()方法接收ClientTransactionItem作为参数,而LaunchAvtivityItem正是继承了ClientTransactionItem

public class LaunchActivityItem extends ClientTransactionItem {
    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);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
}

此函数的核心在于client.handleLaunchActivity(),注意在TransactionExecutor创建时,我们将ActivityThread传入,因此这里的client便是ActivityThread,其实现如下:

public final class ActivityThread extends ClientTransactionHandler {
    @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        // ...
        // 实现在下方
        final Activity a = performLaunchActivity(r, customIntent);
        // ...
    }
    
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // ...
        // 创建Activity
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        // ...
        if (r.isPersistable()) {
            mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
        } else {
            mInstrumentation.callActivityOnCreate(activity, r.state);
        }
        // ...
    }
}

可以看到最终仍然是通过Instrumentation调用的Activity.onCreate()方法:

public class Instrumentation {
    public void callActivityOnCreate(Activity activity, Bundle icicle,
            PersistableBundle persistentState) {
        prePerformCreate(activity);
        activity.performCreate(icicle, persistentState);
        postPerformCreate(activity);
    }
}

至此,Activity.onCreate()调用完成。

上面省略了大量的源码,仅仅是将主要函数的执行顺序串了起来。事实上,如果去阅读源码,其实可以看到关于Activity主题的配置,Activity栈管理、记录以及Service、Broadcast Receiver的初始化也都在上面提到的函数中。如果想详细了解细节,可以读一下这篇文章。

你可能感兴趣的:(Android应用启动源码梳理)