[framework] Activity startup process

1 Introduction

ATMS startup process introduces the startup and initialization process of ActivityTaskManagerService (ATMS). This article will introduce the startup process of Activity. Due to the complexity of the Activity startup process, this article divides it into three parts according to the process:

  • Launcher process : introduces the calling process from Launcher (startActivitySafely method) to ATMS (startActivity method);
  • system_server process : introduces the calling process from ATMS (startActivity method) to ApplicationThread (scheduleTransaction method);
  • Application Process : Introduce the calling process from ApplicationThread (scheduleTransaction method) to Activity (onCreate method).

To distinguish different processes, the Launcher process, system_server process, and application process are identified as light blue, dark blue, and purple, respectively.

2 Source code analysis

2.1 Launcher to ATMS

Launcher generally refers to the desktop program. The Launcher class inherits the Activity class. When the user clicks the shortcut icon on the desktop, the launcher's startActivitySafely() method will be called.

As shown in the figure, the light blue class is executed in the Launcher process, the dark blue class is executed in the system_server process, and the yellow class refers to the interface generated by the AIDL file (for cross-process).

img

(1)startActivitySafely

/packages/apps/Launcher3/src/com/android/launcher3/Launcher.java

public boolean startActivitySafely(View v, Intent intent, ItemInfo item, String sourceContainer) {
	...
    //调用父类 BaseDraggingActivity 的 startActivitySafely 方法
	boolean success = super.startActivitySafely(v, intent, item, sourceContainer);
	...
}

(2)startActivitySafely

/packages/apps/Launcher3/src/com/android/launcher3/BaseDraggingActivity.java

public boolean startActivitySafely(View v, Intent intent, ItemInfo item, String sourceContainer) {
	...
	//getActivityLaunchOptions(v).toBundle(),ActivityOptions 存储了 v 的参数,用于启动动画
	Bundle optsBundle = (v != null) ? getActivityLaunchOptionsAsBundle(v) : null; 
	...
	//设置 FLAG_ACTIVITY_NEW_TASK,保证 Activity 在新任务栈中运行(后面还会出现)
	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    ...
	try {
		...
		if (isShortcut) {
			startShortcutIntentSafely(intent, optsBundle, item, sourceContainer);
		} else if (user == null || user.equals(Process.myUserHandle())) {
			...
            //调用父类 Activity 的 startActivity 方法
			startActivity(intent, optsBundle);
			...
		}
		...
	}
	...
}

(3)startActivity

/frameworks/base/core/java/android/app/Activity.java

public void startActivity(Intent intent, Bundle options) {
	if (options != null) {
		//第二个参数为-1表示 launcher 不需要知道返回结果
		startActivityForResult(intent, -1, options);
	} else {
		startActivityForResult(intent, -1);
	}
}

public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
	//mParent 为 Activity 类型,表示当前 Activity 的父类
	if (mParent == null) {
		//options == null ? ActivityOptions.fromBundle(ActivityTaskManager.getService().getActivityOptions(mToken)) : options
		options = transferSpringboardActivityOptions(options);
        // Instrumentation 类用于监控系统和应用程序之间的交互
		Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
				this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options);
		...
	}
	...
}

Launcher is a subclass of Activity. During the startup process of Launcher, the Instrumentation object has been created, specifically created in the handleBindApplication() method of ActivityThread, and injected into the Activity through the attach() method of Activity.

Instrumentation has the function of tracking the application and activity life cycle, and is used to monitor the interaction between the app and the system. A single instance exists in the application process, that is, there is one and only one Instrumentation object in each application process (Launcher also belongs to an application process).

(4)execStartActivity

/frameworks/base/core/java/android/app/Instrumentation.java

public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, 
		    Activity target, Intent intent, int requestCode, Bundle options) {
	IApplicationThread whoThread = (IApplicationThread) contextThread;
	...
	try {
		...
		int result = ActivityTaskManager.getService().startActivity(
						whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), 
						token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
		...
	}
	...
}

/frameworks/base/core/java/android/app/ActivityTaskManager.java

