Activity启动源码分析-基于Android10(四)

文章目录

  • Activity的创建和onCreate方法回调
    • 1.realStartActivityLocked
    • 2.XXXActivityItem类
    • 3.scheduleTransaction
    • 4.handleLaunchActivity
  • 进程创建
    • 1.创建进程
    • 2.回到原点

在这里插入图片描述

  • Instrumentation
    负责调用Activity和Application生命周期。
  • ActivityTaskManagerService
    负责Activity管理和调度等工作。android10中新增的
  • ActivityManagerService
    负责管理四大组件和进程,包括生命周期和状态切换。
  • ActivityTaskManagerInternal
    ActivityTaskManagerService对外提供的一个抽象类,真正的实现在ActivityTaskManagerService#LocalService
  • ActivityThread
    管理应用程序进程中主线程的执行
  • ActivityStackSupervisor
    负责所有Activity栈的管理
  • TransactionExecutor
    主要作用是执行ClientTransaction
  • ClientLifecycleManager
    生命周期的管理调用

Activity的创建和onCreate方法回调

上篇文章
Activity启动流程-基于Android10(三)通过非常冗余的逻辑调用到了ActivityStackSupervisor的startSpecificActivityLocked方法,今天继续分析后续的逻辑,以此了解Activity的创建和onCreate方法的回调。这里将startSpecificActivityLocked方法的逻辑分为两个部分讲解。

frameworks\base\services\core\java\com\android\server\wm\ActivityStackSupervisor.java

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);
            }

            // If a dead object exception was thrown -- fall through to
            // restart the application.
            knownToBeDead = true;
        }

        // Suppress transition until the new activity becomes ready, otherwise the keyguard can
        // appear for a short amount of time before the new process with the new activity had the
        // ability to set its showWhenLocked flags.
        if (getKeyguardController().isKeyguardLocked()) {
            r.notifyUnknownVisibilityLaunched();
        }

        try {
            if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
                Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
                        + r.processName);
            }
==============================================第二部分===============================================================
            // 重要代码
            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方法。

1.realStartActivityLocked

// 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()) {
        
// 省略部分代码

通过注释可以知道首先需要判断进程是否已经被创建,并且在运行中,如果在运行中就去调用realStartActivityLocked方法。

frameworks\base\services\core\java\com\android\server\wm\ActivityStackSupervisor.java

boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
        boolean andResume, boolean checkConfig) throws RemoteException {

        try {
            if (!proc.hasThread()) {
                throw new 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;

			// 通过前面ActivityStack的代码可以看出andResum是true
            if (andResume) {
                lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
            } else {
                lifecycleItem = PauseActivityItem.obtain();
            }
            clientTransaction.setLifecycleStateRequest(lifecycleItem);

            // 重要代码
            mService.getLifecycleManager().scheduleTransaction(clientTransaction);
            //...
        } catch (RemoteException e) {
           //...
        }
    } finally {
        endDeferResume();
    }
    
    //...省略代码
    
    proc.onStartActivity(mService.mTopProcessState, r.info);
    //...省略代码
    return true;
}

2.XXXActivityItem类

注意到代码中有一个LaunchActivityItem类,这个类在servertransaction包下面。

frameworks\base\core\java\android\app\servertransaction

打开这个包可以看到带有"Pause",“Stop”,“Resume”,"Destory"字段的XXXActivityItem类,我们可以大胆的猜测这些类是和Activity的onStop,onResume,onDestory生命周期相关的类。事实上,通过分析这些类的确是和这些回调是相关的。
Activity启动源码分析-基于Android10(四)_第1张图片
这个包下面的大部分类都是继承自ClientTransactionItem,而ClientTransactionItem实现BaseClientRequest

frameworks\base\core\java\android\app\servertransaction\LaunchActivityItem.java
public class LaunchActivityItem extends ClientTransactionItem {
// ...省略大部分代码
}

frameworks\base\core\java\android\app\servertransaction\ClientTransactionItem.java
public abstract class ClientTransactionItem implements BaseClientRequest, Parcelable {

