IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 游戏开发 -> ActivityManagerService启动activity流程简析(二) -> 正文阅读

[游戏开发]ActivityManagerService启动activity流程简析(二)

Task.java

??? private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {

? ? ? ...

??????? // 1.获取栈顶的activity

??????? ActivityRecord next = topRunningActivity(true /* focusableOnly */);

? ? ? ...

??????? //确保启动该activity的用户存在

??????? if (!mAtmService.mAmInternal.hasStartedUserState(next.mUserId)) {

??????????? Slog.w(TAG, "Skipping resume of top activity " + next

??????????????????? + ": user " + next.mUserId + " is stopped");

??????????? return false;

??????? }

? ? ? ...

? ? ? ? //暂停当前运行的activity

??????? boolean pausing = taskDisplayArea.pauseBackStacks(userLeaving, next);

??????? if (mResumedActivity != null) {

??????????? if (DEBUG_STATES) Slog.d(TAG_STATES,

??????????????????? "resumeTopActivityLocked: Pausing " + mResumedActivity);

? ? ? ? ? ?//暂停栈顶已激活的activity

??????????? pausing |=?startPausingLocked(userLeaving, false /* uiSleeping */, next);

??????? }

??????? if (pausing) {

?????????? ?if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG_STATES,

??????????????????? "resumeTopActivityLocked: Skip resume: need to start pausing");

? ? ? ? ? ? ? ?...

??????????? if (next.attachedToProcess()) {

? ? ? ? ? ? ? ?...

??????????????? //启动目标Activity

??????????????? mAtmService.getAppWarningsLocked().onResumeActivity(next);

??????????????? next.app.setPendingUiCleanAndForceProcessStateUpTo(mAtmService.mTopProcessState);

??????????????? next.abortAndClearOptionsAnimation();

??????????????? transaction.setLifecycleStateRequest(

??????????????????????? ResumeActivityItem.obtain(next.app.getReportedProcState(),

??????????????????????????????? dc.isNextTransitionForward()));

??????????????? mAtmService.getLifecycleManager().scheduleTransaction(transaction)

? ? ? ? ? ? ? ?...

??????? } else {

??????????? // 进程无关联,需要启动目标activity所在进程

??????????? if (!next.hasBeenLaunched) {

?????? ?????????next.hasBeenLaunched = true;

??????????? } else {

??????????????? if (SHOW_APP_STARTING_PREVIEW) {

??????????????????? next.showStartingWindow(null /* prev */, false /* newTask */,

??????????????????????????? false /* taskSwich */);

????????????? ??}

??????????????? if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Restarting: " + next);

??????????? }

??????????? if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);

??????????? mStackSupervisor.startSpecificActivity(next, true, true);

??????? }

??????? return true;

??? }

获取栈顶已激活的activity进行暂停。

final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,

??????????? ActivityRecord resuming) {

? ? ? ?...

? ? ? ??//获取栈顶已激活的activity

??????? ActivityRecord prev = mResumedActivity;

? ? ? ? ...

??????? if (prev.attachedToProcess()) {

?????????? ?if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev);

??????????? try {

??????????????? EventLogTags.writeWmPauseActivity(prev.mUserId, System.identityHashCode(prev),

??????????????????????? prev.shortComponentName, "userLeaving=" + userLeaving);

? ? ? ? ? ? ? ?...

? ? ? ? ? ? ??//通过Binder机制向应用进程发送消息

??????????????? mAtmService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),

??????????????????????? prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,

??????????????????????????????? prev.configChangeFlags, pauseImmediately));

??????????? } catch (Exception e) {

??????????????? Slog.w(TAG, "Exception thrown during pause", e);

??????????????? mPausingActivity = null;

??????????????? mLastPausedActivity = null;

??????????????? mLastNoHistoryActivity = null;

??????????? }

??????? } else {

??????????? mPausingActivity = null;

??????????? mLastPausedActivity = null;

??????????? mLastNoHistoryActivity = null;

??????? }

? ? ? ?...

??? }

如果栈顶已激活activity的进程存在,开始执行状态转换。

ClientLifecycleManager.java。

??? void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,

