Android 11 (R)AMS Activity内部机制

一、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);}@Overridepublic 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服务到ServiceManagerServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);//添加ProcessStats服务到ServiceManagerServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);//添加meminfo服务到ServiceManagerServiceManager.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() {@Overridepublic 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;//进程创建的情况下直接启动activityif (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();//启动Binderreturn 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

    @VisibleForTestingint 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的Activityfinal 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,startActivitymTargetStack.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. */@UnsupportedAppUsageprivate List<ClientTransactionItem> mActivityCallbacks;/** Target client activity. Might be null if the entire transaction is targeting an app. *///目标进程的activityprivate 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);//添加LaunchActivityItemclientTransaction.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里面的scheduleTransactionpublic 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数组中取出itemfinal 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   

    @Overridepublic 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的onCreateif (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_CREATEr.setState(ON_CREATE);

再看executeLifecycleState流程

    private void executeLifecycleState(ClientTransaction transaction) {//获取ActivityLifeCycleItem,这里获取的是我们之前添加的ResumeActivityItemfinal 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_RESUMEcycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);// Execute the final transition with proper parameters.//执行ResumeActivityItem的executelifecycleItem.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_CREATEif (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 >= 1if (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 {@Overridepublic 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) {//在这个数组里面遍历需要暂停的activityfor (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 againremoveIdleTimeoutForActivity(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 或 destroyfor (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.rhkb.cn/news/415950.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

名城优企游学活动走进龙腾半导体:CRM助力构建营销服全流程体系

8月29日&#xff0c;由纷享销客主办的“数字中国 高效增长——名城优企游学系列活动之走进龙腾半导体”研讨会在西安市圆满落幕&#xff0c;来自业内众多领袖专家参与本次研讨会&#xff0c;深入分享交流半导体行业的数字化转型实践&#xff0c;探讨行业数字化、智能化转型之路…

Linux【3】文件目录进阶

目录 cd 回到家目录 在最近两次目录来回切花 相对路径&#xff1a;从当前位置开始&#xff0c;前面没有/ or ~ mkdir rm 不可恢复 删除目录 -f 有则删&#xff0c;无也不报错 ls通配符仍适用&#xff01;【批量删除】 cd 回到家目录 cd cd ~ 在最近两次目录来回…

Python 数据分析— Pandas 基本操作(上)

文章目录 学习内容&#xff1a;一、Series 创建及操作二、DataFram 的创建与操作三、Pandas 的读写操作四、选择指定行列数据 学习内容&#xff1a; 一、Series 创建及操作 ** Series : Pandas 的一种数据结构形式&#xff0c;可理解为含有索引的一维数组。** **&#xff08;…

【Altium Designer脚本开发】——PCB平面绕组线圈 V1.4

PCB平面绕组线圈工具用于生成平面电机线圈&#xff0c;应用场景可参考平面电机的书籍、CNKI论文或平面电机的视频。此工具运行环境在Altium Designer中&#xff0c;可用于Altium Designer全系列的版本中。 以下工具可以定制和试用 原理图文档处理工具 ➡️物料编码自动查找工具…

c++ 156函数

inline内联函数 #include<iostream> using namespace std;inline void printA() {int a 10;cout << "a:" << a << endl;}void main() {//printA();//c编译器会这样 把函数体机械地放到main函数里面{int a 10;cout << "a:"…

云计算之ECS

目录 一、ECS云服务器 1.1 ECS的构成 1.2 ECS的实例规格 1.3 镜像 1.4 磁盘 1.5 安全组 1.6 网络 1.7 产品结构 二、块存储介绍 2.1 快存储定义 2.2 块存储性能指标 2.3 快存储常用操作-云盘扩容 2.4 块存储常见问题 三、快照介绍 3.1 快照定义 3.2 快照常见问题…

tomcat架构设计分析,核心组件详解

提示&#xff1a;tomcat整体架构分析&#xff0c;tomcat核心组件详解、tomcat请求全流程、tomcat设计模式分析。责任链模式设计、tomcat设计详解、tomcat调优的前置文档 文章目录 前言一、相关概念1、tomcat的概念2、web应用部署的3种方式 二、tomcat的整体架构1、tomcat架构图…

家教管理系统设计与实现

摘 要 传统办法管理信息首先需要花费的时间比较多&#xff0c;其次数据出错率比较高&#xff0c;而且对错误的数据进行更改也比较困难&#xff0c;最后&#xff0c;检索数据费事费力。因此&#xff0c;在计算机上安装家教管理系统软件来发挥其高效地信息处理的作用&#xff0c…

[论文笔记]RAFT: Adapting Language Model to Domain Specific RAG

引言 今天带来一篇结合RAG和微调的论文&#xff1a;RAFT: Adapting Language Model to Domain Specific RAG。 为了简单&#xff0c;下文中以翻译的口吻记录&#xff0c;比如替换"作者"为"我们"。 本文介绍了检索增强微调(Retrieval Augmented Fine Tunin…

Opencv中的直方图(4)局部直方图均衡技术函数createCLAHE()的使用

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 创建一个指向 cv::CLAHE 类的智能指针并初始化它。 函数原型 Ptr<CLAHE> cv::createCLAHE (double clipLimit 40.0,Size tileGridSize…

house of cat

文章目录 house of cat概述&#xff1a;_IO_wfile_jumps进入_IO_wfile_seekoffFSOP__malloc_assert 例题&#xff1a;思路&#xff1a;分析&#xff1a;利用&#xff1a; house of cat 概述&#xff1a; house of cat主要的摸底还是覆盖vtable指针&#xff0c;因为在glibc-2.2…

DrissionPage设置启动浏览器为edge

1.查看浏览器启动路径 在浏览器地址栏输入下面地址&#xff0c;拿到可执行文件的路径 。 edge://version/ 2.替换路径 打开DrissionPage._configs. chromium_options.py文件&#xff0c;找到def browser_path(self)这个函数&#xff0c;将返回内容替换为edge的启动路径&#x…

轿厢电梯-电动车检测数据集(真实电梯监控)

轿厢电动车检测数据集&#xff0c; 可做电梯乘客、电动车检测任务。 数据集由真实电梯监控图片&#xff08;大约四千&#xff09;、电动车网图、手机拍摄图片构成&#xff0c;总计14000张左右&#xff0c;其中近8000样本已标注。 注&#xff1a;文件夹后面数字为对应数据集样本…

论斜率优化dp

论斜率优化dp 1问题2暴力算法-线性dp3斜率优化线性dp4后记 1问题 如下图 看到这题&#xff0c;题面很复杂 其实可以转化为如下问题 有 n n n个任务&#xff0c;排成一个有序序列&#xff0c;我们要解决这些任务 总费用是每一个任务的完成时间乘以费用系数求和 每个任务之前…

紫金大数据平台架构之路(一)----大数据任务开发和调度平台架构设计

一、总体设计 初来公司时&#xff0c;公司还没有大数据&#xff0c;我是作为大数据架构师招入的&#xff0c;结合公司的线上和线下业务&#xff0c;制定了如下的大数据架构路线图。 二、大数据任务开发和调度平台架构设计 在设计完总体架构后&#xff0c;并且搭建完hadoop/ya…

Python基础语法(多进程开发进程建数据共享进程锁进程池)

Python基础语法文章导航&#xff1a; Python基础&#xff08;01初识数据类型&变量&#xff09;Python基础&#xff08;02条件&循环语句&#xff09;Python基础&#xff08;03字符串格式化&运算符&进制&编码&#xff09;Python基础&#xff08;04 基础练习…

Marin说PCB之闲谈设计经验之沟通

今天这期小编我不讲解技术&#xff0c;主要是分享一些个人的工作中的一些经验吧&#xff0c;首先给诸位分享的就是小编我的学的降龙十八掌第一式&#xff1a;沟通&#xff0c;为啥要说沟通是第一个我要说的话题呢&#xff0c;这个说来话长了&#xff0c;小编我就长话短说了。 因…

Rust: Web框架Axum和Rest Client协同测试

Axum作为Rust当红Web框架&#xff0c;值得了解一下。下面实例包括几个典型的常场场景。 具体如下&#xff1a; 一、Axum 1、toml中依赖 [dependencies] tokio {version"1.39.3",features ["full"]} axum {version "0.7.5",features ["to…

OceanBase 关于 place_group_by HINT的使用

PLACE_GROUP_BY Hint 表示在多表关联时&#xff0c;如果满足单表查询后直接进行group by 的情形下&#xff0c;在跟其它表进行关联统计&#xff0c;减少表内部联接。 NO_PLACE_GROUP_BY Hint 表示在多表关联时&#xff0c;在关联后才对结果进行group by。 使用place_group_by …

html+css+js网页设计 故宫10个页面 ui还原度100%

htmlcssjs网页设计 故宫10个页面 ui还原度100% 网页作品代码简单&#xff0c;可使用任意HTML编辑软件&#xff08;如&#xff1a;Dreamweaver、HBuilder、Vscode 、Sublime 、Webstorm、Text 、Notepad 等任意html编辑软件进行运行及修改编辑等操作&#xff09;。 获取源码 …