概述
当你点击桌面App的图标到底发生了什么,上篇文章我们大概简述了流程
- App发起进程:
如果从桌面启动应用,则发起进程便是Launcher所在的进程,当从某App启动远程进程,则发起进程是App所在的进程,发起进程首先需要通过Binder发送信息给system_server进程
- system_server进程:
调用Process.start方法,通过Socket向Zygote进程发送新建进程的请求
zygote进程:在执行ZygoteInit.main()后进入runSelectLoop()循环体,当有客户端连接时,便会执行ZygoteConnection.runOnce()方法,再经过层层调用后fork出新的应用进程
- 新进程:
执行handleChildProc方法,设置进程名,打开binder驱动,启动新的binder线程,设置art虚拟机参数,反射目标类的main方法,即调用ActivityThread.main()方法
这次我们来详细的分析一下源码,基于android 10.0
添加日志
对应在系统中添加几个日志节点:
Activity.startActivity的日志添加
frameworks\base\core\java\android\app\Activity.java
public void startActivity(Intent intent, @Nullable Bundle options) {
对应输出日志:
Activity: startActivity
Activity: at android.app.Activity.startActivity(Activity.java:5601)
Activity: at com.android.launcher3.BaseDraggingActivity.startActivitySafely(BaseDraggingActivity.java:335)
Activity: at com.android.launcher3.Launcher.startActivity(Launcher.java:4510)
Activity: at com.android.launcher3.Launcher.startActivitySafely(Launcher.java:4478)
Activity: at com.android.launcher3.touch.ItemClickHandler.startApp(ItemClickHandler.java:589)
Activity: at com.android.launcher3.touch.ItemClickHandler.startAppShortcutOrInfoActivity(ItemClickHandler.java:529)
Activity: at com.android.launcher3.touch.ItemClickHandler.onClickAppShortcut(ItemClickHandler.java:469)
Activity: at com.android.launcher3.touch.ItemClickHandler.onClick(ItemClickHandler.java:163)
Activity: at com.android.launcher3.touch.ItemClickHandler.lambda$oPqR0koj5OQZ6VtyqmfcFGp5X0Q(Unknown Source:0)
Activity: at com.android.launcher3.touch.-$$Lambda$ItemClickHandler$oPqR0koj5OQZ6VtyqmfcFGp5X0Q.onClick(Unknown Source:0)
Activity: at android.view.View.performClick(View.java:7285)
Activity: at com.android.launcher3.BubbleTextView.performClick(BubbleTextView.java:624)
Activity: at android.view.View.performClickInternal(View.java:7249)
Activity: at android.view.View.access$3600(View.java:808)
Activity: at android.view.View$PerformClick.run(View.java:27932)
Activity: at android.os.Handler.handleCallback(Handler.java:883)
Activity: at android.os.Handler.dispatchMessage(Handler.java:100)
Activity: at android.os.Looper.loop(Looper.java:221)
Activity: at android.app.ActivityThread.main(ActivityThread.java:7568)
Activity: at java.lang.reflect.Method.invoke(Native Method)
Activity: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
Activity: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
ActivityRecord.ActivityRecord的日志添加
ActivityRecord(ActivityTaskManagerService _service, WindowProcessController _caller,
int _launchedFromPid, int _launchedFromUid, String _launchedFromPackage, Intent _intent,
String _resolvedType, ActivityInfo aInfo, Configuration _configuration,
ActivityRecord _resultTo, String _resultWho, int _reqCode, boolean _componentSpecified,
boolean _rootVoiceInteraction, ActivityStackSupervisor supervisor,
ActivityOptions options, ActivityRecord sourceRecord) {
对应输出日志:
ActivityTaskManager: at com.android.server.wm.ActivityRecord.<init>(ActivityRecord.java:961)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:971)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:608)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.startActivityMayWait(ActivityStarter.java:1502)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.execute(ActivityStarter.java:539)
ActivityTaskManager: at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1258)
ActivityTaskManager: at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1232)
ActivityTaskManager: at com.android.server.wm.ActivityTaskManagerService.startActivity(ActivityTaskManagerService.java:1209)
ActivityTaskManager: at android.app.IActivityTaskManager$Stub.onTransact(IActivityTaskManager.java:1866)
ActivityTaskManager: at android.os.Binder.execTransactInternal(Binder.java:1021)
ActivityTaskManager: at android.os.Binder.execTransact(Binder.java:994)
ActivityStack.ActivityStack的日志添加
ActivityStack(ActivityDisplay display, int stackId, ActivityStackSupervisor supervisor,
int windowingMode, int activityType, boolean onTop) {
对应输出日志:
ActivityTaskManager: at com.android.server.wm.ActivityStack.<init>(ActivityStack.java:536)
ActivityTaskManager: at com.android.server.wm.ActivityDisplay.createStackUnchecked(ActivityDisplay.java:552)
ActivityTaskManager: at com.android.server.wm.ActivityDisplay.createStack(ActivityDisplay.java:542)
ActivityTaskManager: at com.android.server.wm.ActivityDisplay.getOrCreateStack(ActivityDisplay.java:449)
ActivityTaskManager: at com.android.server.wm.ActivityDisplay.getOrCreateStack(ActivityDisplay.java:468)
ActivityTaskManager: at com.android.server.wm.RootActivityContainer.getLaunchStack(RootActivityContainer.java:1767)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.getLaunchStack(ActivityStarter.java:2930)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.computeStackFocus(ActivityStarter.java:2833)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.setTaskFromReuseOrCreateNewTask(ActivityStarter.java:2539)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.startActivityUnchecked(ActivityStarter.java:1898)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:1608)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:1004)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:608)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.startActivityMayWait(ActivityStarter.java:1502)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.execute(ActivityStarter.java:539)
ActivityTaskManager: at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1258)
ActivityTaskManager: at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1232)
ActivityTaskManager: at com.android.server.wm.ActivityTaskManagerService.startActivity(ActivityTaskManagerService.java:1209)
ActivityTaskManager: at android.app.IActivityTaskManager$Stub.onTransact(IActivityTaskManager.java:1866)
ActivityTaskManager: at android.os.Binder.execTransactInternal(Binder.java:1021)
ActivityTaskManager: at android.os.Binder.execTransact(Binder.java:994)
TaskRecord.createTask的日志添加
void createTask(boolean onTop, boolean showForAllUsers) {
对应输出日志:
ActivityTaskManager: at com.android.server.wm.TaskRecord.createTask(TaskRecord.java:552)
ActivityTaskManager: at com.android.server.wm.ActivityStack.createTaskRecord(ActivityStack.java:6067)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.setTaskFromReuseOrCreateNewTask(ActivityStarter.java:2546)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.startActivityUnchecked(ActivityStarter.java:1898)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:1608)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:1004)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:608)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.startActivityMayWait(ActivityStarter.java:1502)
ActivityTaskManager: at com.android.server.wm.ActivityStarter.execute(ActivityStarter.java:539)
ActivityTaskManager: at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1258)
ActivityTaskManager: at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1232)
ActivityTaskManager: at com.android.server.wm.ActivityTaskManagerService.startActivity(ActivityTaskManagerService.java:1209)
ActivityTaskManager: at android.app.IActivityTaskManager$Stub.onTransact(IActivityTaskManager.java:1866)
ActivityTaskManager: at android.os.Binder.execTransactInternal(Binder.java:1021)
ActivityTaskManager: at android.os.Binder.execTransact(Binder.java:994)
WindowToken.WindowToken的日志添加
WindowToken(WindowManagerService service, IBinder _token, int type, boolean persistOnEmpty,
DisplayContent dc, boolean ownerCanManageAppTokens) {
this(service, _token, type, persistOnEmpty, dc, ownerCanManageAppTokens,
false /* roundedCornersOverlay */);
}
对应输出日志:
WindowManager: at com.android.server.wm.WindowToken.<init>(WindowToken.java:113)
WindowManager: at com.android.server.wm.AppWindowToken.<init>(AppWindowToken.java:373)
WindowManager: at com.android.server.wm.AppWindowToken.<init>(AppWindowToken.java:347)
WindowManager: at com.android.server.wm.ActivityRecord.createAppWindow(ActivityRecord.java:1220)
WindowManager: at com.android.server.wm.ActivityRecord.createAppWindowToken(ActivityRecord.java:1152)
WindowManager: at com.android.server.wm.ActivityStack.startActivityLocked(ActivityStack.java:3562)
WindowManager: at com.android.server.wm.ActivityStarter.startActivityUnchecked(ActivityStarter.java:1928)
WindowManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:1608)
WindowManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:1004)
WindowManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:608)
WindowManager: at com.android.server.wm.ActivityStarter.startActivityMayWait(ActivityStarter.java:1502)
WindowManager: at com.android.server.wm.ActivityStarter.execute(ActivityStarter.java:539)
WindowManager: at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1258)
WindowManager: at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1232)
WindowManager: at com.android.server.wm.ActivityTaskManagerService.startActivity(ActivityTaskManagerService.java:1209)
WindowManager: at android.app.IActivityTaskManager$Stub.onTransact(IActivityTaskManager.java:1866)
WindowManager: at android.os.Binder.execTransactInternal(Binder.java:1021)
WindowManager: at android.os.Binder.execTransact(Binder.java:994)
AppWindowToken.AppWindowToken的日志添加
AppWindowToken(WindowManagerService service, IApplicationToken token,
ComponentName activityComponent, boolean voiceInteraction, DisplayContent dc,
long inputDispatchingTimeoutNanos, boolean fullscreen, boolean showForAllUsers,
int targetSdk, int orientation, int rotationAnimationHint,
boolean launchTaskBehind, boolean alwaysFocusable,
ActivityRecord activityRecord) {
this(service, token, activityComponent, voiceInteraction, dc, fullscreen);
对应输出日志:
WindowManager: at com.android.server.wm.AppWindowToken.<init>(AppWindowToken.java:348)
WindowManager: at com.android.server.wm.ActivityRecord.createAppWindow(ActivityRecord.java:1220)
WindowManager: at com.android.server.wm.ActivityRecord.createAppWindowToken(ActivityRecord.java:1152)
WindowManager: at com.android.server.wm.ActivityStack.startActivityLocked(ActivityStack.java:3562)
WindowManager: at com.android.server.wm.ActivityStarter.startActivityUnchecked(ActivityStarter.java:1928)
WindowManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:1608)
WindowManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:1004)
WindowManager: at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:608)
WindowManager: at com.android.server.wm.ActivityStarter.startActivityMayWait(ActivityStarter.java:1502)
WindowManager: at com.android.server.wm.ActivityStarter.execute(ActivityStarter.java:539)
WindowManager: at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1258)
WindowManager: at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1232)
WindowManager: at com.android.server.wm.ActivityTaskManagerService.startActivity(ActivityTaskManagerService.java:1209)
WindowManager: at android.app.IActivityTaskManager$Stub.onTransact(IActivityTaskManager.java:1866)
WindowManager: at android.os.Binder.execTransactInternal(Binder.java:1021)
WindowManager: at android.os.Binder.execTransact(Binder.java:994)
ActivityStackSupervisor.java.startSpecificActivityLocked的日志添加
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
对应输出日志:
ActivityTaskManager: startSpecificActivityLocked
ActivityTaskManager: at com.android.server.wm.ActivityStackSupervisor.startSpecificActivityLocked(ActivityStackSupervisor.java:998)
ActivityTaskManager: at com.android.server.wm.ActivityStack.resumeTopActivityInnerLocked(ActivityStack.java:3401)
ActivityTaskManager: at com.android.server.wm.ActivityStack.resumeTopActivityUncheckedLocked(ActivityStack.java:2903)
ActivityTaskManager: at com.android.server.wm.RootActivityContainer.resumeFocusedStacksTopActivities(RootActivityContainer.java:1189)
ActivityTaskManager: at com.android.server.wm.ActivityStack.completePauseLocked(ActivityStack.java:2056)
ActivityTaskManager: at com.android.server.wm.ActivityStack.activityPausedLocked(ActivityStack.java:1983)
ActivityTaskManager: at com.android.server.wm.ActivityTaskManagerService.activityPaused(ActivityTaskManagerService.java:1919)
ActivityTaskManager: at android.app.IActivityTaskManager$Stub.onTransact(IActivityTaskManager.java:2361)
ActivityTaskManager: at android.os.Binder.execTransactInternal(Binder.java:1021)
ActivityTaskManager: at android.os.Binder.execTransact(Binder.java:994)
ActivityTaskManager: startSpecificActivityLocked
ActivityTaskManager: at com.android.server.wm.ActivityStackSupervisor.startSpecificActivityLocked(ActivityStackSupervisor.java:998)
ActivityTaskManager: at com.android.server.wm.ActivityStack.makeVisibleAndRestartIfNeeded(ActivityStack.java:2715)
ActivityTaskManager: at com.android.server.wm.ActivityStack.ensureActivitiesVisibleLocked(ActivityStack.java:2470)
ActivityTaskManager: at com.android.server.wm.ActivityDisplay.ensureActivitiesVisible(ActivityDisplay.java:1544)
ActivityTaskManager: at com.android.server.wm.RootActivityContainer.ensureActivitiesVisible(RootActivityContainer.java:825)
ActivityTaskManager: at com.android.server.wm.RootActivityContainer.ensureActivitiesVisible(RootActivityContainer.java:812)
ActivityTaskManager: at com.android.server.wm.ActivityStack.completePauseLocked(ActivityStack.java:2096)
ActivityTaskManager: at com.android.server.wm.ActivityStack.activityPausedLocked(ActivityStack.java:1983)
ActivityTaskManager: at com.android.server.wm.ActivityTaskManagerService.activityPaused(ActivityTaskManagerService.java:1919)
ActivityTaskManager: at android.app.IActivityTaskManager$Stub.onTransact(IActivityTaskManager.java:2361)
ActivityTaskManager: at android.os.Binder.execTransactInternal(Binder.java:1021)
ActivityTaskManager: at android.os.Binder.execTransact(Binder.java:994)
Activity.onResume的日志添加
frameworks\base\core\java\android\app\Activity.java
protected void onResume() {
对应输出日志:
Activity: onResume com.android.dialer.app.DialtactsActivity@ab78927
Activity: at android.app.Activity.onResume(Activity.java:1799)
Activity: at androidx.fragment.app.FragmentActivity.onResume(FragmentActivity.java:456)
Activity: at com.android.dialer.util.TransactionSafeActivity.onResume(TransactionSafeActivity.java:45)
Activity: at com.android.dialer.app.DialtactsActivity.onResume(DialtactsActivity.java:554)
Activity: at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1454)
Activity: at android.app.Activity.performResume(Activity.java:8047)
Activity: at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4267)
Activity: at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4309)
Activity: at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
Activity: at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
Activity: at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
Activity: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2027)
Activity: at android.os.Handler.dispatchMessage(Handler.java:107)
Activity: at android.os.Looper.loop(Looper.java:221)
Activity: at android.app.ActivityThread.main(ActivityThread.java:7568)
Activity: at java.lang.reflect.Method.invoke(Native Method)
Activity: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
Activity: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
ProcessList.startProcessLocked的日志添加
boolean startProcessLocked(HostingRecord hostingRecord,
String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {
对应输出日志:
ActivityManager: startProcessLocked
ActivityManager: at com.android.server.am.ProcessList.startProcessLocked(ProcessList.java:1654)
ActivityManager: at com.android.server.am.ProcessList.startProcessLocked(ProcessList.java:1630)
ActivityManager: at com.android.server.am.ProcessList.startProcessLocked(ProcessList.java:1861)
ActivityManager: at com.android.server.am.ProcessList.startProcessLocked(ProcessList.java:1970)
ActivityManager: at com.android.server.am.ActivityManagerService.startProcessLocked(ActivityManagerService.java:3096)
ActivityManager: at com.android.server.am.BroadcastQueue.processNextBroadcastLocked(BroadcastQueue.java:1778)
ActivityManager: at com.android.server.am.ActivityManagerService.finishReceiver(ActivityManagerService.java:16118)
ActivityManager: at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:1993)
ActivityManager: at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2811)
ActivityManager: at android.os.Binder.execTransactInternal(Binder.java:1021)
ActivityManager: at android.os.Binder.execTransact(Binder.java:994)
1.Launcher
当你点击桌面上的App图标,Launcher捕获点击事件,其过程为BubbleTextView#performClick-> ItemClickHandler#onClick->ItemClickHandler#startAppShortcutOrInfoActivity->BaseDraggingActivity#startActivitySafely-> Activity#startActivity最终调用了 startActivity(intent, optsBundle);方法
其详细流程为:
android.app.Activity.startActivity(Activity.java:5602)
com.android.launcher3.BaseDraggingActivity.startActivitySafely(BaseDraggingActivity.java:335)
com.android.launcher3.Launcher.startActivity(Launcher.java:4505)
com.android.launcher3.Launcher.startActivitySafely(Launcher.java:4473)
com.android.launcher3.touch.ItemClickHandler.startApp(ItemClickHandler.java:589)
com.android.launcher3.touch.ItemClickHandler.startAppShortcutOrInfoActivity(ItemClickHandler.java:529)
com.android.launcher3.touch.ItemClickHandler.onClickAppShortcut(ItemClickHandler.java:469)
com.android.launcher3.touch.ItemClickHandler.onClick(ItemClickHandler.java:163)
com.android.launcher3.touch.ItemClickHandler.lambda$oPqR0koj5OQZ6VtyqmfcFGp5X0Q(Unknown Source:0)
com.android.launcher3.touch.-$$Lambda$ItemClickHandler$oPqR0koj5OQZ6VtyqmfcFGp5X0Q.onClick(Unknown Source:0)
android.view.View.performClick(View.java:7287)
com.android.launcher3.BubbleTextView.performClick(BubbleTextView.java:624)
android.view.View.performClickInternal(View.java:7251)
android.view.View.access$3600(View.java:809)
android.view.View$PerformClick.run(View.java:28033)
android.os.Handler.handleCallback(Handler.java:883)
android.os.Handler.dispatchMessage(Handler.java:100)
android.os.Looper.loop(Looper.java:221)
android.app.ActivityThread.main(ActivityThread.java:7569)
java.lang.reflect.Method.invoke(Native Method)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
其时序图:
下面我们从startActivity(intent, optsBundle);方法开始分析调用流程
2.启动应用的详细流程
Activity.startActivity
上方我们说到了Activity.startActivity,点进源码发现调用的是Activity#startActivityForResult,其中还调用到了Instrumentation#execStartActivity这个方法,源码如下
frameworks\base\core\java\android\app\Activity.java
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);//execStartActivity
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());//sendActivityResult
}
......
Instrumentation.execStartActivity
在Instrumentation.execStartActivity中,我们发现他调用了ActivityTaskManager#getService()#startActivity,其中ActivityTaskManager#getService()返回的是IActivityTaskManager类型的Binder对象,他的具体实现在ActivityTaskManagerService
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) {
......
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
int result = ActivityTaskManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options); //startActivity
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
frameworks\base\core\java\android\app\ActivityTaskManager.java
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
ActivityTaskManagerService.startActivity
我们查看ActivityTaskManagerService.startActivity源码,发现他调用了ActivityTaskManagerService#startActivityAsUser,该方法又调用了ActivityStarter#execute
源码如下:
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());//startActivityAsUser
}
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 /*validateIncomingUser*/);//startActivityAsUser
}
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");
// TODO: Switch to user app stacks here.
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setMayWait(userId)
.execute();
}
frameworks\base\services\core\java\com\android\server\wm\ActivityStartController.java
ActivityStarter obtainStarter(Intent intent, String reason) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}
ActivityStarter.execute
ActivityStarter.execute—-ActivityStarter.startActivityMayWait—-ActivityStarter.startActivity—-ActivityStarter.startActivity—-ActivityStarter.startActivity—-ActivityStarter.startActivityUnchecked—- —-ActivityStack.startActivityLocked
frameworks\base\services\core\java\com\android\server\wm\ActivityStarter.java
/** * Starts an activity based on the request parameters provided earlier. * @return The starter result. */
int execute() {
try {
// TODO(b/64750076): Look into passing request directly to these methods to allow
// for transactional diffs and preprocessing.
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);//startActivityMayWait
} else {
return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
mRequest.outActivity, mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup,
mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);//startActivity
}
} finally {
onExecutionComplete();
}
}
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) {
......
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); //startActivity
......
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) {
......
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);//startActivity
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) {
......
final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity);//startActivity
mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outActivity[0]);
return res;
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
int result = START_CANCELED;
final ActivityStack startedActivityStack;
try {
mService.mWindowManager.deferSurfaceLayout();
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
......
// Note: This method should only be called from {@link startActivity}.
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
......
final boolean dontStart = top != null && mStartActivity.resultTo == null
&& top.mActivityComponent.equals(mStartActivity.mActivityComponent)
&& top.mUserId == mStartActivity.mUserId
&& top.attachedToProcess()
&& ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
|| isLaunchModeOneOf(LAUNCH_SINGLE_TOP, LAUNCH_SINGLE_TASK))
// This allows home activity to automatically launch on secondary display when
// display added, if home was the top activity on default display, instead of
// sending new intent to the home activity on default display.
&& (!top.isActivityTypeHome() || top.getDisplayId() == mPreferredDisplayId);
if (dontStart) {
// For paranoia, make sure we have correctly resumed the top activity.
topStack.mLastPausedActivity = null;
if (mDoResume) {
mRootActivityContainer.resumeFocusedStacksTopActivities();//1.mRootActivityContainer.resumeFocusedStacksTopActivities
}
......
if (newTask) {
EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, mStartActivity.mUserId,
mStartActivity.getTaskRecord().taskId);
}
ActivityStack.logStartActivity(
EventLogTags.AM_CREATE_ACTIVITY, mStartActivity, mStartActivity.getTaskRecord());
mTargetStack.mLastPausedActivity = null;
mRootActivityContainer.sendPowerHintForLaunchStartIfNeeded(
false /* forceSend */, mStartActivity);
mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
mOptions);//2.mTargetStack.startActivityLocked
我们先看//2.mTargetStack.startActivityLocked:
ActivityStack.startActivityLocked
这个主要是创建appWindowToken
ActivityStack.startActivityLocked—-ActivityRecord.createAppWindowToken
frameworks\base\services\core\java\com\android\server\wm\ActivityStack.java
void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,
boolean newTask, boolean keepCurTransition, ActivityOptions options) {
TaskRecord rTask = r.getTaskRecord();
final int taskId = rTask.taskId;
final boolean allowMoveToFront = options == null || !options.getAvoidMoveToFront();
// mLaunchTaskBehind tasks get placed at the back of the task stack.
if (!r.mLaunchTaskBehind && allowMoveToFront
&& (taskForIdLocked(taskId) == null || newTask)) {
// Last activity in task had been removed or ActivityManagerService is reusing task.
// Insert or replace.
// Might not even be in.
insertTaskAtTop(rTask, r);//insertTaskAtTop
}
TaskRecord task = null;
if (!newTask) {
// If starting in an existing task, find where that is...
boolean startIt = true;
for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
task = mTaskHistory.get(taskNdx);
if (task.getTopActivity() == null) {
// All activities in task are finishing.
continue;
}
if (task == rTask) {
// Here it is! Now, if this is not yet visible to the
// user, then just add it without starting; it will
// get started when the user navigates back to it.
if (!startIt) {
if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "
+ task, new RuntimeException("here").fillInStackTrace());
r.createAppWindowToken();//创建appWindowToken
ActivityOptions.abort(options);
return;
}
break;
} else if (task.numFullscreen > 0) {
startIt = false;
}
}
}
// Place a new activity at top of stack, so it is next to interact with the user.
// If we are not placing the new activity frontmost, we do not want to deliver the
// onUserLeaving callback to the actual frontmost activity
final TaskRecord activityTask = r.getTaskRecord();
if (task == activityTask && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) {
mStackSupervisor.mUserLeaving = false;
if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING,
"startActivity() behind front, mUserLeaving=false");
}
task = activityTask;
// Slot the activity into the history stack and proceed
if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task,
new RuntimeException("here").fillInStackTrace());
// TODO: Need to investigate if it is okay for the controller to already be created by the
// time we get to this point. I think it is, but need to double check.
// Use test in b/34179495 to trace the call path.
if (r.mAppWindowToken == null) {
r.createAppWindowToken();//创建appWindowToken
}
task.setFrontOfTask();
......
RootActivityContainer.resumeFocusedStacksTopActivities
我们再看//1.mRootActivityContainer.resumeFocusedStacksTopActivities
RootActivityContainer.resumeFocusedStacksTopActivities—-RootActivityContainer.resumeFocusedStacksTopActivities—-ActivityStack.resumeTopActivityUncheckedLocked—-ActivityStack.resumeTopActivityInnerLocked—-ActivityStackSupervisor.startSpecificActivityLocked
frameworks\base\services\core\java\com\android\server\wm\RootActivityContainer.java
boolean resumeFocusedStacksTopActivities() {
return resumeFocusedStacksTopActivities(null, null, null);
}
boolean resumeFocusedStacksTopActivities(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
.....
boolean result = false;
if (targetStack != null && (targetStack.isTopStackOnDisplay()
|| getTopDisplayFocusedStack() == targetStack)) {
result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
frameworks\base\services\core\java\com\android\server\wm\ActivityStack.java
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mInResumeTopActivity) {
// Don't even start recursing.
return false;
}
boolean result = false;
try {
// Protect against recursion.
mInResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options);
......
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
......
if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);
mStackSupervisor.startSpecificActivityLocked(next, true, true);
ActivityStackSupervisor.startSpecificActivityLocked
这个主要有二个操作,realStartActivityLocked和AMS startProcess。
frameworks\base\services\core\java\com\android\server\wm\ActivityStackSupervisor.java
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
......
realStartActivityLocked(r, wpc, andResume, checkConfig);//1.realStartActivityLocked
......
// Post message to start process to avoid possible deadlock of calling into AMS with the
// ATMS lock held.
final Message msg = PooledLambda.obtainMessage(
ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
mService.mH.sendMessage(msg);//2.AMS startProcess
} finally {
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
}
ActivityManagerService.startProcess
ActivityManagerService.startProcess—-ActivityManagerService.startProcessLocked
frameworks\base\services\core\java\com\android\server\am\ActivityManagerService.java
public void startProcess(String processName, ApplicationInfo info,
boolean knownToBeDead, String hostingType, ComponentName hostingName) {
......
synchronized (ActivityManagerService.this) {
startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
new HostingRecord(hostingType, hostingName),
false /* allowWhileBooting */, false /* isolated */,
true /* keepIfLarge */);
}
......
final ProcessRecord startProcessLocked(String processName,
ApplicationInfo info, boolean knownToBeDead, int intentFlags,
HostingRecord hostingRecord, boolean allowWhileBooting,
boolean isolated, boolean keepIfLarge) {
return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
hostingRecord, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
null /* crashHandler */);
}
ProcessList.startProcessLocked
ProcessList.startProcessLocked—-ProcessList.startProcess—-Process.start
frameworks\base\services\core\java\com\android\server\am\ProcessList.java
boolean startProcessLocked(HostingRecord hostingRecord,
String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {
......
final Process.ProcessStartResult startResult = startProcess(app.hostingRecord,
entryPoint, app, app.startUid, gids, runtimeFlags, mountExternal,
app.seInfo, requiredAbi, instructionSet, invokeWith, app.startTime);//startProcess
synchronized (mService) {
handleProcessStartedLocked(app, startResult, startSeq);
private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {
try {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
app.processName);
checkSlow(startTime, "startProcess: asking zygote to start proc");
final Process.ProcessStartResult startResult;
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,
new String[] {
PROC_START_SEQ_IDENT + app.startSeq});
} else if (hostingRecord.usesAppZygote()) {
final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
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,
/*useUsapPool=*/ false,
new String[] {
PROC_START_SEQ_IDENT + app.startSeq});//1.appZygote.getProcess().start
} else {
startResult = Process.start(entryPoint,
app.processName, uid, uid, gids, runtimeFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, invokeWith, app.info.packageName,
new String[] {
PROC_START_SEQ_IDENT + app.startSeq});//2.Process.start
最终调用Process.start来开启新进程,这个进程的入口就会在android.app.ActivityThread.java的main方法,我们下面继续分析ActivityThread#main
ActivityThread#main
ActivityThread#main方法其中调用了ActivityThread#attach方法,这个方法中的ActivityManager.getService()返回的是IActivityManager类型的Binder对象,其实现类是ActivityManagerService,源码如下
frameworks\base\core\java\android\app\ActivityThread.java
public static void main(String[] args) {
......
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
......
Looper.loop();
......
private void attach(boolean system, long startSeq) {
......
final IActivityManager mgr = ActivityManager.getService();
try {
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
......
现在我们又回到了ActivityManagerService中,查看其attachApplication方法,发现调用了thread#bindApplication和mStackSupervisor#attachApplicationLocked,我们一次讲解这俩个方法作用
frameworks\base\services\core\java\com\android\server\am\ActivityManagerService.java
public final void attachApplication(IApplicationThread thread, long startSeq) {
synchronized (this) {
int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid, callingUid, startSeq);//attachApplicationLocked
IApplicationThread thread;
private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
int pid, int callingUid, long startSeq) {
......
thread.bindApplication(processName, appInfo, providers,
instr2.mClass,
profilerInfo, instr2.mArguments,
instr2.mWatcher,
instr2.mUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.isPersistent(),
new Configuration(app.getWindowProcessController().getConfiguration()),
app.compat, getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, autofillOptions, contentCaptureOptions);
......
thread#bindApplication
上面说到的thread#bindApplication中的thread类型是ApplicationThread,是ActivityThread的一个内部类,继承自IApplicationThread.Stub,我们查看ApplicationThread#bindApplication方法,我发现调用了ActivityThread#sendMessage 方法,它内部调用mH.sendMessage来发送消息,其中mH是ActivityThread的一个内部类H的一个实例
frameworks\base\core\java\android\app\ActivityThread.java
public final void bindApplication(String processName, ApplicationInfo appInfo,
List<ProviderInfo> providers, ComponentName instrumentationName,
ProfilerInfo profilerInfo, Bundle instrumentationArgs,
IInstrumentationWatcher instrumentationWatcher,
IUiAutomationConnection instrumentationUiConnection, int debugMode,
boolean enableBinderTracking, boolean trackAllocation,
boolean isRestrictedBackupMode, boolean persistent, Configuration config,
CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
String buildSerial, AutofillOptions autofillOptions,
ContentCaptureOptions contentCaptureOptions) {
......
sendMessage(H.BIND_APPLICATION, data);
}
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) {
if (DEBUG_MESSAGES) Slog.v(
TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
+ ": " + arg1 + " / " + obj);
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
mH.sendMessage(msg);
}
H.handleMessage
我们来看一下H这个内部类的handleMessage,最终走到了ActivityThread#handleBindApplication方法
public void handleMessage(Message msg) {
...
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;
...
}
}
ActivityThread#handleBindApplication
从源码中我们发现,他首先创建了mInstrumentation对象,调用data#info#makeApplication来创建Application对象,其中data#info代表的是LoadedApk的一个实例,查看LoadedApk#makeApplication方法可以看到,内部调用了Instrumentation#newApplication方法,这个方法内部调用Class#newInstance()来完成对Application的实例化,然后调用Application#attach(context)来绑定Context
上面创建完Application后,就调用Instrumentation#callApplicationOnCreate走Application的onCreate生命周期,源码如下
private void handleBindApplication(AppBindData data) {
...
final InstrumentationInfo ii;
...
// 创建 mInstrumentation 实例
if (ii != null) {
final ApplicationInfo instrApp = new ApplicationInfo();
ii.copyTo(instrApp);
instrApp.initForUser(UserHandle.myUserId());
final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
appContext.getClassLoader(), false, true, false);
final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
try {
final ClassLoader cl = instrContext.getClassLoader();
mInstrumentation = (Instrumentation)
cl.loadClass(data.instrumentationName.getClassName()).newInstance();
} catch (Exception e) {
...
}
...
} else {
mInstrumentation = new Instrumentation();
}
...
Application app;
...
// 创建 Application 实例
try {
...
app = data.info.makeApplication(data.restrictedBackupMode, null);
mInitialApplication = app;
...
try {
mInstrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
...
}
} finally {
...
}
...
}
frameworks\base\core\java\android\app\LoadedApk.java
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}
try {
java.lang.ClassLoader cl = getClassLoader();
...
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {
...
}
mActivityThread.mAllApplications.add(app);
mApplication = app;
if (instrumentation != null) {
// 传入为 null 所以不走
try {
instrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
...
}
}
...
return app;
}
frameworks\base\core\java\android\app\Instrumentation.java
public Application newApplication(ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
Application app = getFactory(context.getPackageName())
.instantiateApplication(cl, className);
app.attach(context);
return app;
}
static public Application newApplication(Class<?> clazz, Context context)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
Application app = (Application)clazz.newInstance();
app.attach(context);
return app;
}
mStackSupervisor#realStartActivityLocked
ActivityStackSupervisor#realStartActivityLocked,这个方法调用了scheduleTransaction,源码如下
frameworks\base\services\core\java\com\android\server\wm\ActivityStackSupervisor.java
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
......
// Create activity launch transaction.
final ClientTransaction clientTransaction = ClientTransaction.obtain(
proc.getThread(), r.appToken);
final DisplayContent dc = r.getDisplay().mDisplayContent;
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.icicle, r.persistentState, results, newIntents,
dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
r.assistToken));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);//scheduleTransaction
ActivityThread.handleLaunchActivity
ActivityThread.handleLaunchActivity—-ActivityThread.performLaunchActivity
frameworks\base\core\java\android\app\ActivityThread.java
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
......
// Make sure we are running with the most recent config.
handleConfigurationChanged(null, null);
......
WindowManagerGlobal.initialize();
// Hint the GraphicsEnvironment that an activity is launching on the process.
GraphicsEnvironment.hintActivityLaunch();
final Activity a = performLaunchActivity(r, customIntent);//performLaunchActivity
......
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
......
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);//activity.attach
......
activity.mCalled = false;
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);//callActivityOnCreate
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);//callActivityOnCreate
return activity;
}
Instrumentation.callActivityOnCreate
Instrumentation.callActivityOnCreate—-activity.performCreate
frameworks\base\core\java\android\app\Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle,
PersistableBundle persistentState) {
prePerformCreate(activity);
activity.performCreate(icicle, persistentState);
postPerformCreate(activity);
}
frameworks\base\core\java\android\app\Activity.java
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
dispatchActivityPreCreated(icicle);
mCanEnterPictureInPicture = true;
restoreHasCurrentPermissionRequest(icicle);
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
mActivityTransitionState.readState(icicle);
mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowNoDisplay, false);
mFragments.dispatchActivityCreated();
mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
dispatchActivityPostCreated(icicle);
}
一个简单的流程Demo图
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debug_hxm_test";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
然后我们点击桌面应用图标启动应用,可以看到其调用流程:
com.firstdemo.MainActivity.onCreate(MainActivity.java:16)
android.app.Activity.performCreate(Activity.java:7877)
android.app.Activity.performCreate(Activity.java:7866)
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3310)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3474)
android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:2027)
android.os.Handler.dispatchMessage(Handler.java:107)
android.os.Looper.loop(Looper.java:221)
android.app.ActivityThread.main(ActivityThread.java:7552)
java.lang.reflect.Method.invoke(Native Method)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
其时序图为:
参考资料
(1)Android App启动过程
https://juejin.cn/post/6844903933802987528
今天的文章androidapp启动流程_开发第一个android程序分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/70985.html