Android 11 (R)AMS Activity内部机制

一、AMS是如何被管理的

如我们在Android 11(R)启动流程中介绍的一样,AMS和ATMS是在SystemServer中被启动的

java 复制代码
ActivityTaskManagerService atm = mSystemServiceManager.startService(
                ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                mSystemServiceManager, atm);

由SystemServiceManager启动具体的服务,从代码可以看出这里启动的是ActivityTaskManagerService.Lifecycle,并没有直接启动ActivityTaskManagerService。这是因为ActivityTaskManagerService只能有一个父类,要继承IActivityTaskManager.Stub,如果想要使用SystemService统一管理atms服务,但atms又无法在继承SystemService。因此需要实现了一个内部静态内部类Lifecycle来继承SystemService并且实例化ActivityTaskManagerService。

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {.....}

java 复制代码
public static final class Lifecycle extends SystemService {
    private final ActivityTaskManagerService mService;

    public Lifecycle(Context context) {
        super(context);
        mService = new ActivityTaskManagerService(context);
    }

    @Override
    public void onStart() {
        publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
        mService.start();
    }

    public ActivityTaskManagerService getService() {
        return mService;
    }
}

然后通过publishBinderService将服务公布到了ServiceManager中,application就可以通过ServiceManager拿到AMS进行通信

publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);

二、AMS 的启动

在ams的start函数中,初始化了很多服务,还添加了很多服务到servicemanager中

java 复制代码
private void start() {
    removeAllProcessGroups();
    mProcessCpuThread.start();//启动cpu监控线程

    mBatteryStatsService.publish();//注册电池状态和权限管理服务
    mAppOpsService.publish();
    Slog.d("AppOps", "AppOpsService published");
    LocalServices.addService(ActivityManagerInternal.class, mInternal);
    mActivityTaskManager.onActivityManagerInternalAdded();
    mPendingIntentController.onActivityManagerInternalAdded();
    // Wait for the synchronized block started in mProcessCpuThread,
    // so that any other access to mProcessCpuTracker from main thread
    // will be blocked during mProcessCpuTracker initialization.
    try {
        mProcessCpuInitLatch.await();
    } catch (InterruptedException e) {
        Slog.wtf(TAG, "Interrupted wait during start", e);
        Thread.currentThread().interrupt();
        throw new IllegalStateException("Interrupted wait during start");
    }
}

//初始化电源管理服务
SystemServer.java   mActivityManagerService.initPowerManagement
//核心内容,为APP进程安排系统进程以便后期监控
SystemServer.java    mActivityManagerService.setSystemProcess();
java 复制代码
public void setSystemProcess() {
    try {
        //添加ams服务到ServiceManager
        ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
        //添加ProcessStats服务到ServiceManager
        ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
        //添加meminfo服务到ServiceManager
        ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
                DUMP_FLAG_PRIORITY_HIGH);
        //添加gfxinfo服务到ServiceManager  图像信息
        ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
        //添加dbinfo服务到ServiceManager  数据库信息
        ServiceManager.addService("dbinfo", new DbBinder(this));
        if (MONITOR_CPU_USAGE) {
            //添加cpuinfo服务到ServiceManager  cpu信息
            ServiceManager.addService("cpuinfo", new CpuBinder(this),
                    /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
        }
        //添加permission服务到ServiceManager  权限和进程信息
        ServiceManager.addService("permission", new PermissionController(this));
        //添加processinfo服务到ServiceManager  进程信息
        ServiceManager.addService("processinfo", new ProcessInfoService(this));
        //添加cacheinfo服务到ServiceManager  缓存信息
        ServiceManager.addService("cacheinfo", new CacheBinder(this));

        ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
        mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

        synchronized (this) {
            //创建ProcessRecord维护进程的相关信息
            ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
                    false,
                    0,
                    new HostingRecord("system"));
            app.setPersistent(true);
            app.pid = app.mPidForCompact = MY_PID;
            app.getWindowProcessController().setPid(MY_PID);
            app.maxAdj = ProcessList.SYSTEM_ADJ;
            app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
            addPidLocked(app);
            mProcessList.updateLruProcessLocked(app, false, null);
            updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
        }
    } catch (PackageManager.NameNotFoundException e) {
        throw new RuntimeException(
                "Unable to find android system package", e);
    }

    // Start watching app ops after we and the package manager are up and running.
    mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
            new IAppOpsCallback.Stub() {
                @Override public void opChanged(int op, int uid, String packageName) {
                    if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
                        if (getAppOpsManager().checkOpNoThrow(op, uid, packageName)
                                != AppOpsManager.MODE_ALLOWED) {
                            runInBackgroundDisabled(uid);
                        }
                    }
                }
            });

    final int[] cameraOp = {AppOpsManager.OP_CAMERA};
    mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() {
        @Override
        public void opActiveChanged(int op, int uid, String packageName, boolean active) {
            cameraActiveChanged(uid, active);
        }
    });
}

