Android 11 (R)AMS Activity内部机制

news2024/11/13 15:55:36

一、AMS是如何被管理的

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

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 {.....}

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中

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

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维持所有正在运行的进程。

/**
 * 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服务器去监听消息

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-》

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

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已经启动

mInstrumentation.callApplicationOnCreate(app);

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

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

mProcessList.updateLruProcessLocked(app, false, null);

    mLruProcesses.add(index, app);

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

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中,

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

    @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

-》


//组要包含两个内容:一个是要处理的一系列的生命周期事件
//还有一个是这个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);
}

/**
 * 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流程

    public void execute(ClientTransaction transaction) {
        ......

        executeCallbacks(transaction);

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

-》executeCallbacks

//遍历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   

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

-》

activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);

-》

//会在这个方法中创建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);

-》

{
............
                //设置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流程

    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中设置的

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

然后进入cycleToPath函数

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

        -》

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

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里面添加了一个事件

Looper.myQueue().addIdleHandler(new Idler());

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

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

void scheduleTransaction(@NonNull IApplicationThread client,
        @NonNull ClientTransactionItem callback) throws RemoteException {
    final ClientTransaction clientTransaction = transactionWithCallback(client,
            null /* activityToken */, callback);
    scheduleTransaction(clientTransaction);
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2103114.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

10、Django Admin修改标题

admin from django.contrib import admin from .models import Category, Origin, Hero, Villain # 添加以下代码 admin.site.site_header "系统管理" admin.site.site_title "管理员界面" admin.site.index_title "欢迎来到这里&#xff…

嵌入式:Keil调试时,Memory窗口的更新时机

相关阅读嵌入式https://blog.csdn.net/weixin_45791458/category_12768532.html?spm1001.2014.3001.5482 在Keil中调试程序时&#xff0c;Memory窗口是一个很有用的工具&#xff08;它们由调试器厂商提供并嵌入IDE&#xff09;&#xff0c;可以实时显示存储器中的数据值&#…

gcc编译与Linux下的库

gcc与g编译 GCC&#xff1a;GCC是一个由GNU项目开发的多平台编译器&#xff0c;最初是为C语言设计的编译器&#xff0c;但随着时间的发展&#xff0c;它已经扩展到支持多种编程语言。它支持多种编程语言&#xff0c;包括C、C、Objective-C、Fortran、Ada和Go等。GCC是自由软件&…

linux文件的拓展属性

一、概述 文件的扩展属性&#xff08;EA&#xff09; 即以名称-值对形式将任意元数据与文件 i 节点关联 起来的技术。 2. EA 可用于实现访问列表&#xff08;第 17 章&#xff09;和文件能力&#xff08;第 39 章&#xff09;。 二、EA 命名空间 EA 的命名格式为 namespace…

C++重载实现Mystring

#include<iostream> #include<cstring> //可以使用string类 #include<string> //#include <string.h>using namespace std;class Mystring {public:Mystring():str(nullptr), len(0){}Mystring(const char *const str1){if (str1){len s…

Datawhale X 李宏毅苹果书AI夏令营 学习笔记

学习日志 日期&#xff1a; 2024年9月3日 今日学习内容&#xff1a; 今天&#xff0c;我深入学习了深度学习中的几种重要概念&#xff0c;包括优化算法、特征归一化、以及批量归一化的原理和应用。这次学习的内容涵盖了从基础的梯度下降法到更高级的优化技术&#xff0c;同时…

【Linux系统编程】TCP实现--socket

使用套接字socket实现服务器和客户端之间的TCP通信。 流程如下&#xff1a; 实现代码&#xff1a; /* server.c */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <arpa/inet.h> #include <s…

分类预测|基于麻雀优化正则化极限学习机的数据分类预测Matlab程序SSA-RELM 多特征输入多类别输出

分类预测|基于麻雀优化正则化极限学习机的数据分类预测Matlab程序SSA-RELM 多特征输入多类别输出 文章目录 一、基本原理1. 数据准备2. RELM模型建立3. SSA优化RELM参数4. 模型训练5. 模型评估6. 结果分析与应用原理总结 二、实验结果三、核心代码四、代码获取五、总结 分类预测…

在Ubuntu上运行QtCreator相关程序

背景&#xff1a;希望尝试在Linux系统上跑一下使用QtCreator相关的程序&#xff0c;因为有一些工作岗位要求有Linux上使用Qt的经验。 (1)我是把Windows上的程序移过来的&#xff0c;Windows上文件名称是不区分大小写的。 而Ubuntu上是区分的 所以一部分头文件需要进行修改&am…

大数据Flink(一百一十二):Flink SQL作业快速入门