    /** Get the state that must follow this callback. */
    @LifecycleState
    public int getPostExecutionState() {
        return UNDEFINED;
    }


    // Parcelable

    @Override
    public int describeContents() {
        return 0;
    }
}

frameworks\base\core\java\android\app\servertransaction\BaseClientRequest.java
public interface BaseClientRequest extends ObjectPoolItem {

    /**
     * Prepare the client request before scheduling.
     * An example of this might be informing about pending updates for some values.
     *
     * @param client Target client handler.
     * @param token  Target activity token.
     */
    default void preExecute(ClientTransactionHandler client, IBinder token) {
    }

    /**
     * Execute the request.
     * @param client Target client handler.
     * @param token Target activity token.
     * @param pendingActions Container that may have data pending to be used.
     */
    void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions);

    /**
     * Perform all actions that need to happen after execution, e.g. report the result to server.
     * @param client Target client handler.
     * @param token Target activity token.
     * @param pendingActions Container that may have data pending to be used.
     */
    default void postExecute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
    }
}

frameworks\base\core\java\android\app\servertransaction\ObjectPoolItem .java
public interface ObjectPoolItem {
    /**
     * Clear the contents of the item and putting it to a pool. The implementation should call
     * {@link ObjectPool#recycle(ObjectPoolItem)} passing itself.
     */
    void recycle();
}

继承关系图:
Activity启动源码分析-基于Android10(四)_第2张图片

3.scheduleTransaction

有了上面的XXXActivityItem,让我们继续分析后续代码。

mService.getLifecycleManager().scheduleTransaction(clientTransaction);

getLifecycleManager得到的是ClientLifecycleManager对象。这里调用了scheduleTransaction方法。继续堆代码:


frameworks\base\services\core\java\com\android\server\wm\ClientLifecycleManager.java

void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
        @NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
    final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
            stateRequest);
    scheduleTransaction(clientTransaction);
}

private static ClientTransaction transactionWithState(@NonNull IApplicationThread client,
        @NonNull IBinder activityToken, @NonNull ActivityLifecycleItem stateRequest) {
    final ClientTransaction clientTransaction = ClientTransaction.obtain(client, activityToken);
    clientTransaction.setLifecycleStateRequest(stateRequest);
    return clientTransaction;
}

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    final IApplicationThread client = transaction.getClient();
    transaction.schedule();
    if (!(client instanceof Binder)) {
        // If client is not an instance of Binder - it's a remote call and at this point it is
        // safe to recycle the object. All objects used for local calls will be recycled after
        // the transaction is executed on client in ActivityThread.
        transaction.recycle();
    }
}

frameworks\base\core\java\android\app\servertransaction\ClientTransaction.java
public void schedule() throws RemoteException {
    mClient.scheduleTransaction(this);
}

那么这个client是什么呢?通过查看ClientTransaction类的代码知道这个client就是IApplicationThread

frameworks\base\core\java\android\app\servertransaction\ClientTransaction.java
	
	/** 目标 client. */
    private IApplicationThread mClient;

    /** Get the target client of the transaction. */
    public IApplicationThread getClient() {
        return mClient;
    }

所以调用mClient的scheduleTransaction,就是调用ActivityThread内部类的ApplicationThread的scheduleTransaction方法。

Activity启动流程-基于Android10(二)中提到IActivityTaskManager.aidl是客户端(Activity)到服务端(ActivityTaskManagerService)的中间桥梁。那么IApplicationThread就是服务端(ActivityTaskManagerService)到客户端(Activity)的中间桥梁

简化流程示意图:
ActivityTaskManagerService.java ⇒ I A p p l i c a t i o n T h r e a d . a i d l \xRightarrow{IApplicationThread.aidl} IApplicationThread.aidl Activity.java

frameworks\base\core\java\android\app\ActivityThread#ApplicationThread

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

这个scheduleTransaction方法在ActivityThread里面是找不到的。其实这个方法在ClientTransactionHandler抽象类中。如果看代码就可以知道,ActivityThread就是继承自ClientTransactionHandler。

