startActivity桌面启动应用
android12-release
1. Launcher点击应用图标
packages/apps/Launcher3/src/com/android/launcher3/touch/ItemClickHandler.java
packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
packages/apps/Launcher3/src/com/android/launcher3/BaseDraggingActivity.java
packages/apps/Launcher3/src/com/android/launcher3/BaseActivity.java
onClickAppShortcut -> startAppShortcutOrInfoActivity -> launcher.startActivitySafely -> startActivity()
最后调用到Activity.java中。
其中
intent
包含信息:
action = “android.intent.action.MAIN”
category=“android.intent.category.LAUNCHER”
cmp=“[包名]/.MainActivity”
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 配合android:taskAffinity
,默认为包名,冷启动应用时Activity在新的任务栈中启动
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
2. 桌面Activity – Instrumentation – AMS/ATMS
mParent
应用首次启动所以mParent为空。mMainThread.getApplicationThread()
获取ApplicationThread成员变量,是一个Binder对象mToken
Activity类的成员变量,它是一个Binder对象的远程接口ActivityTaskManager.getService()
获取Context.ACTIVITY_TASK_SERVICE
即是 ActivityTaskManagerServiceInstrumentation.java
用来监控应用程序和系统的交互checkStartActivityResult(result, intent);
检查是否启动成功
startActivity() -> startActivityForResult -> mInstrumentation.execStartActivity -> ActivityTaskManager.getService().startActivity
frameworks/base/core/java/android/app/Activity.java
frameworks/base/core/java/android/app/Instrumentation.java
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);
// ... ...
} else {
// ... ...
}
}
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
// ... ...
try {
intent.migrateExtraStreamToClipData(who);
intent.prepareToLeaveProcess(who);
int result = ActivityTaskManager.getService().startActivity(whoThread,
who.getOpPackageName(), who.getAttributionTag(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()), token,
target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
2.1 ActivityTaskManager.getService()
IActivityTaskManagerSingleton.get()
单例模式,Android 中 java 单例模板frameworks/base/core/java/android/util/Singleton.java
,查看单例模式(Singleton) 2- 使用
Binder IPC
获取查看Binder系列3-framework层 Context.ACTIVITY_TASK_SERVICE
AMS服务启动时注册到binder,ActivityManagerService启动-android12
3. Binder IPC调用到 ActivityTaskManagerService
frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
frameworks/base/services/core/java/com/android/server/wm/ActivityStartController.java
frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
ActivityTaskManager.getService().startActivity -> startActivityAsUser() -> getActivityStartController().obtainStarter ........ execute() -> executeRequest(mRequest) -> startActivityUnchecked() -> startActivityInner()
obtainStarter(intent, "startActivityAsUser")
工厂模式mFactory.obtain().setIntent(intent).setReason(reason)
获取ActivityStarterexecuteRequest(mRequest)
这里输出START u
日志,一般定制都会加上pid
打印
ActivityRecord r,sourceRecord
信息startActivityInner()
该方法有许多参数处理,如setInitialState
\computeLaunchingTaskFlags
\computeSourceStack
\mIntent.setFlags(mLaunchFlags)
\computeLaunchParams
startActivityInner()
这里wm_create_task
、wm_create_activity
if (newTask) {
EventLogTags.writeWmCreateTask(mStartActivity.mUserId,
mStartActivity.getTask().mTaskId);
}
mStartActivity.logStartActivity(
EventLogTags.WM_CREATE_ACTIVITY, mStartActivity.getTask());
mDoResume
移到栈顶显示resumeFocusedTasksTopActivities
3.1 先startPausingLocked
mRootWindowContainer.resumeFocusedTasksTopActivities -> resumeTopActivityUncheckedLocked -> resumeTopActivityInnerLocked -> 先startPausingLocked后mTaskSupervisor.startSpecificActivity(next, true, true)
next.attachedToProcess()
此时由于第一次(冷启动)为false,主要在Task.java
操作resumeTopActivityInnerLocked()
- 此时当前
mResumedActivity != null
,即为桌面Launcher,先startPausingLocked()
执行Pausing过程,并输出日志wm_pause_activity
if (mResumedActivity != null) {
ProtoLog.d(WM_DEBUG_STATES, "resumeTopActivityLocked: Pausing %s", mResumedActivity);
pausing |= startPausingLocked(false /* uiSleeping */, next,
"resumeTopActivityInnerLocked");
}
-
prev = mResumedActivity、mPausingActivity = prev
赋值mPausingActivity,并设置状态prev.setState(PAUSING, "startPausingLocked")
-
EventLogTags.writeWmPauseActivity()
Event日志 -
mAtmService.getLifecycleManager().scheduleTransaction()
执行PauseActivityItem
,通过ActivityThread、Instrumentation.callActivityOnPause()
通知到ActivityonPause()
,并输出wm_on_paused_called
(Android P Basic lifecycle transaction containers --设计模式体现之策略模式
)
-
completePauseLocked(false, resuming)
pause完成,并设置状态prev.setState(PAUSED, "completePausedLocked");
frameworks/base/services/core/java/com/android/server/wm/Task.java
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
ActivityRecord resuming, String reason) {
// ... ...
ActivityRecord prev = mResumedActivity;
// ... ...
ProtoLog.v(WM_DEBUG_STATES, "Moving to PAUSING: %s", prev);
mPausingActivity = prev;
mLastPausedActivity = prev;
if (prev.isNoHistory() && !mTaskSupervisor.mNoHistoryActivities.contains(prev)) {
mTaskSupervisor.mNoHistoryActivities.add(prev);
}
prev.setState(PAUSING, "startPausingLocked");
prev.getTask().touchActiveTime();
// ... ...
boolean didAutoPip = false;
if (prev.attachedToProcess()) {
if (shouldAutoPip) {
// ... ...
} else {
ProtoLog.v(WM_DEBUG_STATES, "Enqueueing pending pause: %s", prev);
try {
EventLogTags.writeWmPauseActivity(prev.mUserId, System.identityHashCode(prev),
prev.shortComponentName, "userLeaving=" + userLeaving, reason);
mAtmService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,
prev.configChangeFlags, pauseImmediately));
} catch (Exception e) {
// ... ...
}
}
} else {
// ... ...
}
// ... ...
// ... ...
if (pauseImmediately) {
// If the caller said they don't want to wait for the pause, then complete
// the pause now.
completePauseLocked(false, resuming);
return false;
}
// ... ...
}
- 先走这里
mTaskSupervisor.startSpecificActivity
,执行realStartActivityLocked()
;没有启动执行mService.startProcessAsync()
3.2 startSpecificActivity启动:AMS/ATMS -- Instrumentation -- 应用Activity
WindowProcessController wpc
第一次启动获取到的是null;mService.startProcessAsync()
先fork应用进程
frameworks/base/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
// Is this activity's application already running?
final WindowProcessController wpc =
mService.getProcessController(r.processName, r.info.applicationInfo.uid);
boolean knownToBeDead = false;
if (wpc != null && wpc.hasThread()) {
try {
realStartActivityLocked(r, wpc, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
+ r.intent.getComponent().flattenToShortString(), e);
}
// If a dead object exception was thrown -- fall through to
// restart the application.
knownToBeDead = true;
}
r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
final boolean isTop = andResume && r.isTopRunningActivity();
mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
}
3.2.1 启动ActivityThread(内部成员ApplicationThread)
startProcessAsync
通过ATMS/AMS走到ProcessList.java
中startProcess()
调用Process.start
,通过ZYGOTE_PROCESS.start
fork
生成进程,最后执行到ActivityThread.main()
方法回调AMS.attachApplication
public static void main(String[] args) {
// ... ...
Looper.prepareMainLooper();
// ... ...
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
// ... ...
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
ProcessList.java中handleProcessStartedLocked
输出am_proc_start
、AMS.attachApplication
输出am_proc_bound
EventLog.writeEvent(EventLogTags.AM_PROC_START,
UserHandle.getUserId(app.getStartUid()), pid, app.getStartUid(),
app.processName, app.getHostingRecord().getType(),
app.getHostingRecord().getName() != null ? app.getHostingRecord().getName() : "");
EventLogTags.writeAmProcBound(app.userId, pid, app.processName);
- 几经attachApplication:
AMS.attachApplication -> ATMS.attachApplication -> RootWindowContainer.attachApplication(wpc) -> mTaskSupervisor.realStartActivityLocked()
;最终还是调用到realStartActivityLocked
AMS.attachApplication
中thread.bindApplication()
创建Instrumentation
、app = data.info.makeApplication(data.restrictedBackupMode, null)
,并通过Instrumentation通知到Application:
mInstrumentation.onCreate(data.instrumentationArgs);
mInstrumentation.callApplicationOnCreate(app);
3.2.2 realStartActivityLocked()
真正启动APP
ActivityThread.main() -> AMS.attachApplication -> ATMS.attachApplication -> RootWindowContainer.attachApplication(wpc) / startActivityForAttachedApplicationIfNeeded -> mTaskSupervisor.realStartActivityLocked()
- Event日志
wm_restart_activity
EventLogTags.writeWmRestartActivity(r.mUserId, System.identityHashCode(r),
task.mTaskId, r.shortComponentName);
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
通知到Activity Resumed:wm_on_resume_called
mInstrumentation.callActivityOnResume(this);
EventLogTags.writeWmOnResumeCalled(mIdent, getComponentName().getClassName(), reason);
- 与上面pause不同的是添加了
LaunchActivityItem
frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
(Android P Basic lifecycle transaction containers--设计模式体现之策略模式
)
TransactionExecutor
先执行executeCallbacks
即执行LaunchActivityItem
,所以在Resuemed之前处理handleLaunchActivity()
:
- 初始化
activity = mInstrumentation.newActivity()
activity.attach()
处理WMS相关信息mInstrumentation.callActivityOnCreate()
通知onCreate,设置ActivityClientRecord r.setState(ON_CREATE);
executeLifecycleState(transaction)
在ON_CREATE
和ON_RESUME
之间添加ON_START
流程:mHelper.getLifecyclePath(start, finish, excludeLastState)
frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
public void execute(ClientTransaction transaction) {
// ... ...
if (DEBUG_RESOLVER) Slog.d(TAG, transactionToString(transaction, mTransactionHandler));
executeCallbacks(transaction);
executeLifecycleState(transaction);
mPendingActions.clear();
if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
}
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.
mConfigurationController.handleConfigurationChanged(null, null);
if (localLOGV) Slog.v(
TAG, "Handling launch of " + r);
// Initialize before creating the activity
if (ThreadedRenderer.sRendererEnabled
&& (r.activityInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
HardwareRenderer.preload();
}
WindowManagerGlobal.initialize();
// Hint the GraphicsEnvironment that an activity is launching on the process.
GraphicsEnvironment.hintActivityLaunch();
final Activity a = performLaunchActivity(r, customIntent);
// ... ...
}
4. 时序图
待续~~~ 道阻且长
Log关键字:
ActivityTaskManager: START u|ActivityTaskManager: Displayed
wm_create_activity|wm_set_resumed_activity|wm_resume_activity|wm_on_resume_called|wm_activity_launch_time
06-13 23:14:02.056 1000 1787 10268 I wm_create_task: [0,109]
06-13 23:14:02.056 1000 1787 10268 I wm_create_activity: [0,103558740,109,com.tencent.mobileqq/.activity.SplashActivity,android.intent.action.MAIN,NULL,NULL,270532608]
06-13 23:14:02.059 1000 1787 10268 I wm_pause_activity: [0,3858326,com.miui.home/.launcher.Launcher,userLeaving=true]
06-13 23:14:02.067 10083 22061 22061 I wm_on_paused_called: [0,com.miui.home.launcher.Launcher,performPause,1]
06-13 23:14:02.114 1000 1787 3359 I wm_restart_activity: [0,103558740,109,com.tencent.mobileqq/.activity.SplashActivity]
06-13 23:14:02.117 1000 1787 3359 I wm_set_resumed_activity: [0,com.tencent.mobileqq/.activity.SplashActivity,minimalResumeActivityLocked]
06-13 23:14:02.876 10264 26092 26092 I wm_on_create_called: [0,com.tencent.mobileqq.activity.SplashActivity,performCreate,105]
06-13 23:14:02.878 10264 26092 26092 I wm_on_start_called: [0,com.tencent.mobileqq.activity.SplashActivity,handleStartActivity,1]
06-13 23:14:02.885 10264 26092 26092 I wm_on_resume_called: [0,com.tencent.mobileqq.activity.SplashActivity,RESUME_ACTIVITY,7]
06-13 23:14:02.899 10264 26092 26092 I wm_on_top_resumed_gained_called: [103558740,com.tencent.mobileqq.activity.SplashActivity,topStateChangedWhenResumed]
06-13 23:14:02.988 1000 1787 1839 I wm_activity_launch_time: [0,103558740,com.tencent.mobileqq/.activity.SplashActivity,954]
相关文章:
Android应用程序启动过程源代码分析
Android应用程序内部启动Activity过程(startActivity)的源代码分析
startActivity启动过程分析
【 Android 10 四大组件 】系列 – Activity 的“启动流程”
Android之Activity启动流程详解(基于api28)