这篇文章将大致得介绍下应用得一个启动流程,旨在大致理解,具体细节后续文章在做介绍
应用启动过程中得核心要点
- 四个进程,launcher、app、zygote、system-server(ams)
- 进程间通信,binder
- 线程间通信,Handler
掌握以上四点,看启动流程基本就比较舒畅了
应用启动简介
基于sdk32分析,也就是android 12,大致流程如下:
部分参考:(12条消息) 【framework】应用进程启动流程_handleprocessstartedlocked_little_fat_sheep的博客-CSDN博客
要点记录
ActivityThread main方法
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// Install selective syscall interception
AndroidOs.install();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
// Call per-process mainline module initialization.
initializeMainlineModules();
Process.setArgV0("<pre-initialized>");
//Looper 准备,非常重要
Looper.prepareMainLooper();
// Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
// It will be in the format "seq=114"
long startSeq = 0;
if (args != null) {
for (int i = args.length - 1; i >= 0; --i) {
if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
startSeq = Long.parseLong(
args[i].substring(PROC_START_SEQ_IDENT.length()));
}
}
}
//实例一个ActivityThread,并进行attach
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
//进行looper循环取消息处理
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
如何调用Handle***Activity
调用AMS的attachApplication,进行bindApplication之后会进行activity的启动,
ActivityManagerService.java -- attachApplicationLocked
//进行application初始化,告诉应用进程应用信息,创建application和上下文等,
//调用application的oncreate
thread.bindApplication(processName, appInfo, providerList, null, profilerInfo,
//进行activity的处理,该方法之后会有service、broadcast、backup agent等初始化
// See if the top visible activity is waiting to run in this process...
if (normalMode) {
try {
didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
ActivityTaskManagerService.java
//进行application初始化,告诉应用进程应用信息,创建application和上下文等,
@HotPath(caller = HotPath.PROCESS_CHANGE)
@Override
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);
}
}
}
RootWindowContainer.java
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_FRAGMENT_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;
}
//这个地方注意,如果创建成功 mTmpBoolean为true,那么就不会更新visible
if (!didSomething) {
ensureActivitiesVisible(null, 0, false /* preserve_windows */);
}
return didSomething;
}
private boolean startActivityForAttachedApplicationIfNeeded(ActivityRecord r,
WindowProcessController app, ActivityRecord top) {
if (r.finishing || !r.showToCurrentUser() || !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;
}
ActivityTaskSupervisor.java
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
....................省略代码.......................
//这里就是进行HandleLaunchActivity,主要依靠这个LaunchActivityItem的callback
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.getFilteredReferrer(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;
//这里进行了lifecycle状态设置,后面解析的时候会进行更新
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(isTransitionForward);
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction. 执行事务,下个代码块看下具体流程
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
....................省略代码.......................
mService.getLifecycleManager()最终获取的是ClientLifecycleManager
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
//可以明显看到,这个是目标app的binder代理,这个时候看下transaction的处理
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();
}
}
**ClientTransaction.java**
/** Get the target client of the transaction. */
public IApplicationThread getClient() {
return mClient;
}
//可以看到,跨进程调用的是目标app的scheduleTransaction,
//也就是activityThread的方法
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
AvtivityTHread.java
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
//调用父类ClientTransactionHandler的scheduleTransaction
ActivityThread.this.scheduleTransaction(transaction);
}
//ClientTransactionHandler中, 可以看到内部还是handler处理
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
//handler 处理EXECUTE_TRANSACTION
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处理
public void execute(ClientTransaction transaction) {
..................省略代码.......................
if (DEBUG_RESOLVER) Slog.d(TAG, transactionToString(transaction, mTransactionHandler));
//解析transaction,也就是之前add的callback---LaunchActivityItem,进行handlelaunchActivity
executeCallbacks(transaction);
//解析lifecycleState,循环处理,正常就是走到resume,
//中间会处理StartActivityItem最终是ResumeActivityItem,
//每个Item都对应着Handle***Activity,最终调用我们写的on***生命周期函数,
//至此流程打通
executeLifecycleState(transaction);
mPendingActions.clear();
if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
}
以上流程解决了应用启动如何创建进程以及进入到onresume的过程