public static IActivityTaskManager getService() {
	return IActivityTaskManagerSingleton.get();
}

private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton = new Singleton<IActivityTaskManager>() {
	@Override
	protected IActivityTaskManager create() {
		final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE); //"activity_task"
		return IActivityTaskManager.Stub.asInterface(b);
	}
};

ATMS startup and initialization process → ATMS startup process , ServiceManager calls the ServiceManager of the native layer to obtain the ATMS service registered when the Android system starts.

ATMS is used to manage Activity and its containers (tasks, stacks, displays, etc.). It only appeared in Android 10. It was separated from the original AMS (ActivityManagerService) and assumed some of the responsibilities of AMS.

2.2 ATMS to ApplicationThread

As shown in the figure, the dark blue class is executed in the system_server process, the purple class is executed in the application process to be started, and the yellow class refers to the interface generated by the AIDL file (for cross-process).

img

(1)startActivity

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

public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, 
			IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
	return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, resultWho, 
			requestCode, startFlags, profilerInfo, bOptions, UserHandle.getCallingUserId());
}

//较上面方法,多传了调用者的 UserId
public int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, 
			IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
	return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, 
			resultWho, requestCode, startFlags, profilerInfo, bOptions, userId, true);
}

int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, 
			String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, 
			ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
	//判断调用者进程是否被隔离
	enforceNotIsolatedCaller("startActivityAsUser");
	//检查调用者权限
	userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser, Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
	return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
			.setCaller(caller) //mRequest.caller = caller
			.setCallingPackage(callingPackage) //mRequest.callingPackage = callingPackage
			.setResolvedType(resolvedType) //mRequest.resolvedType = resolvedType
			.setResultTo(resultTo) //mRequest.resultTo = resultTo
			.setResultWho(resultWho) //mRequest.resultWho = resultWho
			.setRequestCode(requestCode) //mRequest.requestCode = requestCode
			.setStartFlags(startFlags) //mRequest.startFlags = startFlags
			.setProfilerInfo(profilerInfo) //mRequest.profilerInfo = profilerInfo
			.setActivityOptions(bOptions) //mRequest.activityOptions = SafeActivityOptions.fromBundle(bOptions)
			.setMayWait(userId) //mRequest.mayWait = true、mRequest.userId = userId
			.execute();
}

Description: The obtainStarter() method obtains an ActivityStarter object, which is converted into ActivityRecord, TaskRecord, and ActivityStack according to Intent and flag; setter methods such as setCaller() will inject values ​​into the mRequest object (Request type) of ActivityStarter, which is in It is initialized when it is defined.

(2)obtainStarter

/frameworks/base/services/core/java/com/android/server/wm/ActivityStartController.java

ActivityStarter obtainStarter(Intent intent, String reason) {
    //mFactory 为 DefaultFactory 类型,是 ActivityStarter 的静态内部类
	return mFactory.obtain().setIntent(intent).setReason(reason);
}

DefaultFactory is a static internal class of ActivityStarter, and its creation process is as follows: (Details → ATMS startup process )

img

  • Call the initialize() method of ATMS in the construction method of AMS;
  • In the initialize() method of ATMS, call the constructor of ActivityStartController to create the ActivityStartController object;
  • Call the constructor of DefaultFactory in the constructor of ActivityStartController to create a DefaultFactory object.

(3)obtain

/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.DefaultFactory.java

static class DefaultFactory implements Factory {
	...
	//MAX_STARTER_COUNT = 3
	private SynchronizedPool<ActivityStarter> mStarterPool = new SynchronizedPool<>(MAX_STARTER_COUNT);
	...
	public ActivityStarter obtain() {
		ActivityStarter starter = mStarterPool.acquire();
		if (starter == null) {
			//参数:ActivityStartController、ActivityTaskManagerService、ActivityStackSupervisor、ActivityStartInterceptor
			starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
		}
		return starter;
	}
}

(4)execute

/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java

