Activity启动流程 上篇(Android 10),我们从startActivity
分析到了App进程的入口点ActivityThread
的main
函数。本篇,我们将从这里开始,一步步分析,直到Activity
的onCreate
方法。
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);
Process.setArgV0("<pre-initialized>");
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 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.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
如果大家稍微看过一些源码,我相信对这段代码还是非常熟悉的,Handler相关内容我们不讲,直接看thread.attach(false, startSeq)
函数:
@UnsupportedAppUsage
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = 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);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
....
} else {
....
}
....
}
ActivityManager.getService()
就是ActivityManagerService
,所以我们跨进程到了AMS中,并调用了attachApplication
,还把mAppThread
一个ApplicationThread
句柄带了过去,这个很重要,大部分AMS调用App进行工作都是调用这个Ibinder句柄实现的,后面启动Activity
就是使用这个句柄的,ApplicationThread
是ActivityThread
的一个子类。所以我们直接来看AMS的attachApplication
方法:
@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
if (thread == null) {
throw new SecurityException("Invalid application interface");
}
synchronized (this) {
int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
Binder.restoreCallingIdentity(origId);
}
}
这里调用了attachApplicationLocked
:
....
//这里的thread,就是我们调用attachApplication传入的参数,即:ApplicationThread
thread.bindApplication(....)
....
//先讲上面,一会儿回来将这个。
if (normalMode) {
try {
didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
这里首先调用了bindApplication
又回到了App进程中:
public final void bindApplication(String processName, ApplicationInfo appInfo,
....
sendMessage(H.BIND_APPLICATION, data);
}
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
....
然后是handleBindApplication
private void handleBindApplication(AppBindData data) {
....
try {
// 创建Application
app = data.info.makeApplication(data.restrictedBackupMode, null);
try {
// 调用Application的onCreate方法
mInstrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
if (!mInstrumentation.onException(app, e)) {
throw new RuntimeException(
"Unable to create application " + app.getClass().getName()
+ ": " + e.toString(), e);
}
}
}
首先来看makeApplication
:
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
....
try {
java.lang.ClassLoader cl = getClassLoader();
if (!mPackageName.equals("android")) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
"initializeJavaContextClassLoader");
initializeJavaContextClassLoader();
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
//创建ContextImpl
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
//创建Application
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {
if (!mActivityThread.mInstrumentation.onException(app, e)) {
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
throw new RuntimeException(
"Unable to instantiate application " + appClass
+ ": " + e.toString(), e);
}
}
....
}
再来看mInstrumentation.callApplicationOnCreate(app)
public void callApplicationOnCreate(Application app) {
app.onCreate();
}
至此在App进程中bindApplication
执行完成,回到AMS执行mAtmInternal.attachApplication(app.getWindowProcessController())
,mAtmInternal
是ActivityTaskManagerService
,所以我们来看他的attachApplication
方法:
@Override
public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
synchronized (mGlobalLockWithoutBoost) {
return mRootActivityContainer.attachApplication(wpc);
}
}
来到\frameworks\base\services\core\java\com\android\server\wm\RootActivityContainer.java
的attachApplication
方法:
boolean attachApplication(WindowProcessController app) throws RemoteException {
....
....
try {
if (mStackSupervisor.realStartActivityLocked(activity, app,
top == activity /* andResume */, true /* checkConfig */)) {
didSomething = true;
}
} catch (RemoteException e) {
Slog.w(TAG, "Exception in new application when starting activity "
+ top.intent.getComponent().flattenToShortString(), e);
throw e;
}
....
....
}
}
终于到了大名鼎鼎的realStartActivityLocked
,他在\frameworks\base\services\core\java\com\android\server\wm\ActivityStackSupervisor.java
中:
....
// Create activity launch transaction. 注意这个参数,将一直传输到App进程中
final ClientTransaction clientTransaction = ClientTransaction.obtain(
proc.getThread(), r.appToken);
//将LaunchActivityItem添加到clientTransaction的callback列表中去,这里的intent,就是startActivity时传入的Intent
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),...);
// 设置Activity最终想要达到的状态,resume或者pause
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
....
mService.getLifecycleManager()
获取的是一个\frameworks\base\services\core\java\com\android\server\wm\ClientLifecycleManager.java
对象,调用它的scheduleTransaction
方法:
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();
}
}
ClientTransaction
的schedule
方法:
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
这里mClient
为IApplicationThread
,所以我们又再次回到了App进程:
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
这里我们调用的是ActivityThread
父类ClientTransactionHandler
的scheduleTransaction
方法:
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, 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
的execute
:
public void execute(ClientTransaction transaction) {
//循环遍历回调请求的所有状态并在适当的时间执行它们
executeCallbacks(transaction);
// 转换到最终状态
executeLifecycleState(transaction);
}
这里如果忘记了ClientTransaction 设置的内容的话,可以回到上面的realStartActivityLocked
查看:
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
....
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
....
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
....
}
}
这里执行的肯定就是LaunchActivityItem
的execute
方法了
@Override
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);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
client
就是ActivityThread
,还记得它是继承ClientTransactionHandler
的吗:
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
....
final Activity a = performLaunchActivity(r, customIntent);
....
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
//反射创建Activity
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
....
....
//
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
....
....
}
这里r.isPersistable()是指Activity是否需要持久化的Bundle,详情请看这里 ,其实他们都会调用到Activity的create,只是携带一个或者两个参数的区别。一般的Activity都是调用第二个mInstrumentation.callActivityOnCreate(activity, r.state)
:
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
接下来的内容都在Activity中了,比较简单:
final void performCreate(Bundle icicle) {
performCreate(icicle, null);
}
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
....
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
....
}
这样,就调用到了我们Activity的onCreate方法,TransactionExecutor
的executeLifecycleState(transaction)
会继续调用onResume或者onPause方法。
总结如下: