1.前言
- 最近一直在看 《Android进阶解密》 的一本书,这本书编写逻辑、流程都非常好,而且很容易看懂,非常推荐大家去看看(没有收广告费,单纯觉得作者写的很好)。
- 上一篇简单的介绍了Android进阶(三):Application启动过程(最详细&最简单)。
- 今天就介绍Application启动之后,是如何启动应用程序中的
第一个Activity
(基于Android 8.0 系统)。
- 文章中实例 linhaojian的Github
2.Activity启动过程的时序图
3.源码分析
3.1 ActivityManagerService:
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {
//...
//通知ActivityThread启动application
thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
null, null, null, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, isAutofillCompatEnabled);// 1
// 启动第一个Activity
if (normalMode) {
try {
//Application初始化之后,初始化&启动第一个Activity
if (mStackSupervisor.attachApplicationLocked(app)) {// 2
didSomething = true;
}
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
}
- 注释1:通知ActivityThread启动application;
- 注释2:调用ActivityStackSupervisor,启动第一个Activity;
3.2 ActivityStackSupervisor 启动Activity:
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
//获取应用的进行名称
final String processName = app.processName;
boolean didSomething = false;
for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getChildAt(stackNdx);
if (!isFocusedStack(stack)) {
continue;
}
stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
final ActivityRecord top = stack.topRunningActivityLocked();
final int size = mTmpActivityList.size();
for (int i = 0; i < size; i++) {
final ActivityRecord activity = mTmpActivityList.get(i);
if (activity.app == null && app.uid == activity.info.applicationInfo.uid
&& processName.equals(activity.processName)) {
try {
// Application初始化之后,启动第一个Activity
if (realStartActivityLocked(activity, app,
top == activity /* andResume */, true /* checkConfig */)) { // 1
didSomething = true;
}
} catch (RemoteException e) {
Slog.w(TAG, "Exception in new application when starting activity "
+ top.intent.getComponent().flattenToShortString(), e);
throw e;
}
}
}
}
}
if (!didSomething) {
ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
}
return didSomething;
}
- 注释1:调用自身的realStartActivityLocked(),真正的启动Activity;
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
//...
// Create activity launch transaction.
//通知ActivityThread创建activity的实例 ;调用Activity的OnCreate; 创建对应PhoneWindow实例
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
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, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo)); // 2
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward()); // 3
} else {
lifecycleItem = PauseActivityItem.obtain(); // 4
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// 编制启动Activity实例的事务,并按顺序调用onCreate();onStart();onResume();
mService.getLifecycleManager().scheduleTransaction(clientTransaction);// 5
}
- 注释2:封装启动Activity的相关数据与Activity的启动流程(LaunchActivityItem 下面会介绍该类);
- 注释3:封装Activity启动之后生命周期变化为Resume的流程(ResumeActivityItem下面会介绍该类);
- 注释4:封装Activity启动之后生命周期变化为Pause的流程;
- 注释5:真正开始启动Activity与调用相关的生命周期方法;
3.3 ClientLifecycleManager管理ClientTransaction:
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();// 1
transaction.schedule();// 2
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();
}
}
- 注释1:获取需要启动Activity进程的代理对象IApplicationThread;
- 注释2:调用ClientTransaction中的schedule();
3.4 ClientTransaction中schedule函数:
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);// 1
}
- 注释1:mClient就是与ActivityThread通讯的代理对象(IApplicationThread),所以这里其实是调用ActivityThread类中ApplicationThread内部类的scheduleTransaction();
3.5 ApplicationThread的scheduleTransaction函数:
private class ApplicationThread extends IApplicationThread.Stub {
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);// 1
}
}
- 注释1:这里其实最后还是调用了ActivityThread的scheduleTransaction(),而这个scheduleTransaction()其实真正的实现是ClientTransactionHandler,因为ActivityThread是继承ClientTransactionHandler类的;
public abstract class ClientTransactionHandler {
/** Prepare and schedule transaction for execution. */
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);// 2
}
}
- 注释2:调用ActivityThread的sendMessage(),将ClientTransaction参数通过Handler机制切换至主线程进行处理;
3.6 ActivityThread的H类:
class H extends Handler {
//...
public void handleMessage(Message msg) {
switch (msg.what) {
case EXECUTE_TRANSACTION: // 1
final ClientTransaction transaction = (ClientTransaction) msg.obj;// 2
mTransactionExecutor.execute(transaction);// 3
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;
}
}
}
- 注释1:接收ClientTransactionHandler发送的EXECUTE_TRANSACTION事件;
- 注释2:接收ClientTransactionHandler发送的ClientTransaction参数;
- 注释3:通过TransactionExecutor真正处理ClientTransaction中封装的Activity相关信息;
3.7 TransactionExecutor处理ClientTransaction:
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
executeCallbacks(transaction);
executeLifecycleState(transaction);
mPendingActions.clear();
log("End resolving transaction");
}
3.8 executeCallbacks()启动Activity:
@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
final List callbacks = transaction.getCallbacks();
if (callbacks == null) {
// No callbacks to execute, return early.
return;
}
log("Resolving callbacks");
final IBinder token = transaction.getActivityToken();
ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
// In case when post-execution state of the last callback matches the final state requested
// for the activity in this transaction, we won't do the last transition here and do it when
// moving to final state instead (because it may contain additional parameters from server).
final ActivityLifecycleItem finalStateRequest = transaction.getLifecycleStateRequest();
final int finalState = finalStateRequest != null ? finalStateRequest.getTargetState()
: UNDEFINED;
// Index of the last callback that requests some post-execution state.
final int lastCallbackRequestingState = lastCallbackRequestingState(transaction);
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);// 1
log("Resolving callback: " + item);
final int postExecutionState = item.getPostExecutionState();
final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
item.getPostExecutionState());
if (closestPreExecutionState != UNDEFINED) {
cycleToPath(r, closestPreExecutionState);
}
item.execute(mTransactionHandler, token, mPendingActions);// 2
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);
}
}
}
- 注释1:获取ClientTransaction中的ClientTransactionItem对象(其实这里的对象就上面3.2介绍中的LaunchActivityItem);
- 注释2:调用LaunchActivityItem类的execute(),下面我们看看LaunchActivityItem;
public class LaunchActivityItem extends ClientTransactionItem {
@Override
public void execute(ClientTransactionHandler client, IBinder token,// 1
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);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);// 2
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
}
- 注释1:刚刚说了ClientTransactionHandler是被ActivityThread继承,所以这里传入进来就是ActivityThread;
- 注释2:看到了吧,经过多次不同层次相互调用,最终真正调用ActivityThread的handleLaunchActivity(),启动应用的第一个Activity;
3.8 executeLifecycleState()改变Activity的生命周期:
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();// 1
if (lifecycleItem == null) {
// No lifecycle request, return early.
return;
}
log("Resolving lifecycle state: " + lifecycleItem);
final IBinder token = transaction.getActivityToken();
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
if (r == null) {
// Ignore requests for non-existent client records for now.
return;
}
// Cycle to the state right before the final requested state.
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
// Execute the final transition with proper parameters.
lifecycleItem.execute(mTransactionHandler, token, mPendingActions); // 2
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
- 注释1:获取ClientTransaction中的ActivityLifecycleItem 对象(其实这里的对象就上面3.2介绍中的ResumeActivityItem);
- 注释2:调用ResumeActivityItem的execute(),下面我们看看ResumeActivityItem;
public class ResumeActivityItem extends ActivityLifecycleItem {
//...
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward, // 1
"RESUME_ACTIVITY");
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
}
- 注释1:其实就是调用Activity的handleResumeActivity(),最终就会调用Activity的onStart()与onResume();
4.类关系
- 通过上图发现,Activity启动过程就是AMS与ActivityThread不同的进程交互实现的。
5.总结
- 到此,
Activity启动过程
介绍完毕。
- 如果喜欢我的分享,可以点击 关注 或者 赞,你们支持是我分享的最大动力 。
- linhaojian的Github
欢迎关注linhaojian_CSDN博客或者linhaojian_!
不定期分享关于安卓开发的干货。
写技术文章初心
- 技术知识积累
- 技术知识巩固
- 技术知识分享
- 技术知识交流