frameworks\base\core\java\android\app\ClientTransactionHandler

public abstract class ClientTransactionHandler {

    // Schedule phase related logic and handlers.

    /** Prepare and schedule transaction for execution. */
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
    // ...省略部分代码
}

sendMessage是在ActivityThread里面实现的。

frameworks\base\core\java\android\app\ActivityThread

void sendMessage(int what, Object obj) {
        sendMessage(what, obj, 0, 0, false);
    }

    private void sendMessage(int what, Object obj, int arg1) {
        sendMessage(what, obj, arg1, 0, false);
    }

    private void sendMessage(int what, Object obj, int arg1, int arg2) {
        sendMessage(what, obj, arg1, arg2, false);
    }

    private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        if (DEBUG_MESSAGES) {
            Slog.v(TAG,
                    "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj);
        }
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        mH.sendMessage(msg);
    }

这个mH其实是ActivityThread内部的Handler,通过Message的what为ActivityThread.H.EXECUTE_TRANSACTION。
内部类Handler代码:

frameworks\base\core\java\android\app\ActivityThread

private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);

	// ...省略部分代码
	case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    mTransactionExecutor.execute(transaction);
                    if (isSystem()) {
                        transaction.recycle();
                    }
                    // TODO(lifecycler): Recycle locally scheduled transactions.
                    break;

再看看TransactionExecutor源码

public class TransactionExecutor {

	// ...省略部分代码
    public void execute(ClientTransaction transaction) {
    	
    	// ...省略部分代码
    	for (int i = 0; i < size; ++i) {
            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);
            }

            if (postExecutionState != UNDEFINED && r != null) {
                // Skip the very last transition and perform it by explicit state request instead.
                final boolean shouldExcludeLastTransition =
                        i == lastCallbackRequestingState && finalState == postExecutionState;
                cycleToPath(r, postExecutionState, shouldExcludeLastTransition, transaction);
            }
        }
    }

这里的ClientTransactionItem就是LaunchActivityItem

frameworks\base\services\core\java\com\android\server\wm\ActivityStackSupervisor.java

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));

所以实际上是调用了LaunchActivityItem的execute方法。

frameworks\base\core\java\android\app\servertransaction\LaunchActivityItem

	@Override
    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);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }

4.handleLaunchActivity

这里的mTransactionHandler就是ActivityThread,因为ActivityThread实现了ClientTransactionHandler,所以调用的是ActivityThread的handleLaunchActivity方法。

frameworks\base\core\java\android\app\ActivityThread

@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
            // ...省略部分代码
            
            final Activity a = performLaunchActivity(r, customIntent);
}

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
	// ...省略部分代码
	
	ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
        	// 创建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) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to instantiate activity " + component
                    + ": " + e.toString(), e);
            }
        }
         try {
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);
        //...省略代码
        if (activity != null) {
           //...省略代码
            appContext.setOuterContext(activity);
            
            // 向Activity attach一些重要参数
            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);
            //...省略代码
            
            // 这里回调Instrumentation的callActivityOnCreate
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            r.activity = activity;
        }
        r.setState(ON_CREATE);
        //...省略代码
    } catch (SuperNotCalledException e) {
        throw e;
    } catch (Exception e) {
        //...
    }
    return activity;
}

我们可以看到通过ClassLoader去加载需要启动的activity,再通过Activity的attach方法传递Context,Instrumentation,ActivityThread,Application等等重要的相关的参数。通过调用Instrumentation的callActivityOnCreate,继而调用Activity的onCreate,这样就完成了Activity生命周期的第一个回调onCreate方法。

frameworks\base\core\java\android\app\Instrumentation

public class Instrumentation {
	// ...省略部分代码
	
	public void callActivityOnCreate(Activity activity, Bundle icicle) {
		// MessageQueue.IdleHandler的妙用
        prePerformCreate(activity);
        
        // 这里调用Activity的performCreate
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }
    