int execute() {
	try {
		if (mRequest.mayWait) {
			return startActivityMayWait(mRequest.caller, mRequest.callingUid,
					mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
					mRequest.intent, mRequest.resolvedType,
					mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
					mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
					mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
					mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
					mRequest.inTask, mRequest.reason,
					mRequest.allowPendingRemoteAnimationRegistryLookup,
					mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
		}
		...
	} 
	...
}

In setMayWait(userId), mRequest.mayWait has been set to true, so it will enter the startActivityMayWait() method.

(5)startActivityMayWait

/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java

private int startActivityMayWait(IApplicationThread caller, int callingUid, String callingPackage, 
		int requestRealCallingPid, int requestRealCallingUid, Intent intent, String resolvedType, 
		IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, 
		String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, WaitResult outResult,
		Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
		int userId, TaskRecord inTask, String reason, boolean allowPendingRemoteAnimationRegistryLookup,
		PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
	...
    //解析 Intent
	ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId, 0,
					computeResolveFilterUid(callingUid, realCallingUid, mRequest.filterCallingUid));
	...
    //收集目标 Intent 的信息
	ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
	synchronized (mService.mGlobalLock) {
		...
        //创建 ActivityRecord 数组
		final ActivityRecord[] outRecord = new ActivityRecord[1];
		int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
				voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
				callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
				ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
				allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
				allowBackgroundActivityStart);
		...
	}
}

(6)startActivity

/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent, String resolvedType, 
		ActivityInfo aInfo, ResolveInfo rInfo, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
		IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage, 
		int realCallingPid, int realCallingUid, int startFlags, SafeActivityOptions options, boolean ignoreTargetSecurity, 
		boolean componentSpecified, ActivityRecord[] outActivity, TaskRecord inTask, String reason, boolean allowPendingRemoteAnimationRegistryLookup,
		PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
	...
	mLastStartActivityRecord[0] = null;
	mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
			aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
			callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
			options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
			inTask, allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
			allowBackgroundActivityStart);
	...
}

(7)startActivity

/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent, String resolvedType, 
		ActivityInfo aInfo, ResolveInfo rInfo, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
		IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage, 
		int realCallingPid, int realCallingUid, int startFlags, SafeActivityOptions options, boolean ignoreTargetSecurity, 
		boolean componentSpecified, ActivityRecord[] outActivity, TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup,
		PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
	...
	WindowProcessController callerApp = null;
	if (caller != null) {
        //从 ATMS 中获取 WindowProcessController
		callerApp = mService.getProcessController(caller);
		...
	}
	...
	//一个 ActivityRecord 对应一个 Activity,描述了 Activity 的信息
	ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
			callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
			resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
			mSupervisor, checkedOptions, sourceRecord);
	if (outActivity != null) {
		outActivity[0] = r;
	}
	...
	final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true, 
						checkedOptions, inTask, outActivity, restrictedBgActivity);
	...
}

(8)startActivity

/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
			IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
			int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
			ActivityRecord[] outActivity, boolean restrictedBgActivity) {
	...
	try {
		mService.mWindowManager.deferSurfaceLayout();
		result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
				startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
	}
	...
}

(9)startActivityUnchecked

/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
		IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
		int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
		ActivityRecord[] outActivity, boolean restrictedBgActivity) {
	//初始化 ActivityStarter 的属性
	setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession, voiceInteractor, restrictedBgActivity);
	...
	//计算 mLaunchFlags
	computeLaunchingTaskFlags();
	//计算 mSourceStack
	computeSourceStack();
	...
	final TaskRecord taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null) ? mSourceRecord.getTaskRecord() : null;
	...
	if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
		newTask = true;
		//创建新的 TaskStack,即 mTargetStack:computeStackFocus() -> getLaunchStack()
		result = setTaskFromReuseOrCreateNewTask(taskToAffiliate);
	}
	...
	//处理 Task 和 Activity 的进栈操作
	mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition, mOptions);
	if (mDoResume) {
		final ActivityRecord topTaskActivity = mStartActivity.getTaskRecord().topRunningActivityLocked();
		if (!mTargetStack.isFocusable() || (topTaskActivity != null && topTaskActivity.mTaskOverlay && mStartActivity != topTaskActivity)) {
			...
		} else {
            ...
			//启动焦点栈的栈顶 Activity
			mRootActivityContainer.resumeFocusedStacksTopActivities(mTargetStack, mStartActivity, mOptions);
		}
	}
	...
}