三、Application 进程启动流程

在做activity流程分析之前,先明确一下AMS和ATMS的不同,ATMS是在android 11版本从AMS中分离出来的

ATMS:只做activity的管理

AMS:管理四大组件

首先看下Activity启动的流程图

启动方式一般有两种

1.在launcher里面点击启动

2.在某一个app里面去启动另外一个app

APP进程的启动

在启动activity时会判断进程是否存在

ActivityStackSupervisor.java

java 复制代码
void startSpecificActivity(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;
    //进程创建的情况下直接启动activity
    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;
    }

    r.notifyUnknownVisibilityLaunchedForKeyguardTransition();

    final boolean isTop = andResume && r.isTopRunningActivity();
    //进程不存在,为app启动一个进程
    mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
}

ActivityStackSupervisor.java startSpecificActivity(判断app进程是否存在,存在时启动activity,不存在时去创建进程) -》

ActivityManagerService.java -> LocalService -> startProcess -》

startProcessLocked-》

ProcessList.java . startProcessLocked (这里会经过多个startProcessLocked )-》

startProcess-》

Process.start-》

ZYGOTE_PROCESS.start-》

startViaZygote-》

zygoteSendArgsAndGetResult-》

attemptZygoteSendArgsAndGetResult-》

zygoteWriter.write(msgStr); 发送socket消息给zygote

可以看到startProcessLocked最后返回一个ProcessRecord,processrecord就是进程在ams层面的表现形式。所有的ProcessRecord都由mProcessList进行统一管理。

ProcessList.java中有个mLruProcesses维持所有正在运行的进程。

java 复制代码
/**
 * List of running applications, sorted by recent usage.
 * The first entry in the list is the least recently used.
 */
final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>();

在zygote进程中,启动了socket服务器去监听消息

java 复制代码
zygoteServer = new ZygoteServer(isPrimaryZygote);
caller = zygoteServer.runSelectLoop(abiList);

runSelectLoop-》

Zygote.forkAndSpecialize-》

nativeForkAndSpecialize-》

com_android_internal_os_Zygote_nativeForkAndSpecialize-》

fork-》

pid ==0表示子进程

-》zygoteServer.closeServerSocket();关掉socket服务器,避免多服务器问题-》

handleChildProc-》

ZygoteInit.zygoteInit-》

java 复制代码
public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
        String[] argv, ClassLoader classLoader) {
    if (RuntimeInit.DEBUG) {
        Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
    }

    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
    RuntimeInit.redirectLogStreams();

    RuntimeInit.commonInit();//初始化运行环境
    ZygoteInit.nativeZygoteInit();//启动Binder
    return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
            classLoader);
}

RuntimeInit.commonInit();//初始化运行环境

ZygoteInit.nativeZygoteInit();-》

app_main.cpp onZygoteInit-》

new ProcessState->

mDriverFD(open_driver(driver) //初始化binder驱动

proc->startThreadPool //启动Binder线程池

RuntimeInit.applicationInit -》

findStaticMain-》

getMethod //这里通过反射找到ActivityThread中的main函数

最后在ZygoteInit.java中会调用caller.run();在通过invoke调用main函数。

上面代码逻辑画成流程图

四、AMS如何获取application的binder

在ActivityThread.java中创建了ActivityThread对象,调用attch函数将application的binder给到AMS

java 复制代码
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);