    public void callActivityOnCreate(Activity activity, Bundle icicle,
            PersistableBundle persistentState) {
        // MessageQueue.IdleHandler的妙用
        prePerformCreate(activity);
        
        // 这里调用Activity的performCreate
        activity.performCreate(icicle, persistentState);
        postPerformCreate(activity);
    }
    
	private void prePerformCreate(Activity activity) {
        if (mWaitingActivities != null) {
            synchronized (mSync) {
                final int N = mWaitingActivities.size();
                for (int i=0; i<N; i++) {
                    final ActivityWaiter aw = mWaitingActivities.get(i);
                    final Intent intent = aw.intent;
                    if (intent.filterEquals(activity.getIntent())) {
                        aw.activity = activity;
                        
                        // 在MessageQueue空闲的时候处理一些相关数据
                        // 这样就不会卡住MessageQueue队列
                        mMessageQueue.addIdleHandler(new ActivityGoing(aw));
                    }
                }
            }
        }
    }

	// MessageQueue.IdleHandler接口
	private final class ActivityGoing implements MessageQueue.IdleHandler {
        private final ActivityWaiter mWaiter;

        public ActivityGoing(ActivityWaiter waiter) {
            mWaiter = waiter;
        }

        public final boolean queueIdle() {
            synchronized (mSync) {
                mWaitingActivities.remove(mWaiter);
                mSync.notifyAll();
            }
            return false;
        }
    }

	public Activity newActivity(Class<?> clazz, Context context, 
            	IBinder token, Application application, Intent intent, 			ActivityInfo info, 
            CharSequence title, Activity parent, String id,
            Object lastNonConfigurationInstance) throws InstantiationException,
            IllegalAccessException {
        Activity activity = (Activity)clazz.newInstance();
        ActivityThread aThread = null;
        // Activity.attach expects a non-null Application Object.
        if (application == null) {
            application = new Application();
        }
        activity.attach(context, aThread, this, token, 0 /* ident */, application, intent,
                info, title, parent, id,
                (Activity.NonConfigurationInstances)lastNonConfigurationInstance,
                new Configuration(), null /* referrer */, null /* voiceInteractor */,
                null /* window */, null /* activityConfigCallback */, null /*assistToken*/);
        return activity;
    }
    // ...省略部分代码
}
============================================================================
frameworks\base\core\java\android\app\Activity

	@UnsupportedAppUsage
    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        dispatchActivityPreCreated(icicle);
        mCanEnterPictureInPicture = true;
        restoreHasCurrentPermissionRequest(icicle);
        
        // 调用Activity的onCreate方法
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
        writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
        mActivityTransitionState.readState(icicle);

        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
                com.android.internal.R.styleable.Window_windowNoDisplay, false);
        mFragments.dispatchActivityCreated();
        mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
        dispatchActivityPostCreated(icicle);
    }

至此,通过上面的分析充分了解了第一部分的处理逻辑。

进程创建

ActivityStackSupervisor的startSpecificActivityLocked方法的第一部分逻辑讲完了。接下来讲下第二部分,关于进程创建的问题。

final Message msg = PooledLambda.obtainMessage(
                    ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
                    r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
            mService.mH.sendMessage(msg);

1.创建进程

重点关注ActivityManagerInternal::startProcess,这里的::其实是java8的新特性,语法含义是调用ActivityManagerInternal类的startProcess方法。后面的那些变量就是传递到startProcess的参数。

至于mService.mH.sendMessage(msg);它的作用其实是发送msg给ActivityTaskManagerService的内部类Handler,调用AppTimeTracker的deliverResult方法。作用应该是统计用户使用APP的相关时间。

ActivityManagerInternal是一个抽象类,startProcess的具体实现是在ActivityManagerService内部类LocalService。

frameworks\base\services\core\java\com\android\server\am\ActivityManagerService

final class LocalService extends ActivityManagerInternal{
		// ...省略部分代码
		@Override
        public void startProcess(String processName, ApplicationInfo info,
                boolean knownToBeDead, String hostingType, ComponentName hostingName) {
                synchronized (ActivityManagerService.this) {
                    startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
                            new HostingRecord(hostingType, hostingName),
                            false /* allowWhileBooting */, false /* isolated */,
                            true /* keepIfLarge */);
                }
        }
        // ...省略部分代码
        final ProcessRecord startProcessLocked(String processName,
            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
            HostingRecord hostingRecord, boolean allowWhileBooting,
            boolean isolated, boolean keepIfLarge) {
        return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
                hostingRecord, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
                null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
                null /* crashHandler */);
    }
}