??????????? @NonNull ActivityLifecycleItem stateRequest) throws RemoteException {

? ? ? ?//获取ActivityThread代理

??????? final ClientTransaction clientTransaction = transactionWithState(client, activityToken,

??????????????? stateRequest);

????????scheduleTransaction(clientTransaction);

??? }

获取activityThread代理。

??? void scheduleTransaction(ClientTransaction transaction) throws RemoteException {

??????? final IApplicationThread client = transaction.getClient();

??????? transaction.schedule();

??????? if (!(client instanceof Binder)) {

??????????? // 如果client不是Binder实例,则进行回收,在ActivityThread中执行

??????????? transaction.recycle();

??????? }

??? }

ClientTransaction.java.

??? public void schedule() throws RemoteException {

? ? ? ?mClient.scheduleTransaction(this);

??? }

按以下顺序安排事务:

1.主线程调用preExecute,触发所有需要在真正调度事务前执行完毕的工作。
2.发送事务的message到主线程。
3.主线程调用TransactionExecutor.execute,执行所有回调以及必要的生命周期事务。

mClient是ActivityThread的Binder对象,ActivityThread继承ClientTransactionHandler。

ClientTransactionHandler.java

??? void scheduleTransaction(ClientTransaction transaction) {

??????? transaction.preExecute(this);

??????? sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);

? ?}

ActivityThread接收到消息后,会调用TransactionExecutor.execute执行生命周期转换。

TransactionExecutor.java

??? public void execute(ClientTransaction transaction) {

? ? ?...

? ? ? ? executeCallbacks(transaction);

? ? ? ??executeLifecycleState(transaction);

? ? ? ? mPendingActions.clear();

??? }

检查目标状态并执行。

??? private void executeLifecycleState(ClientTransaction transaction) {

??????? final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();

??????? if (lifecycleItem == null) {

??????????? return;

??????? }

??????? final IBinder token = transaction.getActivityToken();

??????? final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);

??????? if (DEBUG_RESOLVER) {

??????????? Slog.d(TAG, tId(transaction) + "Resolving lifecycle state: "

????? ??????????????+ lifecycleItem + " for activity: "

??????????????????? + getShortActivityName(token, mTransactionHandler));

??????? }

??????? if (r == null) {

??????????? return;

???? ???}

? ? ? ? //执行最终状态转换

????????cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);

??????? lifecycleItem.execute(mTransactionHandler, token, mPendingActions);

??????? lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);

??? }

获取目标item,并执行目标item的execute以及postExecute。

PauseActivityItem.java

??? public void execute(ClientTransactionHandler client, ActivityClientRecord r,

??????????? PendingTransactionActions pendingActions) {

??????? Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause");

??????? client.handlePauseActivity(r, mFinished, mUserLeaving, mConfigChanges, pendingActions,

??????????????? "PAUSE_ACTIVITY_ITEM");

??????? Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);

??? }

通过进程间调用,调用到ActivityThread的handlePauseActivity,再调用到performPauseActivity函数。

??? final Bundle performPauseActivity(IBinder token, boolean finished, String reason,

??????????? PendingTransactionActions pendingActions) {

??????? ActivityClientRecord r = mActivities.get(token);

??????? return r != null ??performPauseActivity(r, finished, reason, pendingActions) : null;

??? }

??? private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,

??????????? PendingTransactionActions pendingActions) {

??????? if (r.paused) {

? ? ? ? ...

????????performPauseActivityIfNeeded(r,?reason);

? ? ? ? ...

??????? return shouldSaveState ? r.state : null;

??? }

??? private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {

??????? if (r.paused) {

??????????? // You are already paused silly...

??????????? return;

??????? }

??????? reportTopResumedActivityChanged(r, false /* onTop */, "pausing");

??????? try {

??????????? r.activity.mCalled = false;

??????????? mInstrumentation.callActivityOnPause(r.activity);

???????? ???if (!r.activity.mCalled) {

??????????????? throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)

??????????????????????? + " did not call through to super.onPause()");

??????????? }

??????? } catch (SuperNotCalledException e) {

??????????? throw e;

??????? } catch (Exception e) {

??????????? if (!mInstrumentation.onException(r.activity, e)) {

??????????????? throw new RuntimeException("Unable to pause activity "

??????????????????????? + safeToComponentShortString(r.intent) + ": " + e.toString(), e);

??????????? }

??????? }