文章目录 Flink SQL作业快速入门 一、进入Flink开发平台 二、​​​​​​​创建作业 三、​​​​​​​​​​​​​​编写作业代码 四、​​​​​​​​​​​​​​进行更多配置 五、​​​​​​​​​​​​​​进行深度检查 六、​​​​​​​​​​​​​​进…

AWS SES服务 Golang接入教程(排坑版)

因为刚来看的时候 也迷迷糊糊的 所以 先讲概念 再上代码 一 基础设置 这里需要完成两个最基础的设置任务 1 是验证至少一个收件电子邮箱 2 【很关键】是验证发送域。即身份里的域类型的身份。&#xff08;可以理解为配置你的域名邮箱服务器&#xff08;SMPT&#xff09;为亚马…

PMP–一、二、三模、冲刺、必刷–分类–14.敏捷–技巧--累积流图

文章目录 技巧一模二模三模14.敏捷–敏捷团队的衡量结果–累积流图&#xff1a;1、 敏捷项目的项目经理担心团队在最近的迭代中失去了动力。项目经理应该使用哪两种工具来分析团队绩效&#xff1f;&#xff08;选择两个&#xff09; 冲刺必刷7.成本管理--挣值分析燃尽图仅能了解…

Trm理论 3(ELMo)

LSTM模型 如图&#xff0c;LSTM模型是rnn模型的改良版&#xff0c;通过ft来选择性的保留上一次得到的信息 ELMo模型&#xff08;双向LSTM&#xff09; ELMo模型是对word2vec的改良&#xff0c;改良了word2vec的二义性 对比上下两图&#xff0c;可以发现&#xff0c;WE对预测…

基于约束大于规范的想法,封装缓存组件

架构&#xff1f;何谓架构&#xff1f;好像并没有一个准确的概念。以前我觉得架构就是搭出一套完美的框架&#xff0c;可以让其他开发人员减少不必要的代码开发量&#xff1b;可以完美地实现高内聚低耦合的准则;可以尽可能地实现用最少的硬件资源&#xff0c;实现最高的程序效率…

Linux文件【系统调用接口及进程中对打开文件的管理操作】详细讲解

目录 一、open函数 1.介绍 2.open函数返回值 二、重定向 1.文件描述符的分配规则 2.重定向的本质 3.dup2系统调用 三、C语言库函数中的缓冲区及不同刷新模式 前言&#xff1a; 我们先来简单回顾一下C语言中的文件相关知识 ● 打开文件的方式 r …

数图亮相第三届中国区域零售创新峰会:共绘零售新蓝图,携手迈向新征程

8月31日&#xff0c;备受瞩目的第三届中国区域零售创新峰会在历史悠久的湖北襄阳圆满落下帷幕。在这场零售行业的盛会上&#xff0c;数图信息科技作为重要参会企业&#xff0c;积极参与其中&#xff0c;与众多行业精英共聚一堂&#xff0c;共同擘画零售业的宏伟蓝图。以下是本次…

C程序设计——指针杂谈0

变量和常量讲的差不多了&#xff0c;这里先把指针再深入理解一下&#xff0c;如果你是C语言初学者&#xff0c;本节可能看不太懂&#xff0c;没关系可以以后再看。 变量 当定义变量的时候&#xff0c;本质是在内存中分配了一段空间&#xff0c;这段空间的大小与变量的类型相关…

GD - EmbeddedBuilder - 给已有工程换MCU

文章目录 GD - EmbeddedBuilder - 给已有工程换MCU概述不行的重现 笔记工程的.gdc文件内容中有MCU型号可以改 给已有工程换MCU的使用场景END GD - EmbeddedBuilder - 给已有工程换MCU 概述 一个现存的EmbeddedBuilder的工程&#xff0c;想换个MCU配置做实验&#xff0c;又不想…

极盾故事|某金融租赁机构应用数据保护新策略:“动态脱敏”“二次授权”

数据的流通使用是创新的动力&#xff0c;但安全和合规是不可逾越的底线。企业如何在这三者之间找到平衡点&#xff1f; 极盾科技&#xff0c;助力某金融租赁机构&#xff0c;基于极盾觅踪构建应用数据动态脱敏系统&#xff0c;实现10&#xff0b;核心应用系统的统一管理&#x…

库(Library)

库的定义 在Linux操作系统中&#xff0c;库&#xff08;Library&#xff09;是一段编译好的、可重用的代码&#xff0c;它能够被其他程序或应用程序在运行时调用。库可以提高代码的模块化&#xff0c;使得开发者可以共享和重用代码&#xff0c;从而提高开发效率&#xff0c;减少…