接下来执行了ProcessList的startProcessLocked方法,最终调用Process的start方法

frameworks\base\services\core\java\com\android\server\am\ProcessList

private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
            ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
            String seInfo, String requiredAbi, String instructionSet, String invokeWith,
            long startTime) {
        try {
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
                    app.processName);
            checkSlow(startTime, "startProcess: asking zygote to start proc");
            final Process.ProcessStartResult startResult;
            if (hostingRecord.usesWebviewZygote()) {
            // ...省略部分代码
            } else if (hostingRecord.usesAppZygote()) {
            // ...省略部分代码
            } else {
                startResult = Process.start(entryPoint,
                        app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                        app.info.dataDir, invokeWith, app.info.packageName,
                        new String[] {PROC_START_SEQ_IDENT + app.startSeq});
            }
            checkSlow(startTime, "startProcess: returned from zygote!");
            return startResult;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        }
    }
========================================================================================================================================================
frameworks\base\core\java\android\os\Process

public static final ZygoteProcess ZYGOTE_PROCESS = new ZygoteProcess();

public static ProcessStartResult start(@NonNull final String processClass,
                                           @Nullable final String niceName,
                                           int uid, int gid, @Nullable int[] gids,
                                           int runtimeFlags,
                                           int mountExternal,
                                           int targetSdkVersion,
                                           @Nullable String seInfo,
                                           @NonNull String abi,
                                           @Nullable String instructionSet,
                                           @Nullable String appDataDir,
                                           @Nullable String invokeWith,
                                           @Nullable String packageName,
                                           @Nullable String[] zygoteArgs) {
        return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
                    runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                    abi, instructionSet, appDataDir, invokeWith, packageName,
                    /*useUsapPool=*/ true, zygoteArgs);
    }

调用ZygoteProcess的start方法,进而调用startViaZygote方法

frameworks\base\core\java\android\os\ZygoteProcess

private Process.ProcessStartResult startViaZygote(@NonNull final String processClass,
                                                      @Nullable final String niceName,
                                                      final int uid, final int gid,
                                                      @Nullable final int[] gids,
                                                      int runtimeFlags, int mountExternal,
                                                      int targetSdkVersion,
                                                      @Nullable String seInfo,
                                                      @NonNull String abi,
                                                      @Nullable String instructionSet,
                                                      @Nullable String appDataDir,
                                                      @Nullable String invokeWith,
                                                      boolean startChildZygote,
                                                      @Nullable String packageName,
                                                      boolean useUsapPool,
                                                      @Nullable String[] extraArgs)
                                                      throws ZygoteStartFailedEx {
        ArrayList<String> argsForZygote = new ArrayList<>();

		// 各种执行命令       

        synchronized(mLock) {
            // The USAP pool can not be used if the application will not use the systems graphics
            // driver.  If that driver is requested use the Zygote application start path.
            return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
                                              useUsapPool,
                                              argsForZygote);
        }
    }

private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
    try {
        attemptConnectionToPrimaryZygote();

        if (primaryZygoteState.matches(abi)) {
            return primaryZygoteState;
        }

        if (mZygoteSecondarySocketAddress != null) {
            // The primary zygote didn't match. Try the secondary.
            attemptConnectionToSecondaryZygote();

            if (secondaryZygoteState.matches(abi)) {
                return secondaryZygoteState;
            }
        }
    } catch (IOException ioe) {
        throw new ZygoteStartFailedEx("Error connecting to zygote", ioe);
    }

    throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
}