??????? r.setState(ON_PAUSE);

??? }

调用到Instrumentation的callActivityOnPause函数中,之后进一步调用到Activity的onPause函数。

PauseActivityItem.java

???? @Override

??? public void?postExecute(ClientTransactionHandler client, IBinder token,

??????????? PendingTransactionActions pendingActions) {

????? ??if (mDontReport) {

??????????? return;

??????? }

? ? ? ? //Binder调用,Activity的onPause已经执行

??????? ActivityClient.getInstance().activityPaused(token);

??? }

调用到ActivityClientController的activityPaused,进一步调用到ActivityRecord的activityPaused。

ActivityRecord.java

??? void activityPaused(boolean timeout) {

??????? ProtoLog.v(WM_DEBUG_STATES, "Activity paused: token=%s, timeout=%b", appToken,

??????????????? timeout);

??????? if (task != null) {

??????????? removePauseTimeout();

??????????? final ActivityRecord pausingActivity = task.getPausingActivity();

??????????? if (pausingActivity == this) {

??????????????? ProtoLog.v(WM_DEBUG_STATES, "Moving to PAUSED: %s %s", this,

??????????????????????? (timeout ? "(due to timeout)" : " (pause complete)"));

??????????????? mAtmService.deferWindowLayout();

??????????????? try {

??????????????????? task.completePauseLocked(true /* resumeNext */, null /* resumingActivity */);

??????????????? } finally {

??????????????????? mAtmService.continueWindowLayout();

??????????????? }

??????????????? return;

??????????? } else {

?????????? ?????EventLogTags.writeWmFailedToPause(mUserId, System.identityHashCode(this),

??????????????????????? shortComponentName, pausingActivity != null

??????????????????????????????? ? pausingActivity.shortComponentName : "(none)");

??????????????? if (isState(PAUSING)) {

??????????????????? setState(PAUSED, "activityPausedLocked");

??????????????????? if (finishing) {

??????????????????????? ProtoLog.v(WM_DEBUG_STATES,

??????????????????????????????? "Executing finish of failed to pause activity: %s", this);

??????????????????????? completeFinishing("activityPausedLocked");

??????????????????? }

??????????????? }

??????????? }

??????? }

??????? mDisplayContent.handleActivitySizeCompatModeIfNeeded(this);

??????? mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);

??? }

Task.java

??? void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {

? ? ? ...

??????? ActivityRecord prev = mPausingActivity;

? ? ? ? ? ? ? ? ...

??????????????? prev.stopFreezingScreenLocked(true /*force*/);

? ? ? ? ? ? ? ?...

??????????? mPausingActivity = null;

??????? }

??????? if (resumeNext) {

??????????? final Task topRootTask = mRootWindowContainer.getTopDisplayFocusedRootTask();

??????????? if (topRootTask != null && !topRootTask.shouldSleepOrShutDownActivities()) {

??????????????? mRootWindowContainer.resumeFocusedTasksTopActivities(topRootTask, prev, null);

? ? ? ? ? ...

??? }

RootWindowContainer.java

??boolean resumeFocusedTasksTopActivities(

? ? ? ? ? ?...

??????????? result |= resumedOnDisplay[0];

??????????? if (!resumedOnDisplay[0]) {

??????????????? final Task focusedRoot = display.getFocusedRootTask();

??????????????? if (focusedRoot != null) {

??????????????????? result |= focusedRoot.resumeTopActivityUncheckedLocked(target, targetOptions);

??????????????? } else if (targetRootTask == null) {

??????????????????? result |= resumeHomeActivity(null /* prev */, "no-focusable-task",

???????????????? ???????????display.getDefaultTaskDisplayArea());

??????????????? }

??????????? }

??????? }

??????? return result;

??? }

??? @GuardedBy("mService")

??? boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options,

??????????? boolean deferPause) {

? ? ? ? ? ? ? ? ...

??????????????????? someActivityResumed |= child.resumeTopActivityUncheckedLocked(prev, options,

??????????????????????????? deferPause);

? ? ? ? ? ? ? ?...

??? }

??? private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options,