RootActivityContainer only appeared in Android 10, separated from the original ActivityStackSupervisor, the purpose is to maintain a peer-to-peer hierarchy with RootWindowContainer.

RootActivityContainer is created in the initialize() method of ATMS, and injected into ActivityStarter through ATMS.mRootActivityContainer in the construction method of ActivityStarter.

The creation process of ActivityStack is as follows:

img

(10)resumeFocusedStacksTopActivities

/frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer .java

boolean resumeFocusedStacksTopActivities(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
	...
	if (targetStack != null && (targetStack.isTopStackOnDisplay() || getTopDisplayFocusedStack() == targetStack)) {
		result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
	}
	...
}

(11)resumeTopActivityUncheckedLocked

/frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
	...
	try {
		...
		result = resumeTopActivityInnerLocked(prev, options);
		...
	}
	...
}

(12)resumeTopActivityInnerLocked

/frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
	...
	ActivityRecord next = topRunningActivityLocked(true);
	...
	mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);
	...
	if (next.attachedToProcess()) {
		...
	} else {
		...
        //mStackSupervisor 为 ActivityStackSupervisor,在 ATMS 的 initialize() 方法中创建
		mStackSupervisor.startSpecificActivityLocked(next, true, true);
	}
	...
}

ActivityStackSupervisor is created in the initialize() method of ATMS and injected into ActivityStack in the construction method of ActivityStack.

(13)startSpecificActivityLocked

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

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
	final WindowProcessController wpc = mService.getProcessController(r.processName, r.info.applicationInfo.uid);
	...
    //判断应用进程是否已创建,即 IApplicationThread 是否为空
	if (wpc != null && wpc.hasThread()) {
		try {
            //启动 Activity
			realStartActivityLocked(r, wpc, andResume, checkConfig);
			return;
		}
	}
	try {
		...
		//应用进程不存在,通知创建应用进程
		final Message msg = PooledLambda.obtainMessage(
				ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
				r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
		mService.mH.sendMessage(msg);
	}
	...
}

(14)realStartActivityLocked

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

boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) throws RemoteException {
	...
	try {
		...
		r.setProcess(proc);
		...
		proc.addActivityIfNeeded(r);
		...
		try {
			...
			//创建启动 Activity 的事务
            //instance = new ClientTransaction(); instance.mClient = client; instance.mActivityToken = activityToken
			final ClientTransaction clientTransaction = ClientTransaction.obtain(proc.getThread(), r.appToken);
			...
			final DisplayContent dc = r.getDisplay().mDisplayContent;
			//添加回调,这里添加的 LaunchActivityItem 会在 TransactionExecutor 中获取并执行
			clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
					System.identityHashCode(r), r.info,
					mergedConfiguration.getGlobalConfiguration(),
					mergedConfiguration.getOverrideConfiguration(), r.compat,
					r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
					r.icicle, r.persistentState, results, newIntents,
					dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(), r.assistToken));
			final ActivityLifecycleItem lifecycleItem;
			if (andResume) {
				lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
			}
			...
			clientTransaction.setLifecycleStateRequest(lifecycleItem);
			//启动事务,mService 为 ATMS,ClientLifecycleManager 对象在 ATMS 的构造方法中创建
			mService.getLifecycleManager().scheduleTransaction(clientTransaction);
			...
		}
		...
	}
	...
}

ClientLifecycleManager is created in the constructor of ATMS.

LaunchActivityItem encapsulates the startup information of the Activity, and its parent class (ClientTransactionItem) implements the Parcelable interface, which is a data packet for Binder cross-process communication. The LaunchActivityItem object is added to the ClientTransaction and transmitted to the application process along with the ClientTransaction.