private void attemptConnectionToPrimaryZygote() throws IOException {
    if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
        primaryZygoteState =
                ZygoteState.connect(mZygoteSocketAddress, mUsapPoolSocketAddress);
        maybeSetApiBlacklistExemptions(primaryZygoteState, false);
        maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
        maybeSetHiddenApiAccessStatslogSampleRate(primaryZygoteState);
    }
}

/**
 * Creates a ZygoteState for the secondary zygote if it doesn't exist or has been disconnected.
 */
@GuardedBy("mLock")
private void attemptConnectionToSecondaryZygote() throws IOException {
    if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
        secondaryZygoteState =
                ZygoteState.connect(mZygoteSecondarySocketAddress,
                        mUsapPoolSecondarySocketAddress);

        maybeSetApiBlacklistExemptions(secondaryZygoteState, false);
        maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState);
        maybeSetHiddenApiAccessStatslogSampleRate(secondaryZygoteState);
    }

最终是通过Zygote通信去fork去一个新的的进程。具体细节可以在ZygoteProcess中看看,最后调用ActivityThread的main方法

2.回到原点

frameworks\base\core\java\android\app\ActivityThread.java

public static void main(String[] args) {
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
    
    AndroidOs.install();
    
    CloseGuard.setEnabled(false);

    Environment.initForCurrentUser();

    // Make sure TrustedCertificateStore looks in the right place for CA certificates
    final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
    TrustedCertificateStore.setDefaultUserDirectory(configDir);

    Process.setArgV0("");

    Looper.prepareMainLooper();

    long startSeq = 0;
    if (args != null) {
        for (int i = args.length - 1; i >= 0; --i) {
            if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                startSeq = Long.parseLong(
                        args[i].substring(PROC_START_SEQ_IDENT.length()));
            }
        }
    }

	ActivityThread thread = new ActivityThread();
    // 重要代码
    thread.attach(false, startSeq);

    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");
}

这里面包括Looper的创建和轮询,调用ActivityThread的attach方法。

	@UnsupportedAppUsage
    private void attach(boolean system, long startSeq) {
    	// ...省略部分代码
		final IActivityManager mgr = ActivityManager.getService();
        try {
             mgr.attachApplication(mAppThread, startSeq);
        } catch (RemoteException ex) {
             throw ex.rethrowFromSystemServer();
        }
        // ...省略部分代码
	}

通过代码可以看出,这里调用了ActivityManagerService的attachApplication方法

frameworks\base\services\core\java\com\android\server\am\ActivityManagerService

public ActivityTaskManagerInternal mAtmInternal;