??????????? boolean deferPause) {

? ? ? ? ? ? ...?

? ? ? ? if (next.attachedToProcess()) {

? ? ? ? ? ? ...

??????????????? mAtmService.getAppWarningsLocked().onResumeActivity(next);

??????????????? next.app.setPendingUiCleanAndForceProcessStateUpTo(mAtmService.mTopProcessState);

??????????????? next.abortAndClearOptionsAnimation();

??????????????? transaction.setLifecycleStateRequest(

??????????????????????? ResumeActivityItem.obtain(next.app.getReportedProcState(),

??????????????????????????????? dc.isNextTransitionForward()));

??????????????? mAtmService.getLifecycleManager().scheduleTransaction(transaction);

? ? ? ? ? ? ...

??????? } else?{

? ? ? ? ? ? ...

??????????? ProtoLog.d(WM_DEBUG_STATES, "resumeTopActivityLocked: Restarting %s", next);

??????????? mTaskSupervisor.startSpecificActivity(next, true, true);

? ? ? ?}

??????? return true;

??? }

如果目标进程与当前进程是否有关系,如果有关系直接进行转化,如果没有关联,执行startSpecificActivity。

ActivityTaskSupervisor.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;

??????? if (wpc != null && wpc.hasThread()) {

??????????? try {

????????????????realStartActivityLocked(r, wpc, andResume, checkConfig);

? ? ? ? ? ? ? ? ...

? ? ? ? ? ?}

? ? ? ...

? ? ? mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");

??? }

判断目标进程是否创建,如果已经创建,执行realStartActivityLocked,最后启动目标activity的进程。

? boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,

??????????? boolean andResume, boolean checkConfig) throws RemoteException {

? ? ? ? ?...

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

??????????????????????? r.takeOptions(), isTransitionForward,

??????????????????????? proc.createProfilerInfoIfNeeded(), r.assistToken, activityClientController,

??????????????????????? r.createFixedRotationAdjustmentsIfNeeded(), r.shareableActivityToken,

??????????????????????? r.getLaunchedFromBubble()));

??????????????? // Set desired final state.

??????????????? final ActivityLifecycleItem lifecycleItem;

??????????????? if (andResume) {

??????????????????? lifecycleItem =?ResumeActivityItem.obtain(isTransitionForward);

??????????????? } else {

??????????????????? lifecycleItem = PauseActivityItem.obtain();

??????????????? }

??????????????? clientTransaction.setLifecycleStateRequest(lifecycleItem);

??????????????? // Schedule transaction.

????????????? ??mService.getLifecycleManager().scheduleTransaction(clientTransaction);

? ? ? ? ? ? ? ? ...

??????? return true;

??? }

调用LaunchActivityItem.java,启动应用程序。

启动进程:

ActivityTaskManagerService.java

? ??void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,

??????????? String hostingType) {

??????? try {

??????????? if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {

??????????????? Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"

??????????????????????? + activity.processName);

??????????? }

??????????? final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,

??????????????????? mAmInternal, activity.processName,?activity.info.applicationInfo, knownToBeDead,

??????????????????? isTop, hostingType, activity.intent.getComponent());

??????????? mH.sendMessage(m);

??????? } finally {

??????????? Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);

??????? }

??? }

通过进程间通信,调用到AMS的startProcessLocked。

ActivityManagerService.java

??? final ProcessRecord startProcessLocked(String processName,

??????????? ApplicationInfo info, boolean knownToBeDead, int intentFlags,

??????????? HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting,

??????????? boolean isolated) {

??????? return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,

??????????????? hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */,

??????????????? null /* ABI override */, null /* entryPoint */,

??????????????? null /* entryPointArgs */, null /* crashHandler */);

??? }

ProcessList.java

?@GuardedBy("mService")