private void attach(boolean system, long startSeq) {
......
    if (!system) {
        android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                UserHandle.myUserId());
        final IActivityManager mgr = ActivityManager.getService();
        mgr.attachApplication(mAppThread, startSeq);
......
}

ActivityManagerService.java attachApplication-》

attachApplicationLocked

在attachApplicationLocked核心是类型为ProcessRecord 的 app变量。

同时在ProcessRecord中有一个很重要的变量,如下图。

在attachApplicationLocked中会调用下面这行将thread设置给ProcessRecord

app.makeActive(thread, mProcessStats);

因此后面AMS如果要调用app 的binder,只需要通过

final ProcessList mProcessList = new ProcessList();这个变量拿到

五、AMS用app的binder做了什么?

AMS在将binder传递给ProcessRecord之前,还会调用bindApplication,实际上是调用的ActivityThread.java的bindApplication函数。

构建Application 对象,用Application来管理相关生命周期等

这个函数里面会调用安装provider组件

ams对application的持有链条

然后去调用application的onCreate,这里意味着application已经启动

java 复制代码
mInstrumentation.callApplicationOnCreate(app);

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

最后,在ams中会将app 添加到 mProcessList列表中

java 复制代码
mProcessList.updateLruProcessLocked(app, false, null);

    mLruProcesses.add(index, app);

接下来就会去管理activity的生命周期

java 复制代码
mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);

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

六、Activity生命周期全流程

ActivityStarter类用于解析activity启动参数

ActivityTaskManagerService.java startActivityAsUser -》

getActivityStartController().obtainStarter -》

mFactory.obtain-》mStarterPool.acquire(); 这里从Factory的pool中拿ActivityStarter对象,这样可以减小内存抖动。这里获取ActivityStarter对象后会设置caller等,最后调用execute。

这里的设置变量最后都保存在ActivityStarter的内部类Request中,

java 复制代码
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
        .setCaller(caller)
        .setCallingPackage(callingPackage)
        .setCallingFeatureId(callingFeatureId)
        .setResolvedType(resolvedType)
        .setResultTo(resultTo)
        .setResultWho(resultWho)
        .setRequestCode(requestCode)
        .setStartFlags(startFlags)
        .setProfilerInfo(profilerInfo)
        .setActivityOptions(bOptions)
        .setUserId(userId)
        .execute();

execute-》

executeRequest executeRequest中会读取request中的参数-》

new ActivityRecord

创建出目标ActivityRecord 对象,存到传入数组0索引上。在ams中,这里构建一个activity实例

-》mController.doPendingActivityLaunches(false);

这里去启动因为各种原因导致pending的activity

-》startActivityUnchecked 此次需要启动的activity

-》startActivityInner