@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
    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 final boolean attachApplicationLocked(IApplicationThread thread,
        int pid, int callingUid, long startSeq) {
    ProcessRecord app;
    long startTime = SystemClock.uptimeMillis();
    long bindApplicationTimeMillis;
    //...省略代码
    // If this application record is still attached to a previous
    // process, clean it up now.
    if (app.thread != null) {
        handleAppDiedLocked(app, true, true);
    }

    final String processName = app.processName;
    try {
        AppDeathRecipient adr = new AppDeathRecipient(
                app, pid, thread);
        thread.asBinder().linkToDeath(adr, 0);
        app.deathRecipient = adr;
    } catch (RemoteException e) {
        app.resetPackageList(mProcessStats);
        mProcessList.startProcessLocked(app,
                new HostingRecord("link fail", processName));
        return false;
    }
    checkTime(startTime, "attachApplicationLocked: before bindApplication");

    try {
        checkTime(startTime, "attachApplicationLocked: immediately before bindApplication");
        bindApplicationTimeMillis = SystemClock.elapsedRealtime();
        mAtmInternal.preBindApplication(app.getWindowProcessController());
        final ActiveInstrumentation instr2 = app.getActiveInstrumentation();
        if (app.isolatedEntryPoint != null) {
            // This is an isolated process which should just call an entry point instead of
            // being bound to an application.
            thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
        } else if (instr2 != null) {
            thread.bindApplication(processName, appInfo, providers,
                    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);
        } else {
            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);
        }
        if (profilerInfo != null) {
            profilerInfo.closeFd();
            profilerInfo = null;
        }

        // Make app active after binding application or client may be running requests (e.g
        // starting activities) before it is ready.
        app.makeActive(thread, mProcessStats);
        checkTime(startTime, "attachApplicationLocked: immediately after bindApplication");
        mProcessList.updateLruProcessLocked(app, false, null);
        checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked");
        app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
    } catch (Exception e) {
        //...省略代码
    }

    // Remove this record from the list of starting applications.
    mPersistentStartingProcesses.remove(app);
    if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES,
            "Attach application locked removing on hold: " + app);
    mProcessesOnHold.remove(app);

    boolean badApp = false;
    boolean didSomething = false;

	// Activity相关处理逻辑,本文的重点
    // See if the top visible activity is waiting to run in this process...
    if (normalMode) {
        try {
            didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
            badApp = true;
        }
    }

	// Service相关处理逻辑
    // Find any services that should be running in this process...
    if (!badApp) {
        try {
            didSomething |= mServices.attachApplicationLocked(app, processName);
            checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
            badApp = true;
        }
    }

	// BroadcastReceiver相关处理逻辑
    // Check if a next-broadcast receiver is in this process...
    if (!badApp && isPendingBroadcastProcessLocked(pid)) {
        try {
            didSomething |= sendPendingBroadcastsLocked(app);
            checkTime(startTime, "attachApplicationLocked: after sendPendingBroadcastsLocked");
        } catch (Exception e) {
            // If the app died trying to launch the receiver we declare it 'bad'
            Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e);
            badApp = true;
        }
    }

    // Check whether the next backup agent is in this process...
    if (!badApp && backupTarget != null && backupTarget.app == app) {
        if (DEBUG_BACKUP) Slog.v(TAG_BACKUP,
                "New app is backup target, launching agent for " + app);
        notifyPackageUse(backupTarget.appInfo.packageName,
                         PackageManager.NOTIFY_PACKAGE_USE_BACKUP);
        try {
            thread.scheduleCreateBackupAgent(backupTarget.appInfo,
                    compatibilityInfoForPackage(backupTarget.appInfo),
                    backupTarget.backupMode, backupTarget.userId);
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e);
            badApp = true;
        }
    }

    if (badApp) {
        app.kill("error during init", true);
        handleAppDiedLocked(app, false, true);
        return false;
    }

    if (!didSomething) {
        updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN);
        checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked");
    }
    return true;
}

该段代码可以看到对于Activity、Service、BroadcastReceiver的处理逻辑,本文主要讨论对Activity的处理。其中关键的代码mAtmInternal.attachApplication。mAtmInternal是ActivityTaskManagerInternal,ActivityTaskManagerService的内部类LocalService是它的实现类。所以最终调用的是LocalService的attachApplication方法

frameworks\base\services\core\java\com\android\server\wm\ActivityTaskManagerService.java

@Override
public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
    synchronized (mGlobalLockWithoutBoost) {
        return mRootActivityContainer.attachApplication(wpc);
    }
}

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 {
                    	// 重要代码
                        if (mStackSupervisor.realStartActivityLocked(activity, app,
                                top == activity /* andResume */, true /* checkConfig */)) {
                            didSomething = true;
                        }
                    } catch (RemoteException e) {
                        Slog.w(TAG, "Exception in new application when starting activity "
                                + top.intent.getComponent().flattenToShortString(), e);
                        throw e;
                    }
                }
            }
        }
    }
    if (!didSomething) {
        ensureActivitiesVisible(null, 0, false /* preserve_windows */);
    }
    return didSomething;
}

这里的逻辑又运行到了realStartActivityLocked方法中,这个方法就是本文开头的那个方法。所以最后绕了一大圈又绕回来了。

至此,Activity启动逻辑大体上是清楚了,由于Activity启动的逻辑复杂,这里只是做了大体上的研究,技术细节可以留待后面慢慢研究。

参考文章:Activity的启动流程-基于Android10源码

你可能感兴趣的:(Android源码研习)