??? ProcessRecord startProcessLocked(String processName, ApplicationInfo info,

??????????? boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord,

??????????? int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated, int isolatedUid,

??????????? String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {

? ? ? ? ...

??????? ProcessRecord predecessor = null;

??????? if (app != null && app.getPid() > 0) {

? ? ? ? ? ? ? ? ...

????????????????return?app;

??????????? }

? ? ? ? ...

??????? final boolean success =

????????????????startProcessLocked(app, hostingRecord, zygotePolicyFlags, abiOverride);

??????? checkSlow(startTime, "startProcess: done starting proc!");

??????? return success ? app : null;

??? }

??? boolean startProcessLocked(HostingRecord hostingRecord, String entryPoint, ProcessRecord app,

??????????? int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags, int mountExternal,

??????????? String seInfo, String requiredAbi, String instructionSet, String invokeWith,

??????????? long startTime) {

? ? ? ? ...

??????? if (mService.mConstants.FLAG_PROCESS_START_ASYNC) {

??????????? if (DEBUG_PROCESSES) Slog.i(TAG_PROCESSES,

??????????????????? "Posting procStart msg for " + app.toShortString());

??????????? mService.mProcStartHandler.post(() -> handleProcessStart(

??????????????????? app, entryPoint, gids, runtimeFlags, zygotePolicyFlags, mountExternal,

??????????????????? requiredAbi, instructionSet, invokeWith, startSeq));

??????????? return true;

??????? } else {

??????????? try {

??????????????? final Process.ProcessStartResult startResult =?startProcess(hostingRecord,

??????????????????????? entryPoint, app,

??????????????????????? uid, gids, runtimeFlags, zygotePolicyFlags, mountExternal, seInfo,

??????????????????????? requiredAbi, instructionSet, invokeWith, startTime);

??????????????? handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,

??????????????????????? startSeq, false);

??????????? } catch (RuntimeException e) {

??????????????? Slog.e(ActivityManagerService.TAG, "Failure starting process "

??????????????????????? + app.processName, e);

??????????????? app.setPendingStart(false);

??????????????? mService.forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid),

??????????????????????? false, false, true, false, false, app.userId, "start failure");

??????????? }

??????????? return app.getPid() > 0;

??????? }

??? }

??? private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,

??????????? ProcessRecord app, int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags,

?????? ?????int mountExternal, String seInfo, String requiredAbi, String instructionSet,

??????????? String invokeWith, long startTime) {

? ? ? ? ? ? ...

??????????? final Process.ProcessStartResult startResult;

??????? ????boolean regularZygote = false;

??????????? if (hostingRecord.usesWebviewZygote()) {

??????????????? startResult = startWebView(entryPoint,

??????????????????????? app.processName, uid, uid, gids, runtimeFlags, mountExternal,

????????????????????????app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,

????????????????????????app.info.dataDir, null,?app.info.packageName,

??????????????????????? app.getDisabledCompatChanges(),

??????????????????????? new String[]{PROC_START_SEQ_IDENT + app.getStartSeq()});

??????????? } else if (hostingRecord.usesAppZygote()) {

??????????????? final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);

??????????????? // zogyte启动进程

????? ??????????startResult = appZygote.getProcess().start(entryPoint,

??????????????????????? app.processName, uid, uid, gids, runtimeFlags, mountExternal,

????????????????????????app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,

???????????????? ???????app.info.dataDir, null,?app.info.packageName,

??????????????????????? /*zygotePolicyFlags=*/ ZYGOTE_POLICY_FLAG_EMPTY, isTopApp,

??????????????????????? app.getDisabledCompatChanges(), pkgDataInfoMap, allowlistedAppDataInfoMap,

???????????????????? ???false, false,

??????????????????????? new String[]{PROC_START_SEQ_IDENT + app.getStartSeq()});

??????????? } else {

??????????????? regularZygote = true;

??????????????? startResult = Process.start(entryPoint,

??????????????????????? app.processName, uid, uid, gids, runtimeFlags, mountExternal,

????????????????????????app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,

????????????????????????app.info.dataDir, invokeWith,?app.info.packageName, zygotePolicyFlags,

??????????????????????? isTopApp, app.getDisabledCompatChanges(), pkgDataInfoMap,

??????????????????????? allowlistedAppDataInfoMap, bindMountAppsData, bindMountAppStorageDirs,

??????????????????????? new String[]{PROC_START_SEQ_IDENT + app.getStartSeq()});

??????????? }

? ? ? ?...

??? }

通过Zogyte进程启动应用程序进程,之后会实例化ActivityThread,反射获取main函数。

ActivityThread.java

??? public static void main(String[] args) {

??????? Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

? ? ? ?...

??????? ActivityThread thread = new ActivityThread();

??????? thread.attach(false, startSeq);

? ? ? ...

??? }