java 复制代码
    @VisibleForTesting
    int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, Task inTask,
            boolean restrictedBgActivity, NeededUriGrants intentGrants) {

......

    //判断是否是新任务,如果是,targetTaskTop将为null,否则,targetTaskTop指向目标任务栈中栈顶        没有Finishing的Activity
    final ActivityRecord targetTaskTop = newTask
        ? null : targetTask.getTopNonFinishingActivity();
    if (targetTaskTop != null) {
        // Recycle the target task for this launch.
        startResult = recycleTask(targetTask, targetTaskTop, reusedTask, intentGrants);
        if (startResult != START_SUCCESS) {
            return startResult;
        }
    } else {
        mAddingToTask = true;
    }
.....

    if (mTargetStack == null) {
        mTargetStack = getLaunchStack(mStartActivity, mLaunchFlags, targetTask, mOptions);
    }
    //调用RootTask,startActivity
    mTargetStack.startActivityLocked(mStartActivity,
        topStack != null ? topStack.getTopNonFinishingActivity() : null, newTask,

}

-》mTargetStack.startActivityLocked 启动黑白屏

-》mRootWindowContainer.resumeFocusedStacksTopActivities

RootWindowContainer是窗口容器(WindowContainer)的根容器,管理了所有窗口容器,

设备商所有的窗口(Window)、显示(Display)都是由它来管理的

//resumeFocusedStacksTopActivities 会恢复对应任务栈顶部的Activity

-》resumeTopActivityUncheckedLocked

//开始activity的协议阶段,在栈中进行管理activity

-》startPausingLocked

如果有正在运行的activity,执行它的onpause生命周期

-》next.attachedToProcess() 这里判断为false

-》mStackSupervisor.startSpecificActivity ActivityStackSupervisor是管理activitystack的类

将activity启动封装成一个事务,事务最终要传递给App

-》realStartActivityLocked 进程存在直接进入启动activity

-》

java 复制代码
//组要包含两个内容:一个是要处理的一系列的生命周期事件
//还有一个是这个Client在执行一系列事件后最终的LifeCycle状态
//一系列的事件是由callback的列表控制,而最终的lifecycle状态则由mLifecycleStateRequest控制

public class ClientTransaction implements Parcelable, ObjectPoolItem {
...
    /** A list of individual callbacks to a client. */
    @UnsupportedAppUsage
    private List<ClientTransactionItem> mActivityCallbacks;

    /** Target client activity. Might be null if the entire transaction is targeting an app. */
    //目标进程的activity
    private IBinder mActivityToken;


    /** Target client. */
    //目标进程
    private IApplicationThread mClient;
}


boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
    boolean andResume, boolean checkConfig) throws RemoteException {
    //创建ClientTransaction对象
    final ClientTransaction clientTransaction = ClientTransaction.obtain(proc.getThread(), r.appToken);

    //添加LaunchActivityItem
    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()));

    final ActivityLifecycleItem lifecycleItem;
    if (andResume) {
        lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
    } else {
        lifecycleItem = PauseActivityItem.obtain();
    }
    clientTransaction.setLifecycleStateRequest(lifecycleItem);

    // Schedule transaction.
    //获取生命周期管理类  ClientLifeCycleManager,并执行事务
    mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}
java 复制代码
/**
 * Schedule a transaction, which may consist of multiple callbacks and a lifecycle request.
 * @param transaction A sequence of client transaction items.
 * @throws RemoteException
 *
 * @see 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();
    }
}


//通过mClient 也就是IApplicationThread跨进程调用到应用进程
/**
 * Schedule the transaction after it was initialized. It will be send to client and all its
 * individual parts will be applied in the following sequence:
 * 1. The client calls {@link #preExecute(ClientTransactionHandler)}, which triggers all work
 *    that needs to be done before actually scheduling the transaction for callbacks and
 *    lifecycle state request.
 * 2. The transaction message is scheduled.
 * 3. The client calls {@link TransactionExecutor#execute(ClientTransaction)}, which executes
 *    all callbacks and necessary lifecycle transitions.
 */
public void schedule() throws RemoteException {
    mClient.scheduleTransaction(this);
}

从这里开始一次垮进程调用,调用到ActivityThread.java里面的scheduleTransaction

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

//最终执行到ActivityThread.java中

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;

TransactionExecutor.java execute

这里的executeCallbacks 和executeLifecycleState执行的都是ams中添加后过来的,下面先看executeCallbacks流程

java 复制代码
    public void execute(ClientTransaction transaction) {
        ......

        executeCallbacks(transaction);

        executeLifecycleState(transaction);
        mPendingActions.clear();
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
    }

-》executeCallbacks

java 复制代码
//遍历callbacks数组
for (int i = 0; i < size; ++i) {
    //从callbacks数组中取出item
    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);
    }
    //调用launchActivityItem的execute方法
    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);
    }
}

-》item.execute

-》LaunchActivityItem.java

java 复制代码
    @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, mFixedRotationAdjustments);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
java 复制代码
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);
}


//activity的真实实例
    /** Activity client record, used for bookkeeping for the real {@link Activity} instance. */
    public static final class ActivityClientRecord {

}