(15)scheduleTransaction

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

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
	...
	transaction.schedule();
	...
}

(16)schedule

/frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java

public void schedule() throws RemoteException {
    //mClient 为 IApplicationThread 类型
	mClient.scheduleTransaction(this); 
}

ClientTransaction implements the Parcelable interface, which is the data packet of Binder cross-process communication, and transfers the data encapsulated by itself to the application process by calling mClient.scheduleTransaction(this).

2.3 ApplicationThread 到 Activity

As shown in the figure, the dark blue class is executed in the system_server process, the purple class is executed in the application process to be started, the yellow class refers to the interface generated by the AIDL file (for cross-process), and the green class implements Parcelable Interface (packets transmitted by Binder cross-process communication).

img

(1)scheduleTransaction

/frameworks/base/core/java/android/app/ActivityThread**.****ApplicationThread**.java

public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    //ActivityThread 继承了 ClientTransactionHandler,这里调用的是父类的 scheduleTransaction() 方法
	ActivityThread.this.scheduleTransaction(transaction);
}

Description: ApplicationThread is the inner class of ActivityThread and inherits the IApplicationThread.Stub class.

(2)scheduleTransaction

/frameworks/base/core/java/android/app/ClientTransactionHandler.java

void scheduleTransaction(ClientTransaction transaction) {
	transaction.preExecute(this);
	sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

(3)sendMessage

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

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

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
	...
	Message msg = Message.obtain();
	msg.what = what;
	msg.obj = obj;
	msg.arg1 = arg1;
	msg.arg2 = arg2;
	if (async) {
		msg.setAsynchronous(true);
	}
    //mH 是 H 类的对象,在定义时就被创建:mH = new H()
	mH.sendMessage(msg);
}

The H class inherits the Handler class and is an internal class of ActivityThread, which is mainly used for communication between the Binder thread and the main thread (UI thread).

(4)handleMessage

/frameworks/base/core/java/android/app/ActivityThread**.****H**.java

class H extends Handler {
	...
	public static final int EXECUTE_TRANSACTION = 159;
	...
	public void handleMessage(Message msg) {
		...
		switch (msg.what) {
			...
			case EXECUTE_TRANSACTION:
				final ClientTransaction transaction = (ClientTransaction) msg.obj;
                //mTransactionExecutor 在定义时就被初始化,即:mTransactionExecutor = new TransactionExecutor(this);
				mTransactionExecutor.execute(transaction);
				...
				break;
			...
		}
		...
	}
}

The previous communication with the ATMS process runs in the Binder thread, that is, ApplicationThread, so here you need to use H to switch the code logic to the main thread (UI thread). TransactionExecutor is initialized when it is defined in ApplicationThread.

(5)scheduleTransaction

/frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java

public void execute(ClientTransaction transaction) {
	...
	executeCallbacks(transaction);
	executeLifecycleState(transaction);
	...
}

(6)executeCallbacks

/frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java

public void executeCallbacks(ClientTransaction transaction) {
	final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
	...
	final IBinder token = transaction.getActivityToken();
	ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
	...
	final int size = callbacks.size();
	for (int i = 0; i < size; ++i) {
        //item 是 ClientTransactionItem 的子类(LaunchActivityItem)的对象
		final ClientTransactionItem item = callbacks.get(i);
		...
		item.execute(mTransactionHandler, token, mPendingActions);
		item.postExecute(mTransactionHandler, token, mPendingActions);
		...
	}
}

(7)execute

/frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java

public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) {
	...
    //创建 ActivityClientRecord,它是 ActivityThread 的内部类
	ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
			mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
			mPendingResults, mPendingNewIntents, mIsForward,
			mProfilerInfo, client, mAssistToken);
    //client 是 ClientTransactionHandler 的子类(ActivityThread)的对象
	client.handleLaunchActivity(r, pendingActions, null);
	...
}

(8)handleLaunchActivity

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