??? private void attach(boolean system, long startSeq) {

??????? sCurrentActivityThread = this;

??????? mConfigurationController = new ConfigurationController(this);

??????? mSystemThread = system;

??????? if (!system) {

? ? ? ? ? //应用进程

??????????? android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",

??????????????????????????????????????????????????? UserHandle.myUserId());

??????????? RuntimeInit.setApplicationObject(mAppThread.asBinder());

??????????? final IActivityManager mgr = ActivityManager.getService();

??????????? try {

??????????????? mgr.attachApplication(mAppThread, startSeq);

? ? ? ? ? ?...

??????? } else {

? ? ? ? ??//系统进程

??????????? android.ddm.DdmHandleAppName.setAppName("system_process",

??????????????????? UserHandle.myUserId());

??????????? try {

??????????????? mInstrumentation = new Instrumentation();

??????????????? mInstrumentation.basicInit(this);

??????????????? ContextImpl context = ContextImpl.createAppContext(

??????????????????????? this, getSystemContext().mPackageInfo);

??????????????? mInitialApplication = context.mPackageInfo.makeApplication(true, null);

??????????????? mInitialApplication.onCreate();

? ? ? ? ? ?...

??????? }

? ? ? ? ...

??? }

判断是系统进程还是应用进程,如果是应用进程,调用AMS.attachApplication。

ActivityManagerService.java

??? @GuardedBy("this")

??? private boolean attachApplicationLocked(@NonNull IApplicationThread thread,

??????????? int pid, int callingUid, long startSeq) {

? ? ? ...

??????????????? thread.bindApplication(processName, appInfo, providerList,

??????????????????????? instr2.mClass,

??????????????????????? profilerInfo, instr2.mArguments,

??????????????????????? instr2.mWatcher,

??????????????????????? instr2.mUiAutomationConnection, testMode,

??????????????????????? mBinderTransactionTrackingEnabled, enableTrackAllocation,

??????????????????????? isRestrictedBackupMode || !normalMode, app.isPersistent(),

??????????????????????? new Configuration(app.getWindowProcessController().getConfiguration()),

??????????????????????? app.getCompat(), getCommonServicesLocked(app.isolated),

??????????????????????? mCoreSettingsObserver.getCoreSettingsLocked(),

??????????????????????? buildSerial, autofillOptions, contentCaptureOptions,

??????????????????????? app.getDisabledCompatChanges(), serializedSystemFontMap);

??????????? } else {

??????????????? thread.bindApplication(processName, appInfo, providerList, null, profilerInfo,

??????????????????????? null, null, null, testMode,

?????? ?????????????????mBinderTransactionTrackingEnabled, enableTrackAllocation,

??????????????????????? isRestrictedBackupMode || !normalMode, app.isPersistent(),

??????????????????????? new Configuration(app.getWindowProcessController().getConfiguration()),

? ??????????????????????app.getCompat(), getCommonServicesLocked(app.isolated),

??????????????????????? mCoreSettingsObserver.getCoreSettingsLocked(),

??????????????????????? buildSerial, autofillOptions, contentCaptureOptions,

??????????????????????? app.getDisabledCompatChanges(), serializedSystemFontMap);

??????????? }

...

??????? // See if the top visible activity is waiting to run in this process...

??????? if (normalMode) {

??????????? try {

??????????????? didSomething = mAtmInternal.attachApplication(app.getWi

??? boolean attachApplication(WindowProcessController app) throws RemoteException {

??????? boolean didSomething = false;

??????? for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {

??????????? mTmpRemoteException = null;

??????????? mTmpBoolean = false; // Set to true if an activity was started.

??????????? final DisplayContent display = getChildAt(displayNdx);

??????????? display.forAllRootTasks(rootTask -> {

??????????????? if (mTmpRemoteException != null) {

??????????????????? return;

??????????????? }

??????????????? if (rootTask.getVisibility(null /*starting*/) == TASK_VISIBILITY_INVISIBLE) {

?? ?????????????????return;

??????????????? }

??????????????? final PooledFunction c = PooledLambda.obtainFunction(

??????????????????????? RootWindowContainer::startActivityForAttachedApplicationIfNeeded, this,

??????????????????????? PooledLambda.__(ActivityRecord.class), app,

??????????????????????? rootTask.topRunningActivity());

??????????????? rootTask.forAllActivities(c);

??????????????? c.recycle();

??????????? });

??????????? if (mTmpRemoteException != null) {

??????????????? throw mTmpRemoteException;

??????????? }

??????????? didSomething |= mTmpBoolean;

??????? }

??????? if (!didSomething) {

??????????? ensureActivitiesVisible(null, 0, false /* preserve_windows */);

??????? }

??????? return didSomething;

??? }

ndowProcessController());

??????????? } catch (Exception e) {

??????????????? Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);

??????????????? badApp = true;

?????? ?????}

??????? }