-》performLaunchActivity

-》

java 复制代码
activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);

-》

java 复制代码
//会在这个方法中创建Activity的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);

-》

java 复制代码
{
............
                //设置mLifecycleState为ON_CREATE,调用activity的onCreate
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                if (!activity.mCalled) {
                    throw new SuperNotCalledException(
                        "Activity " + r.intent.getComponent().toShortString() +
                        " did not call through to super.onCreate()");
                }
                r.activity = activity;
                mLastReportedWindowingMode.put(activity.getActivityToken(),
                        config.windowConfiguration.getWindowingMode());
            }
            //设置mLifecycleState 为ON_CREATE
            r.setState(ON_CREATE);

再看executeLifecycleState流程

java 复制代码
    private void executeLifecycleState(ClientTransaction transaction) {
        //获取ActivityLifeCycleItem,这里获取的是我们之前添加的ResumeActivityItem
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        if (lifecycleItem == null) {
            // No lifecycle request, return early.
            return;
        }

............

        // Cycle to the state right before the final requested state.
        //ResumeActivityItem 的getTargetState 是ON_RESUME
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);


        // Execute the final transition with proper parameters.
        //执行ResumeActivityItem的execute
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }

executeLifecycleState去获取ActivityLifecycleItem的值,这个值是在构建clientTransaction时在ActivityStackSupervisor.java中设置的

java 复制代码
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
    lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
} else {
    lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);

然后进入cycleToPath函数

java 复制代码
private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
        ClientTransaction transaction) {
    final int start = r.getLifecycleState();//这里的start是ON_CREATE
    if (DEBUG_RESOLVER) {
        Slog.d(TAG, tId(transaction) + "Cycle activity: "
                + getShortActivityName(r.token, mTransactionHandler)
                + " from: " + getStateName(start) + " to: " + getStateName(finish)
                + " excludeLastState: " + excludeLastState);
    }
    //这里的start是ON_CREATE,finish是ON_RESUME
    //调用getLifecyclePath返回的path包含ON_START  和  ON_RESUME
    //这里是Activity 执行onStart 函数的关键所在
    final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
    //执行path中的相关的生命周期函数
    performLifecycleSequence(r, path, transaction);
}

-》mHelper.getLifecyclePath

-》

java 复制代码
if (finish >= start) {//走到此分支  3 >= 1
    if (start == ON_START && finish == ON_STOP) {
        // A case when we from start to stop state soon, we don't need to go
        // through the resumed, paused state.
        mLifecycleSequence.add(ON_STOP);
    } else {
        // just go there
        // start 为 1,i <= 3,add会将 2 3 都加入到mlifecyclesqquence中
        for (int i = start + 1; i <= finish; i++) {
            mLifecycleSequence.add(i);
        }
    }

    // Remove last transition in case we want to perform it with some specific params.
    //因为excludeLastState 为true,所以删除掉ON_RESUME状态
    if (excludeLastState && mLifecycleSequence.size() != 0) {
        mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
    }
}
java 复制代码
private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
        ClientTransaction transaction) {

//通过mHelper调用getLifecyclePath返回的path,是ON_START
state = path.get(i);
switch (state) {
....
    case ON_START:
    mTransactionHandler.handleStartActivity(r.token, mPendingActions);
}
....
}

-》activity.performStart

-》ResumeActivityItem.java lifecycleItem.execute

-》client.handleResumeActivity

-》ActivityThread.java handleResumeActivity

-》performResumeActivity

-》r.activity.performResume

MainActivity启动流程-生命周期触发器触发执行阶段

启动activity的activity stop阶段

activity resume之后,往handler里面添加了一个事件