public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) {
	...
	//获取 WMS
	WindowManagerGlobal.initialize();
	...
	final Activity a = performLaunchActivity(r, customIntent);
	...
	return a;
}

(9)performLaunchActivity

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

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
	ActivityInfo aInfo = r.activityInfo;
	...
	//ComponentName 中包含 Activity 的类名和包名
	ComponentName component = r.intent.getComponent();
	...
	//创建 Context:ContextImpl.createActivityContext(this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig)
	ContextImpl appContext = createBaseContextForActivity(r);
	Activity activity = null;
	try {
		java.lang.ClassLoader cl = appContext.getClassLoader();
		//创建 Activity,通过反射实现:cl.loadClass(className).newInstance()
		activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
		...
	}
	...
	try {
		//创建 Application
		Application app = r.packageInfo.makeApplication(false, mInstrumentation);
		...
		if (activity != null) {
			...
			Window window = null; //实现类为 PhoneWindow
			...
			appContext.setOuterContext(activity);
			//将属性(Instrumentation等)注入 Activity,并创建 PhoneWindow、WindowManagerImpl 对象                                                  
			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);
			...
			if (r.isPersistable()) {
				//回调 Activity 的 onCreate() 方法
				mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
			}
			...
			r.activity = activity;
		}
		//切换 Activity 状态
		r.setState(ON_CREATE);
		...
		synchronized (mResourcesManager) {
			mActivities.put(r.token, r);
		}
	}
	...
	return activity;
}

When creating and starting the application process, the Instrumentation object has been created in the handleBindApplication() method of ActivityThread and injected into the Activity through the attach() method of Activity.

Instrumentation has the function of tracking the application and activity life cycle, and is used to monitor the interaction between the app and the system. A single instance exists in the application process, that is, there is only one Instrumentation object in each application process.

(10)callActivityOnCreate

/frameworks/base/core/java/android/app/Instrumentation.java

public void callActivityOnCreate(Activity activity, Bundle icicle, PersistableBundle persistentState) {
	//onCreate() 方法回调前处理
	prePerformCreate(activity);
	//调用 onCreate() 方法
	activity.performCreate(icicle, persistentState);
	//onCreate() 方法回调后处理
	postPerformCreate(activity);
}

(11)performCreate

/frameworks/base/core/java/android/app/Activity.java

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
	dispatchActivityPreCreated(icicle);
	...
	if (persistentState != null) {
		//调用用户自定义 Activity 的 oncreate() 方法
		onCreate(icicle, persistentState);
	} else {
		onCreate(icicle);
	}
	...
	dispatchActivityPostCreated(icicle);
}

In order to help you understand the function and structure of the Framework in the entire Android architecture, systematically learn and master the Android framework, here we specially collaborated with Ali P7 architects and Google technical teams to organize a learning material for the Android framework family bucket.

Summary: "Android Framework Development Secret"; Summary of Android Framework high-frequency interview questions; Android Framework refined kernel analysis; Android 11.0 latest Framework analysis.

Content features: clear organization, including graphic representation, which is easier to understand.

Due to the large content of the article and the limited space, the information has been organized into PDF documents. If you need the complete document of "Android Framework Advanced Study Guide", you can scan the card below to get it for free~

"Android Framework Development Secret"

Table of contents

imgimg

Chapter 1 System Startup Process Analysis

​ ● The first section Android startup overview

​ ● Section 2 init.rc analysis

​ ● Section 3 Zygote

​ ● Interview questions

img

Chapter 2 Binder Analysis

​ ● The first section macro understanding of Binder

​ ● In the second section, the jni method registration of binder

​ ● The third section binder driver

​ ● Section 4 Data Structure

​ ● The fifth section starts service_manager

​ ● Section 6 Get service_manager

​ ● Section 7 addService process

​ ● Full analysis of Binder interview questions in the eighth section

img

Chapter 3 Handler Analysis

​ ● Section 1 source code analysis

​ ● Difficult questions in the second quarter

​ ● Section 3 Handler common interview questions

img

Guess you like

Origin blog.csdn.net/Gaga246/article/details/130578873