? ?}

之后会通过进程间调用调用到ATMS的attachApplication,进一步调用到RootWindowContainer的attachApplication。

ActivityTaskManagerService.java

??? boolean attachApplication(WindowProcessController app) throws RemoteException {

??????? boolean didSomething = false;

? ? ? ? ...

??????????????? final PooledFunction c = PooledLambda.obtainFunction(

??????????????????????? RootWindowContainer::startActivityForAttachedApplicationIfNeeded, this,

??????????????????????? PooledLambda.__(ActivityRecord.class), app,

??????????????????????? rootTask.topRunningActivity());

??????????????? rootTask.forAllActivities(c);

? ? ? ? ? ? ...

??? }

??? private boolean startActivityForAttachedApplicationIfNeeded(ActivityRecord r,

??????????? WindowProcessController app, ActivityRecord top) {

??????? if (r.finishing || !r.okToShowLocked() || !r.visibleIgnoringKeyguard || r.app != null

??????????????? || app.mUid !=?r.info.applicationInfo.uid || !app.mName.equals(r.processName)) {

??????????? return false;

??????? }

??????? try {

??????????? if (mTaskSupervisor.realStartActivityLocked(r, app,

??????????????????? top == r && r.isFocusable() /*andResume*/, true /*checkConfig*/)) {

??????????????? mTmpBoolean = true;

??????????? }

??????? } catch (RemoteException e) {

??????????? Slog.w(TAG, "Exception in new application when starting activity "

??????????????????? + top.intent.getComponent().flattenToShortString(), e);

??????????? mTmpRemoteException = e;

??????????? return true;

??????? }

??????? return false;

??? }

再次调用到realStartActivityLocked,此时进程已启动,开始执行activity的状态转换。

整个流程为:

1.获取栈顶已激活的Activity,并进行暂停,暂停流程分为两步:

  1. 调用主线程的handlePauseActivity进行处理,之后再次通过Instrument调用到Activity的onPause函数。
  2. 暂停结束后,通过进程间通信,再次调用到Task的resumeTopActivityInnerLocked。

2.在resumeTopActivityInnerLocked中判断目标activity与当前进程是否有关联,若有关联,直接恢复目标activity,否则启动目标activity所在的进程。

3.判断目标进程是否已启动,如果目标进程启动,调用realStartActivityLocked进行状态转换,否则,通过Zogyte启动新进程。

4.新进程启动后,创建ActivityThread的实例,并进入main函数,通过进程间通信调用到ActivityManagerService的attachAppliaction函数,再进一步调用到attachAppliactionLocked进行进程间通信,通过ActivityThread的bindApplication绑定应用程序,之后再次通过进程间调用,通知ATMS调用到realStartActivityLocked进行状态转换。

流程图:

?

  游戏开发 最新文章
6、英飞凌-AURIX-TC3XX: PWM实验之使用 GT
泛型自动装箱
CubeMax添加Rtthread操作系统 组件STM32F10
python多线程编程:如何优雅地关闭线程
数据类型隐式转换导致的阻塞
WebAPi实现多文件上传,并附带参数
from origin ‘null‘ has been blocked by
UE4 蓝图调用C++函数(附带项目工程)
Unity学习笔记(一)结构体的简单理解与应用
【Memory As a Programming Concept in C a
上一篇文章      下一篇文章      查看所有文章
加:2022-04-22 19:10:32  更:2022-04-22 19:11:50 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2025年1日历 -2025/1/16 21:54:38-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码