# 核心原始碼
Source | Path(/packages/apps/Launcher3/) |
---|---|
BaseDraggingActivity.java | src/com/android/launcher3/BaseDraggingActivity.java |
ItemClickHandler.java | src/com/android/launcher3/touch/ItemClickHandler.java |
Launcher.java | src/com/android/launcher3/Launcher.java |
Source | Path(/framework/base/) |
Activity.java | core/java/android/app/Activity.java |
ActivityManager.java | core/java/android/app/ActivityManager.java |
ActivityThread.java | core/java/android/app/ActivityThread.java |
ClientTransaction.java | core/java/android/app/servertransaction/ClientTransaction.java |
ClientTransactionHandler.java | core/java/android/app/ClientTransactionHandler.java |
Instrumentation.java | core/java/android/app/Instrumentation.java |
LaunchActivityItem.java | core/java/android/app/servertransaction/LaunchActivityItem.java |
PauseActivityItem.java | core/java/android/app/servertransaction/PauseActivityItem.java |
Process.java | core/java/android/os/Process.java |
TransactionExecutor.java | core/java/android/app/servertransaction/TransactionExecutor.java |
ActivityManagerService.java | services/core/java/com/android/server/am/ActivityManagerService.java |
ActivityStack.java | services/core/java/com/android/server/am/ActivityStack.java |
ActivityStarter.java | services/core/java/com/android/server/am/ActivityStarter.java |
ActivityStartController.java | services/core/java/com/android/server/am/ActivityStartController.java |
ActivityStackSupervisor.java | services/core/java/com/android/server/am/ActivityStackSupervisor.java |
ClientLifecycleManager.java | services/core/java/com/android/server/am/ClientLifecycleManager.java |
一、前言
點選 Launcher 介面的應用圖示,執行各種眼花繚亂,功能強大的應用,是我們的日常行為,作為一名系統工程師,我們有必要一起深入研究一下,當我們點選 APK 圖示,直到應用的主介面最後顯示出來,這期間從原始碼角度到底發生了什麼,處理邏輯是什麼樣的?
這個流程個人覺得是非常必要深刻理解的,比如有時當我們點選應用出現了 卡頓
、黑白屏
現象,這些是應用本身的問題,還是系統的問題?當你分析此類問題的時候,如果對 Activity 的啟動流程不熟悉,分析起來會狠吃力,並且未必能深入分析得到最根本的原因。
廢話不多說,為了更方便並且細緻的分析原始碼流程,我們選取 Launcher 介面點選應用
為切入點進行分析(通過一個特定場景/操作是研究原始碼最好的做法),接下來直接進入正題。(各位獅子們,這也是很多面試官喜歡提問的問題)
二、Launcher 的 onPause 流程
我們既然要啟動新的 APK 置於前臺,那麼當前活動必然要被切換到後臺,所以首先涉及到的就是 Launcher 的 onPause
流程。Activity 的生命週期可以閱讀 【 Android '四大元件' 】篇 -- Activity 的 "生命週期" 一文。
2.1 ItemClickHandler.onClick
當點選應用程式 Launcher 的某個圖示時,回撥介面 ItemClickHandler
會執行 onClick()
方法中的 startAppShortcutOrInfoActivity
。
// packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
public View createShortcut(ViewGroup parent, ShortcutInfo info) {
BubbleTextView favorite = (BubbleTextView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.app_icon, parent, false);
favorite.applyFromShortcutInfo(info);
favorite.setOnClickListener(ItemClickHandler.INSTANCE);
favorite.setOnFocusChangeListener(mFocusHandler);
return favorite;
}
// packages/apps/Launcher3/src/com/android/launcher3/touch/ItemClickHandler.java
public class ItemClickHandler {
public static final OnClickListener INSTANCE = ItemClickHandler::onClick;
private static void onClick(View v) {
... ...
if (tag instanceof ShortcutInfo) {
onClickAppShortcut(v, (ShortcutInfo) tag, launcher);
} else if (tag instanceof FolderInfo) {
if (v instanceof FolderIcon) {
onClickFolderIcon(v);
}
} else if (tag instanceof AppInfo) {
// 執行 startAppShortcutOrInfoActivity 方法
startAppShortcutOrInfoActivity(v, (AppInfo) tag, launcher);
} else if (tag instanceof LauncherAppWidgetInfo) {
if (v instanceof PendingAppWidgetHostView) {
onClickPendingWidget((PendingAppWidgetHostView) v, launcher);
}
}
}
... ...
}
複製程式碼
2.2 ItemClickHandler.startAppShortcutOrInfoActivity
// packages/apps/Launcher3/src/com/android/launcher3/touch/ItemClickHandler.java
private static void startAppShortcutOrInfoActivity(View v, ItemInfo item, Launcher launcher) {
Intent intent;
if (item instanceof PromiseAppInfo) {
PromiseAppInfo promiseAppInfo = (PromiseAppInfo) item;
intent = promiseAppInfo.getMarketIntent(launcher);
} else {
intent = item.getIntent();
}
if (intent == null) {
throw new IllegalArgumentException("Input must have a valid intent");
}
if (item instanceof ShortcutInfo) {
ShortcutInfo si = (ShortcutInfo) item;
if (si.hasStatusFlag(ShortcutInfo.FLAG_SUPPORTS_WEB_UI)
&& intent.getAction() == Intent.ACTION_VIEW) {
intent = new Intent(intent);
intent.setPackage(null);
}
}
// 執行 startActivitySafely 方法
launcher.startActivitySafely(v, intent, item);
}
複製程式碼
2.3 Launcher.startActivitySafely
程式碼最終走到 Launcher 的 startActivitySafely()
方法。
// packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
// 呼叫父類 BaseDraggingActivity 的 startActivitySafely 方法
boolean success = super.startActivitySafely(v, intent, item);
if (success && v instanceof BubbleTextView) {
BubbleTextView btv = (BubbleTextView) v;
btv.setStayPressed(true);
setOnResumeCallback(btv);
}
return success; // 表示啟動新應用程式的 Activity 成功
}
複製程式碼
2.4 BaseDraggingActivity.startActivitySafely
// packages/apps/Launcher3/src/com/android/launcher3/BaseDraggingActivity.java
public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
... ...
// 新增標誌,表示要在一個新的 Task 中啟動這個 Activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (v != null) {
intent.setSourceBounds(getViewBounds(v));
}
try {
boolean isShortcut = Utilities.ATLEAST_MARSHMALLOW
&& (item instanceof ShortcutInfo)
&& (item.itemType == Favorites.ITEM_TYPE_SHORTCUT
|| item.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT)
&& !((ShortcutInfo) item).isPromise();
if (isShortcut) {
startShortcutIntentSafely(intent, optsBundle, item);
} else if (user == null || user.equals(Process.myUserHandle())) {
startActivity(intent, optsBundle); // 呼叫 Activity.startActivity 方法
} else {
LauncherAppsCompat.getInstance(this).startActivityForProfile(
intent.getComponent(), user, intent.getSourceBounds(), optsBundle);
}
getUserEventDispatcher().logAppLaunch(v, intent);
return true;
} catch (ActivityNotFoundException|SecurityException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Unable to launch. tag=" + item + " intent=" + intent, e);
}
return false;
}
複製程式碼
2.5 Activity.startActivity
// framework/base/core/java/android/app/Activity.java
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options); // options 表示 Launcher 啟動 Activity 時的動畫效果
} else {
startActivityForResult(intent, -1);
}
}
複製程式碼
2.6 Activity.startActivityForResult
// framework/base/core/java/android/app/Activity.java
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
// mParent 代表目前 Launcher Activity 的狀態
if (mParent == null) { // 第一次啟動 Activity,走此條分支
options = transferSpringboardActivityOptions(options);
// 執行 mInstrumentation.execStartActivity() 方法
Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(this,
mMainThread.getApplicationThread(), mToken,
this, intent, requestCode, options);
... ...
} else {
if (options != null) {
// 最終會呼叫 mInstrumentation.execStartActivity() 方法
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
複製程式碼
mMainThread
是 Activity 類的 成員變數
,它的型別是 ActivityThread
,它代表的是應用程式的 主執行緒
。
// frameworks/base/core/java/android/app/ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler {
... ...
final ApplicationThread mAppThread = new ApplicationThread();
... ...
private class ApplicationThread extends IApplicationThread.Stub {...}
... ...
public ApplicationThread getApplicationThread()
{
return mAppThread;
}
... ...
}
複製程式碼
mMainThread.getApplicationThread()
獲得的是 ApplicationThread
內部成員變數,它是一個 Binder
物件。這個物件是幹嘛用的,我們後面會講解到。
2.7 Instrumentation.execStartActivity
Instrumentation
是 Android 系統中啟動 Activity
的一個實際操作類,它用來監控應用程式和系統的互動。
// 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);
// 通過 ActivityManager.getService() 方法可以獲得 ActivityManagerService 提供的服務
int result = ActivityManager.getService().startActivity(whoThread,
who.getBasePackageName(), 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;
}
複製程式碼
我們研究下 ActivityManager.getService()
方法:
// frameworks/base/core/java/android/app/ActivityManager.java
public static IActivityManager getService() {
return IActivityManagerSingleton.get(); // 獲取 IActivityManager 單例
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public class ActivityManagerService extends IActivityManager.Stub
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
複製程式碼
我們發現 ActivityManagerService
與 ActivityManger
的 Binder 通訊採用了 AIDL
的方式。
ActivityManager.getService().startActivity
方法實際上呼叫到了 ActivityManagerService
的 startActivity()
方法。
如果對於 AIDL 不瞭解,你可以檢視 【 Android '核心機制' 】篇 -- 無處不在的 "AIDL" 一文。
2.8 ActivityManagerService.startActivity
下面看看 ActivityManagerService
的 startActivity
方法:
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
// 調轉到 startActivityAsUser 方法
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
複製程式碼
2.9 ActivityManagerService.startActivityAsUser
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
// Android P 新增,這邊的流程與以前的就完全不一樣了,但最終調取的方法還是一樣的,細心跟一下
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
// 繼續調 startActivityAsUser 方法
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
true /*validateIncomingUser*/);
}
public final 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("startActivity");
userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
// 在 Android P 之前呼叫的是 ActivityStartController.startActivityMayWait 方法
return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setMayWait(userId) // 設定了 mRequest.mayWait = true,後面會用到
.execute();
}
複製程式碼
2.10 ActivityStartController.obtainStarter
// frameworks/base/services/core/java/com/android/server/am/ActivityStartController.java
import com.android.server.am.ActivityStarter.Factory;
private final Factory mFactory;
ActivityStarter obtainStarter(Intent intent, String reason) {
// obtain()、setIntent()、setReason() 分別幹了什麼,下面一一說明
return mFactory.obtain().setIntent(intent).setReason(reason);
}
複製程式碼
這邊用到了工廠模式,我們跟一下具體的處理流程。
2.10.1 DefaultFactory.obtain
// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
interface Factory {
void setController(ActivityStartController controller);
ActivityStarter obtain();
void recycle(ActivityStarter starter);
}
// DefaultFactory 為實現類
static class DefaultFactory implements Factory {
... ...
@Override
public ActivityStarter obtain() {
ActivityStarter starter = mStarterPool.acquire();
// obtain() 方法最終返回的是 ActivityStarter 的例項
if (starter == null) {
starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
}
return starter;
}
... ...
}
複製程式碼
2.10.2 ActivityStarter.setIntent
// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
ActivityStarter setIntent(Intent intent) {
mRequest.intent = intent; // 為 mRequest 賦值
return this;
}
複製程式碼
2.10.3 ActivityStarter.setReason
// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
ActivityStarter setReason(String reason) {
mRequest.reason = reason; // 為 mRequest 賦值
return this;
}
複製程式碼
mActivityStartController.obtainStarter()
方法最終獲得一個包含所有啟動資訊的 ActivityStarter
物件,然後作了各種賦值處理,最後執行 execute
方法。
2.11 ActivityStarter.execute
// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
// 上面執行了 setMayWait(userId) 方法
ActivityStarter setMayWait(int userId) {
mRequest.mayWait = true;
mRequest.userId = userId;
return this;
}
int execute() {
try {
if (mRequest.mayWait) { // setMayWait() 方法中置為 true
return startActivityMayWait(mRequest.caller, mRequest.callingUid,
mRequest.callingPackage, 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);
} 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);
}
} finally {
onExecutionComplete();
}
}
複製程式碼
繞了一圈還,最終還是走到了 startActivityMayWait()
方法!
2.12 流程小結
2.13 ActivityStarter.startActivityMayWait
// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
private int startActivityMayWait(IApplicationThread caller, int callingUid,
String callingPackage, 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) {
// Refuse possible leaked file descriptors
if (intent != null && intent.hasFileDescriptors()) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}
mSupervisor.getActivityMetricsLogger().notifyActivityLaunching();
boolean componentSpecified = intent.getComponent() != null;
final int realCallingPid = Binder.getCallingPid();
final int realCallingUid = Binder.getCallingUid();
... ...
// 解析 Intent 的資料
ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
0 /* matchFlags */,
computeResolveFilterUid(
callingUid, realCallingUid, mRequest.filterCallingUid));
... ...
// 收集 intent 中的相關資訊
ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
synchronized (mService) {
... ...
// 用於記錄 Activity 的資料
final ActivityRecord[] outRecord = new ActivityRecord[1];
// 啟動 Activity
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);
Binder.restoreCallingIdentity(origId);
... ...
mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outRecord[0]);
return res;
}
}
複製程式碼
2.14 ActivityStarter.startActivity -01
// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
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) {
... ...
// 跳轉 startActivity
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);
... ...
return getExternalResult(mLastStartActivityResult);
}
複製程式碼
2.15 ActivityStarter.startActivity -02
// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
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) {
... ...
// 跳轉 startActivity
return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true /* doResume */, checkedOptions, inTask, outActivity);
}
複製程式碼
2.16 ActivityStarter.startActivity -03
// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
int result = START_CANCELED;
try {
// 暫停佈局
mService.mWindowManager.deferSurfaceLayout();
// 呼叫 startActivityUnchecked 方法
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity);
} finally {
final ActivityStack stack = mStartActivity.getStack();
if (!ActivityManager.isStartResultSuccessful(result) && stack != null) {
stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
null /* intentResultData */, "startActivity", true /* oomAdj */);
}
// 繼續佈局
mService.mWindowManager.continueSurfaceLayout();
}
postStartActivityProcessing(r, result, mTargetStack);
return result;
}
複製程式碼
呼叫了 3 次 startActivity()
,最終執行了 startActivityUnchecked()
方法,這個方法裡會根據 啟動標誌位
和 Activity 啟動模式
來決定如何啟動一個 Activity。
2.17 ActivityStarter.startActivityUnchecked
// frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
// 初始化啟動 Activity 的各種配置,會先重置再重新配置,其中包括 ActivityRecord、Intent 等
setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
voiceInteractor);
// 計算出啟動的 FLAG,並將計算的值賦值給 mLaunchFlags
computeLaunchingTaskFlags();
computeSourceStack();
// 將 mLaunchFlags 設定給 Intent,達到設定 Activity 的啟動方式的目的
mIntent.setFlags(mLaunchFlags);
// 獲取是否有可以複用的 activity
ActivityRecord reusedActivity = getReusableIntentActivity();
... ...
// 可複用 Activity 不為空
if (reusedActivity != null) {
... ...
}
... ...
mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
mOptions);
if (mDoResume) {
final ActivityRecord topTaskActivity =
mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isFocusable()
|| (topTaskActivity != null && topTaskActivity.mTaskOverlay
&& mStartActivity != topTaskActivity)) {
... ...
} else {
if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
mTargetStack.moveToFront("startActivityUnchecked");
}
// 呼叫 resumeFocusedStackTopActivityLocked() 方法
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
mOptions);
}
} else if (mStartActivity != null) {
mSupervisor.mRecentTasks.add(mStartActivity.getTask());
}
... ...
return START_SUCCESS;
}
複製程式碼
2.18 ActivityStackSupervisor.resumeFocusedStackTopActivityLocked
// frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (!readyToResume()) {
return false;
}
if (targetStack != null && isFocusedStack(targetStack)) {
// 呼叫 resumeTopActivityUncheckedLocked 方法
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
if (r == null || !r.isState(RESUMED)) {
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
} else if (r.isState(RESUMED)) {
mFocusedStack.executeAppTransition(targetOptions);
}
return false;
}
複製程式碼
2.19 ActivityStack.resumeTopActivityUncheckedLocked
// frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mStackSupervisor.inResumeTopActivity) {
// Don't even start recursing.
return false;
}
boolean result = false;
try {
// Protect against recursion.
mStackSupervisor.inResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options); // 關鍵方法
final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
if (next == null || !next.canTurnScreenOn()) {
checkReadyForSleep();
}
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
return result;
}
複製程式碼
2.20 ActivityStack.resumeTopActivityInnerLocked
// frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
if (!mService.mBooting && !mService.mBooted) {
// Not ready yet!
return false;
}
... ...
boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
if (mResumedActivity != null) {
if (DEBUG_STATES) Slog.d(TAG_STATES,
"resumeTopActivityLocked: Pausing " + mResumedActivity);
// 先執行 startPausingLocked() 方法
pausing |= startPausingLocked(userLeaving, false, next, false);
}
... ...
ActivityStack lastStack = mStackSupervisor.getLastStack();
if (next.app != null && next.app.thread != null) {
... ...
synchronized(mWindowManager.getWindowManagerLock()) {
... ...
try {
... ...
} catch (Exception e) {
... ...
// 執行 startSpecificActivityLocked() 方法
mStackSupervisor.startSpecificActivityLocked(next, true, false);
return true;
}
}
try {
next.completeResumeLocked();
} catch (Exception e) {
requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
"resume-exception", true);
if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
return true;
}
} else {
... ...
// 執行 startSpecificActivityLocked() 方法
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
return true;
}
複製程式碼
在 resumeTopActivityInnerLocked
方法中會去判斷是否有 Activity 處於 Resume
狀態。
如果有的話會先讓這個 Activity 執行 Pausing
過程(其實也就是本案例中 Launcher
的 onPause
流程),然後再執行 startSpecificActivityLocked
方法來啟動需要啟動的 Activity。
2.21 ActivityStack.startPausingLocked
我們先分析 startPausingLocked()
原始碼,應用的啟動流程 startSpecificActivityLocked()
放在第三節討論!
// frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
// 棧頂 Activity 執行 onPause 方法退出
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
ActivityRecord resuming, boolean pauseImmediately) {
... ...
ActivityRecord prev = mResumedActivity;
... ...
// 把 prev 賦值給 mPausingActivity,這個值在 Activity 啟動過程中會用到,
// 這邊其實就是將 mResumedActivity 賦值給 mPausingActivity,就是我們的 Launcher。
mPausingActivity = prev;
... ...
if (prev.app != null && prev.app.thread != null) {
try {
EventLogTags.writeAmPauseActivity(prev.userId, System.identityHashCode(prev),
prev.shortComponentName, "userLeaving=" + userLeaving);
mService.updateUsageStats(prev, false);
/*
* Android P 在這裡引入了 ClientLifecycleManager 和 ClientTransactionHandler 來輔助
* 管理 Activity 生命週期,它會傳送 EXECUTE_TRANSACTION 訊息
* 到 ActivityThread.H 裡面繼續處理。
* 通過 ClientLifecycleManager 的 scheduleTransaction 方法把 PauseActivityItem
* 事件加入到執行計劃中,開始棧頂的 pausing 過程。
*/
mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
PauseActivityItem.obtain(prev.finishing, userLeaving,
prev.configChangeFlags, pauseImmediately));
} catch (Exception e) {
// Ignore exception, if process died other code will cleanup.
Slog.w(TAG, "Exception thrown during pause", e);
mPausingActivity = null;
mLastPausedActivity = null;
mLastNoHistoryActivity = null;
}
} else {
mPausingActivity = null;
mLastPausedActivity = null;
mLastNoHistoryActivity = null;
}
... ...
}
複製程式碼
2.22 ClientLifecycleManager.scheduleTransaction
// frameworks/base/services/core/java/com/android/server/am/ClientLifecycleManager.java
class ClientLifecycleManager {
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {
transaction.recycle();
}
}
... ...
}
// frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
public class ClientTransaction implements Parcelable, ObjectPoolItem {
/** Target client. */
private IApplicationThread mClient;
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
}
複製程式碼
ClientTransaction.schedule
方法的 mClient
是一個 IApplicationThread
型別,ActivityThread 的內部類 ApplicationThread
派生這個介面類並實現了對應的方法。所以直接跳轉到 ApplicationThread
中的 scheduleTransaction
方法。
2.23 ActivityThread.scheduleTransaction
// frameworks/base/core/java/android/app/ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler {
private class ApplicationThread extends IApplicationThread.Stub {
... ...
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
}
}
複製程式碼
2.24 流程小結
2.25 ClientTransactionHandler.scheduleTransaction
ActivityThread 類中並沒有定義 scheduleTransaction
方法,所以呼叫的是他父類 ClientTransactionHandler
的 scheduleTransaction
方法。
// frameworks/base/core/java/android/app/ClientTransactionHandler.java
public abstract class ClientTransactionHandler {
abstract void sendMessage(int what, Object obj);
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
// 呼叫了 sendMessage 方法,這個方法是一個抽象方法,
// 它的實現是在 ClientTransactionHandler 派生類的 ActivityThread 中。
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
}
複製程式碼
2.26 ActivityThread.sendMessage
// frameworks/base/core/java/android/app/ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler {
private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
void sendMessage(int what, Object obj) {
sendMessage(what, obj, 0, 0, false);
}
private void sendMessage(int what, Object obj, int arg1) {
sendMessage(what, obj, arg1, 0, false);
}
private void sendMessage(int what, Object obj, int arg1, int arg2) {
sendMessage(what, obj, arg1, arg2, false);
}
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
// ActivityThread.sendMessage 方法會把訊息傳送給內部名字叫 H 的 Handler
mH.sendMessage(msg);
}
class H extends Handler {
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
// Handler H 的例項接收到 EXECUTE_TRANSACTION 訊息後呼叫
// TransactionExecutor.execute 方法切換 Activity 狀態。
mTransactionExecutor.execute(transaction);
if (isSystem()) {
transaction.recycle();
}
// TODO(lifecycler): Recycle locally scheduled transactions.
break;
}
}
}
}
複製程式碼
2.27 TransactionExecutor.execute
// frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
public class TransactionExecutor {
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
executeCallbacks(transaction); // 重要方法 1
executeLifecycleState(transaction); // 重要方法 2
mPendingActions.clear();
log("End resolving transaction");
}
// 重要方法 1
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
if (callbacks == null) {
// No callbacks to execute, return early.
return;
}
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
... ...
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
... ...
}
}
// 重要方法 2
/** Transition to the final state if requested by the transaction. */
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
... ...
// 執行當前生命週期狀態之前的狀態
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
// Execute the final transition with proper parameters.
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
}
複製程式碼
前面在 ActivityStack.startPausingLocked
方法裡面 scheduleTransaction
傳遞的是 PauseActivityItem
物件,所以 executeLifecycleState
方法裡呼叫的 execute
方法其實是 PauseActivityItem.execute
方法。
2.28 PauseActivityItem.execute
// frameworks/base/core/java/android/app/servertransaction/PauseActivityItem.java
public class PauseActivityItem extends ActivityLifecycleItem {
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
// 跳轉到 ActivityThread.handlePauseActivity 方法
client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
"PAUSE_ACTIVITY_ITEM");
}
}
複製程式碼
2.29 ActivityThread.handlePauseActivity
// frameworks/base/core/java/android/app/ActivityThread.java
@Override
public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
int configChanges, PendingTransactionActions pendingActions, String reason) {
ActivityClientRecord r = mActivities.get(token);
if (r != null) {
... ...
performPauseActivity(r, finished, reason, pendingActions);
... ...
}
}
複製程式碼
2.30 ActivityThread.performPauseActivity
// frameworks/base/core/java/android/app/ActivityThread.java
final Bundle performPauseActivity(IBinder token, boolean finished, String reason,
PendingTransactionActions pendingActions) {
ActivityClientRecord r = mActivities.get(token);
return r != null ? performPauseActivity(r, finished, reason, pendingActions) : null;
}
private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
PendingTransactionActions pendingActions) {
... ...
performPauseActivityIfNeeded(r, reason);
... ...
return shouldSaveState ? r.state : null;
}
複製程式碼
2.31 ActivityThread.performPauseActivityIfNeeded
// frameworks/base/core/java/android/app/ActivityThread.java
private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
if (r.paused) {
// You are already paused silly...
return;
}
try {
r.activity.mCalled = false;
mInstrumentation.callActivityOnPause(r.activity); // 關鍵方法
if (!r.activity.mCalled) {
throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
+ " did not call through to super.onPause()");
}
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException("Unable to pause activity "
+ safeToComponentShortString(r.intent) + ": " + e.toString(), e);
}
}
r.setState(ON_PAUSE);
}
複製程式碼
2.32 Instrumentation.callActivityOnPause
// frameworks/base/core/java/android/app/Instrumentation.java
public void callActivityOnPause(Activity activity) {
activity.performPause(); // 直接呼叫 Activity.performPause 方法
}
複製程式碼
2.33 Activity.performPause
// frameworks/base/core/java/android/app/Activity.java
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory2,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks2,
Window.OnWindowDismissedCallback, WindowControllerCallback,
AutofillManager.AutofillClient {
final void performPause() {
... ...
onPause();
... ...
}
}
複製程式碼
2.34 流程小結
至此,Launcher 的 onPause() 流程分析結束!同時,我們需要明白一點:在啟動一個 Activity 的時候最先被執行的是棧頂的 Activity 的 onPause 方法。
三、啟動程式
Launcher 的 onPause()
流程分析完,接下來我們看看新程式的啟動流程:startSpecificActivityLocked()
方法。在這個方法中會去根據 程式
和 執行緒
是否存在判斷 App 是否已經啟動。
3.1 ActivityStackSupervisor.startSpecificActivityLocked
// frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
// Is this activity's application already running?
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
getLaunchTimeTracker().setLaunchTime(r);
// 如果 app 存在,並且已經啟動
if (app != null && app.thread != null) {
try {
if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
|| !"android".equals(r.info.packageName)) {
app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
mService.mProcessStats);
}
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
+ r.intent.getComponent().flattenToShortString(), e);
}
}
// 啟動新的程式,mService 為 ActivityManagerService
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
複製程式碼
如果已經啟動,就會呼叫 ActivityManagerService.realStartActivityLocked
方法繼續處理。
如果沒有啟動,則會呼叫 ActivityManagerService.startProcessLocked
方法建立新的程式處理。
3.2 ActivityManagerService.startProcessLocked -01
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
final ProcessRecord startProcessLocked(String processName,
ApplicationInfo info, boolean knownToBeDead, int intentFlags,
String hostingType, ComponentName hostingName, boolean allowWhileBooting,
boolean isolated, boolean keepIfLarge) {
return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
null /* crashHandler */);
}
複製程式碼
3.3 ActivityManagerService.startProcessLocked -02
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
... ...
final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);
}
複製程式碼
3.3 ActivityManagerService.startProcessLocked -03
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
private final boolean startProcessLocked(ProcessRecord app,
String hostingType, String hostingNameStr, String abiOverride) {
return startProcessLocked(app, hostingType, hostingNameStr,
false /* disableHiddenApiChecks */, abiOverride);
}
複製程式碼
3.4 ActivityManagerService.startProcessLocked -04
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
private final boolean startProcessLocked(ProcessRecord app, String hostingType,
String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
try {
... ...
return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
startTime);
} catch (RuntimeException e) {
forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), false,
false, true, false, false, UserHandle.getUserId(app.userId), "start failure");
return false;
}
}
複製程式碼
3.5 ActivityManagerService.startProcessLocked -05
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
private boolean startProcessLocked(String hostingType, String hostingNameStr, String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {
... ...
final ProcessStartResult startResult = startProcess(hostingType, entryPoint, app,
uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet,
invokeWith, startTime);
... ...
}
複製程式碼
3.6 ActivityManagerService.startProcess
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
private ProcessStartResult startProcess(String hostingType, 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);
checkTime(startTime, "startProcess: asking zygote to start proc");
final ProcessStartResult startResult;
if (hostingType.equals("webview_service")) {
startResult = startWebView(entryPoint,
app.processName, uid, uid, gids, runtimeFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, null,
new String[] {PROC_START_SEQ_IDENT + app.startSeq});
} else {
// 執行 Process.start 方法
startResult = Process.start(entryPoint,
app.processName, uid, uid, gids, runtimeFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, invokeWith,
new String[] {PROC_START_SEQ_IDENT + app.startSeq});
}
checkTime(startTime, "startProcess: returned from zygote!");
return startResult;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
}
複製程式碼
到這裡,我們就明白了:ActivityManagerService.startProcessLocked
方法經過多次跳轉最終會通過 Process.start
方法來為應用建立程式。
程式的建立流程和原始碼分析,這邊我們就不再討論了!在 【 Android '程式執行緒' 】篇 -- 聊聊 "程式" 如何 "建立" 一文中,我們作了詳細的分析!
四、Activity 程式
我們在程式建立的博文中,討論過原始碼最後會執行到 ActivityThread.main
方法,執行主執行緒的初始化工作。
4.1 初始化主執行緒
// frameworks/base/core/java/android/app/ActivityThread.java
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
EventLogger.setReporter(new EventLoggingReporter());
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper(); // 建立主執行緒 looper
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(); // 初始化 ActivityThread
thread.attach(false, startSeq); // attach 到系統程式
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop(); // 主執行緒啟動,進入迴圈狀態
throw new RuntimeException("Main thread loop unexpectedly exited");
}
複製程式碼
4.2 啟動 Activity
// frameworks/base/core/java/android/app/ActivityThread.java
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
... ...
final IActivityManager mgr = ActivityManager.getService();
try {
// 通過 ActivityManagerService 為這個應用繫結一個 Application
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
// 新增一個垃圾回收觀察者,每當系統觸發垃圾回收的時候就會在 run 方法裡面
// 去計算應用使用了多少記憶體,如果超過總量的四分之三就會嘗試釋放記憶體
BinderInternal.addGcWatcher(new Runnable() {
@Override public void run() {
if (!mSomeActivitiesChanged) {
return;
}
Runtime runtime = Runtime.getRuntime();
long dalvikMax = runtime.maxMemory();
long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
if (dalvikUsed > ((3*dalvikMax)/4)) {
if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
+ " total=" + (runtime.totalMemory()/1024)
+ " used=" + (dalvikUsed/1024));
mSomeActivitiesChanged = false;
try {
mgr.releaseSomeActivities(mAppThread);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
});
} else {
... ...
}
... ...
// 為根 View 新增 config 回撥接收 config 變化相關的資訊
ViewRootImpl.addConfigCallback(configChangedCallback);
}
複製程式碼
4.2.1 ActivityManagerService.attachApplication
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
@Override
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);
Binder.restoreCallingIdentity(origId);
}
}
複製程式碼
4.2.2 ActivityManagerService.attachApplicationLocked
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {
... ...
// See if the top visible activity is waiting to run in this process...
if (normalMode) {
try {
if (mStackSupervisor.attachApplicationLocked(app)) {
didSomething = true;
}
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
... ...
return true;
}
複製程式碼
4.3 ActivityStackSupervisor.attachApplicationLocked
// frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
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 {
// 執行 realStartActivityLocked 方法
if (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;
}
}
}
}
}
if (!didSomething) {
ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
}
return didSomething;
}
複製程式碼
4.4 ActivityStackSupervisor.realStartActivityLocked
realStartActivityLocked
就是應用程式已經啟動的情況下去啟動 Activity
所呼叫的方法。
// frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
try {
... ...
try {
... ...
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
// 為 ClientTransaction 物件新增 LaunchActivityItem 的 callback
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo));
final ActivityLifecycleItem lifecycleItem;
// 設定當前的生命週期狀態
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// 呼叫 ClientLifecycleManager.scheduleTransaction 方法
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
... ...
}
複製程式碼
呼叫 ClientLifecycleManager.scheduleTransaction
方法之後具體是如何執行的前面已經分析過了,這裡就不再分析了。
我們這裡看一下執行 callback
後跳轉到 LaunchActivityItem.execute
方法。
4.5 LaunchActivityItem.execute
// frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java
@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);
// 呼叫 ActivityThread.handleLaunchActivity 方法
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
複製程式碼
4.6 ActivityThread.handleLaunchActivity
// frameworks/base/core/java/android/app/ActivityThread.java
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
... ...
final Activity a = performLaunchActivity(r, customIntent);
... ...
}
複製程式碼
4.7 ActivityThread.performLaunchActivity
// frameworks/base/core/java/android/app/ActivityThread.java
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
// 初始化 ComponentName
ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
// 初始化 ContextImpl 和 Activity
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
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) {
... ...
}
try {
// 初始化Application
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (r.overrideConfig != null) {
config.updateFrom(r.overrideConfig);
}
Window window = null;
if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
window = r.mPendingRemoveWindow;
r.mPendingRemoveWindow = null;
r.mPendingRemoveWindowManager = null;
}
appContext.setOuterContext(activity);
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);
if (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstances = null;
checkAndBlockForNetworkAccess();
activity.mStartedActivity = false;
// 設定 Activity 的 Theme
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
activity.mCalled = false;
// 呼叫 Instrumentation.callActivityOnCreate 方法
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
if (!activity.mCalled) {
... ...
r.activity = activity;
}
r.setState(ON_CREATE);
mActivities.put(r.token, r);
} catch (SuperNotCalledException e) {
... ...
}
return activity;
}
複製程式碼
4.8 Instrumentation.callActivityOnCreate
// 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);
}
複製程式碼
4.9 Activity.performCreate
// frameworks/base/core/java/android/app/Activity.java
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
... ...
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
... ...
}
複製程式碼
至此 executeCallbacks()
執行完畢,開始執行 executeLifecycleState
方法,會先執行 cycleToPath
方法。
4.10 TransactionExecutor.cycleToPath
// frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
private void cycleToPath(ActivityClientRecord r, int finish,
boolean excludeLastState) {
final int start = r.getLifecycleState();
log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
performLifecycleSequence(r, path);
}
複製程式碼
4.11 TransactionExecutor.performLifecycleSequence
// frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
final int size = path.size();
for (int i = 0, state; i < size; i++) {
state = path.get(i);
log("Transitioning to state: " + state);
// 生命週期狀態是從 ON_CREATE 狀態到 ON_RESUME 狀態,中間有一個 ON_START 狀態,
// 所以會執行 ActivityThread.handleStartActivity 方法。
switch (state) {
case ON_CREATE:
mTransactionHandler.handleLaunchActivity(r, mPendingActions,
null /* customIntent */);
break;
case ON_START:
mTransactionHandler.handleStartActivity(r, mPendingActions);
break;
case ON_RESUME:
mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
break;
case ON_PAUSE:
mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
false /* userLeaving */, 0 /* configChanges */, mPendingActions,
"LIFECYCLER_PAUSE_ACTIVITY");
break;
case ON_STOP:
mTransactionHandler.handleStopActivity(r.token, false /* show */,
0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
"LIFECYCLER_STOP_ACTIVITY");
break;
case ON_DESTROY:
mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
0 /* configChanges */, false /* getNonConfigInstance */,
"performLifecycleSequence. cycling to:" + path.get(size - 1));
break;
case ON_RESTART:
mTransactionHandler.performRestartActivity(r.token, false /* start */);
break;
default:
throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
}
}
}
複製程式碼
4.12 ActivityThread.handleStartActivity
// frameworks/base/core/java/android/app/ActivityThread.java
public void handleStartActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions) {
... ...
// Start
activity.performStart("handleStartActivity");
r.setState(ON_START);
... ...
}
複製程式碼
4.13 Activity.performStart
// frameworks/base/core/java/android/app/Activity.java
final void performStart(String reason) {
... ...
mInstrumentation.callActivityOnStart(this);
... ...
}
複製程式碼
4.14 Instrumentation.callActivityOnStart
// frameworks/base/core/java/android/app/Instrumentation.java
public void callActivityOnStart(Activity activity) {
// 經過多次跳轉最後會呼叫 Activity.onStart 方法
activity.onStart();
}
複製程式碼
執行完畢 cycleToPath
,開始執行 ResumeActivityItem.execute
方法。
4.15 ResumeActivityItem.execute
// frameworks/base/core/java/android/app/servertransaction/ResumeActivityItem.java
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
"RESUME_ACTIVITY");
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
複製程式碼
4.16 ActivityThread.handleResumeActivity
// frameworks/base/core/java/android/app/ActivityThread.java
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason) {
... ...
// TODO Push resumeArgs into the activity for consideration
final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
if (r == null) {
// We didn't actually resume the activity, so skipping any follow-up actions.
return;
}
... ...
if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
// 這邊的方法我們在最後會說明,其中涉及到 onStop() 方法
Looper.myQueue().addIdleHandler(new Idler());
}
複製程式碼
4.17 ActivityThread.performResumeActivity
// frameworks/base/core/java/android/app/ActivityThread.java
public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
String reason) {
... ...
try {
r.activity.onStateNotSaved();
r.activity.mFragments.noteStateNotSaved();
checkAndBlockForNetworkAccess();
if (r.pendingIntents != null) {
deliverNewIntents(r, r.pendingIntents);
r.pendingIntents = null;
}
if (r.pendingResults != null) {
deliverResults(r, r.pendingResults, reason);
r.pendingResults = null;
}
// 執行 performResume 方法
r.activity.performResume(r.startsNotResumed, reason);
r.state = null;
r.persistentState = null;
r.setState(ON_RESUME);
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException("Unable to resume activity "
+ r.intent.getComponent().toShortString() + ": " + e.toString(), e);
}
}
return r;
}
複製程式碼
4.18 Activity.performResume
// frameworks/base/core/java/android/app/Activity.java
final void performResume(boolean followedByPause, String reason) {
performRestart(true /* start */, reason);
... ...
// mResumed is set by the instrumentation
mInstrumentation.callActivityOnResume(this);
... ...
}
複製程式碼
4.19 Instrumentation.callActivityOnResume
// frameworks/base/core/java/android/app/Instrumentation.java
public void callActivityOnResume(Activity activity) {
activity.mResumed = true;
// 最終呼叫到 Activity.onResume 方法
activity.onResume();
... ...
}
複製程式碼
至此,Activity
啟動完畢。
五、棧頂活動 onStop
我們在討論 ActivityThread.handleResumeActivity
原始碼的時候,最後一行程式碼還未討論。
// frameworks/base/core/java/android/app/ActivityThread.java
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason) {
... ...
final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
... ...
// 當 MessageQueue 空閒的時候就會執行這個 Handler,即執行完當前 Activity 的 onResume() 方法後執行
Looper.myQueue().addIdleHandler(new Idler());
}
複製程式碼
為什麼要單獨討論這行程式碼,因為上面分析了棧頂 Activity
的 onPause()
、新 Activity
的 onCreate()、onStart()、onResume()
,但缺失一個棧頂 Activity
的 onStop()
生命週期,此方法就是在這行程式碼中處理的。
5.1 Idler
// frameworks/base/core/java/android/app/ActivityThread.java
private class Idler implements MessageQueue.IdleHandler {
@Override
public final boolean queueIdle() {
... ...
if (a != null) {
mNewActivities = null;
IActivityManager am = ActivityManager.getService();
ActivityClientRecord prev;
do {
if (a.activity != null && !a.activity.mFinished) {
try {
// 呼叫 ActivityManagerService.activityIdle 方法
am.activityIdle(a.token, a.createdConfig, stopProfiling);
a.createdConfig = null;
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
prev = a;
a = a.nextIdle;
prev.nextIdle = null;
} while (a != null);
}
... ...
return false;
}
}
複製程式碼
5.2 ActivityManagerService.activityIdle
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
final long origId = Binder.clearCallingIdentity();
synchronized (this) {
ActivityStack stack = ActivityRecord.getStackLocked(token);
if (stack != null) {
// 呼叫 ActivityStackSupervisor.activityIdleInternalLocked 方法
ActivityRecord r =
mStackSupervisor.activityIdleInternalLocked(token, false /* fromTimeout */,
false /* processPausingActivities */, config);
if (stopProfiling) {
if ((mProfileProc == r.app) && mProfilerInfo != null) {
clearProfilerLocked();
}
}
}
}
Binder.restoreCallingIdentity(origId);
}
複製程式碼
5.3 ActivityStackSupervisor.activityIdleInternalLocked
// frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
boolean processPausingActivities, Configuration config) {
for (int i = 0; i < NS; i++) {
r = stops.get(i);
final ActivityStack stack = r.getStack();
if (stack != null) {
if (r.finishing) {
stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false,
"activityIdleInternalLocked");
} else {
stack.stopActivityLocked(r);
}
}
}
... ...
return r;
}
複製程式碼
5.4 ActivityStack.stopActivityLocked
// frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
final void stopActivityLocked(ActivityRecord r) {
... ...
if (r.app != null && r.app.thread != null) {
adjustFocusedActivityStack(r, "stopActivity");
r.resumeKeyDispatchingLocked();
try {
... ...
mService.getLifecycleManager().scheduleTransaction(r.app.thread, r.appToken,
StopActivityItem.obtain(r.visible, r.configChangeFlags));
if (shouldSleepOrShutDownActivities()) {
r.setSleeping(true);
}
Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
} catch (Exception e) {
... ...
}
}
}
複製程式碼
又見到了 ClientLifecycleManager.scheduleTransaction
方法,前面已經分析過多次,會去執行 StopActivityItem.execute
方法,然後經過多次跳轉,最終執行了 Activity.onStop
方法。
5.5 StopActivityItem.execute
// frameworks/base/core/java/android/app/servertransaction/StopActivityItem.java
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStop");
client.handleStopActivity(token, mShowWindow, mConfigChanges, pendingActions,
true /* finalStateRequest */, "STOP_ACTIVITY_ITEM");
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
複製程式碼
5.6 ActivityThread.handleStopActivity
// frameworks/base/core/java/android/app/ActivityThread.java
@Override
public void handleStopActivity(IBinder token, boolean show, int configChanges,
PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) {
... ...
performStopActivityInner(r, stopInfo, show, true /* saveState */, finalStateRequest,
reason);
... ...
}
複製程式碼
5.7 ActivityThread.performStopActivityInner
// frameworks/base/core/java/android/app/ActivityThread.java
private void performStopActivityInner(ActivityClientRecord r, StopInfo info, boolean keepShown,
boolean saveState, boolean finalStateRequest, String reason) {
if (r != null) {
... ...
if (!keepShown) {
callActivityOnStop(r, saveState, reason);
}
}
}
複製程式碼
5.8 ActivityThread.callActivityOnStop
// frameworks/base/core/java/android/app/ActivityThread.java
private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
... ...
try {
r.activity.performStop(false /*preserveWindow*/, reason);
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
... ...
}
... ...
}
複製程式碼
5.9 Activity.performStop
// frameworks/base/core/java/android/app/Activity.java
final void performStop(boolean preserveWindow, String reason) {
... ...
if (!mStopped) {
... ...
mInstrumentation.callActivityOnStop(this);
}
}
複製程式碼
5.10 Instrumentation.callActivityOnStop
// frameworks/base/core/java/android/app/Instrumentation.java
public void callActivityOnStop(Activity activity) {
activity.onStop();
}
複製程式碼