java 复制代码
Looper.myQueue().addIdleHandler(new Idler());
java 复制代码
private class Idler implements MessageQueue.IdleHandler {
    @Override
    public final boolean queueIdle() {
.......
        if (a != null) {
            mNewActivities = null;
            IActivityTaskManager am = ActivityTaskManager.getService();
            ActivityClientRecord prev;
            do {
                if (localLOGV) Slog.v(
                    TAG, "Reporting idle of " + a +
                    " finished=" +
                    (a.activity != null && a.activity.mFinished));
                if (a.activity != null && !a.activity.mFinished) {
                    try {
                        am.activityIdle(a.token, a.createdConfig, stopProfiling);
                        a.createdConfig = null;
                    } catch (RemoteException ex) {
                        throw ex.rethrowFromSystemServer();
                    }
                }
                prev = a;
                a = a.nextIdle;
                prev.nextIdle = null;
            } while (a != null);
        }
...........
    }
}

可以看到,在handler空闲阶段,会去执行ams里面的activityIdle

-》mStackSupervisor.activityIdleInternal

-》processStoppingAndFinishingActivities

java 复制代码
private void processStoppingAndFinishingActivities(ActivityRecord launchedActivity,
        boolean processPausingActivities, String reason) {

    //在这个数组里面遍历需要暂停的activity
    for (int i = mStoppingActivities.size() - 1; i >= 0; --i) {
        final ActivityRecord s = mStoppingActivities.get(i);
        final boolean animating = s.isAnimating(TRANSITION | PARENTS,
                ANIMATION_TYPE_APP_TRANSITION | ANIMATION_TYPE_RECENTS);
        if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + s.nowVisible
                + " animating=" + animating + " finishing=" + s.finishing);
        if (!animating || mService.mShuttingDown) {
            if (!processPausingActivities && s.isState(PAUSING)) {
                // Defer processing pausing activities in this iteration and reschedule
                // a delayed idle to reprocess it again
                removeIdleTimeoutForActivity(launchedActivity);
                scheduleIdleTimeout(launchedActivity);
                continue;
            }

            if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
            if (readyToStopActivities == null) {
                readyToStopActivities = new ArrayList<>();
            }
            readyToStopActivities.add(s);

            mStoppingActivities.remove(i);
        }
    }

    //轮询然后调用stop 或 destroy
    for (int i = 0; i < numReadyStops; i++) {
        final ActivityRecord r = readyToStopActivities.get(i);
        if (r.isInHistory()) {
            if (r.finishing) {
                // TODO(b/137329632): Wait for idle of the right activity, not just any.
                r.destroyIfPossible(reason);
            } else {
                r.stopIfPossible();
            }
        }
    }


}

-》stopIfPossible

-》mAtmService.getLifecycleManager().scheduleTransaction

-》ClientLifecycleManager.java scheduleTransaction 封装ClientTransaction

java 复制代码
void scheduleTransaction(@NonNull IApplicationThread client,
        @NonNull ClientTransactionItem callback) throws RemoteException {
    final ClientTransaction clientTransaction = transactionWithCallback(client,
            null /* activityToken */, callback);
    scheduleTransaction(clientTransaction);
}
相关推荐
敲代码敲到头发茂密1 小时前
【大语言模型】LangChain 核心模块介绍(Memorys)
android·语言模型·langchain
H1002 小时前
重构(二)
android·重构
拓端研究室2 小时前
R基于贝叶斯加法回归树BART、MCMC的DLNM分布滞后非线性模型分析母婴PM2.5暴露与出生体重数据及GAM模型对比、关键窗口识别
android·开发语言·kotlin
zhangphil3 小时前
Android简洁缩放Matrix实现图像马赛克,Kotlin
android·kotlin
m0_512744643 小时前
极客大挑战2024-web-wp(详细)
android·前端
lw向北.3 小时前
Qt For Android之环境搭建(Qt 5.12.11 Qt下载SDK的处理方案)
android·开发语言·qt
不爱学习的啊Biao3 小时前
【13】MySQL如何选择合适的索引?
android·数据库·mysql
Clockwiseee4 小时前
PHP伪协议总结
android·开发语言·php
mmsx10 小时前
android sqlite 数据库简单封装示例(java)
android·java·数据库
众拾达人13 小时前
Android自动化测试实战 Java篇 主流工具 框架 脚本
android·java·开发语言