編輯:關於 Android 程式設計
Android 官方 guide 中有這樣一段描述:
By default, every application runs in its own Linux process. Android starts the process when any of the application's components need to be executed, then shuts down the process when it's no longer needed or when the system must recover memory for other applications.
也就是說,每個 Android 應用默認運行在獨立的 Linux 進程中。系統在該應用的某個組件需要執行時啟動進程,並在沒有組件運行、或需要為其他應用回收內存時結束它。因此,當我們要啟動四大組件之一,而宿主進程尚未啟動時,系統會先把進程拉起來。
本文以 Activity 的啟動過程為切入點,梳理應用進程的啟動流程。
上一篇文章介紹過:SystemServer 完成各項系統服務啟動後,會調用 ActivityManagerService 的 systemReady(),Launcher 的啟動邏輯就在其中。Launcher 啟動時會向 PackageManagerService 查詢系統中所有已安裝應用的包名、圖標與名稱,填充到自己的 Adapter 中。於是我們點擊某個圖標時,就能根據它的包名和啟動 Activity 類名構造 Intent,調用 startActivity(Intent)。
事實上,啟動 Activity、Service、ContentProvider 或 BroadcastReceiver 都可能導致進程被拉起。系統會先判斷該組件所屬進程是否存在,不存在則先創建進程。
Launcher 的圖標點擊事件:
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = intentForPosition(position);
startActivity(intent);
}
關鍵在於:此刻應用進程還沒啟動,而 startActivity 卻成功打開了 Activity——說明它在啟動 Activity 之前,先把進程拉起來了。下面就以這個方法為入口跟蹤。
Activity 中的重載調用:
@Override
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
最終落到核心重載:
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
if (mParent == null) {
Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(mToken, mEmbeddedID, requestCode,
ar.getResultCode(), ar.getResultData());
}
...
} else {
mParent.startActivityFromChild(this, intent, requestCode, options);
}
}
這裡出現了 Instrumentation。它是 Android 應用端操作 Activity 的具體代理類(相對於 ActivityManagerService 這個服務端而言),Activity 生命周期的實際調度都經由它完成。
public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token,
Activity target, Intent intent, int requestCode, Bundle options) {
...
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
checkStartActivityResult(result, intent);
...
}
ActivityManagerNative 繼承自 Binder 接口,是 Binder 機制的客戶端;而 ActivityManagerService 繼承自 ActivityManagerNative,是服務端。所以上面這行本質是一次跨進程通訊——把參數傳給 AMS 並執行它的 startActivity。
// ActivityManagerService
@Override
public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, options,
UserHandle.getCallingUserId());
}
@Override
public final int startActivityAsUser(..., int userId) {
enforceNotIsolatedCaller("startActivity");
userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
false, ALLOW_FULL_ONLY, "startActivity", null);
return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, options, false, userId, null, null);
}
接下來是一串層層調用,把 Activity 一路推向啟動:
// ActivityStackSupervisor
final int startActivityMayWait(...) {
int res = startActivityLocked(caller, intent, resolvedType, aInfo, ...);
return res;
}
final int startActivityLocked(...) {
err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, true, options, inTask);
...
}
final int startActivityUncheckedLocked(...) {
targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
...
}
// ActivityStack
final void startActivityLocked(ActivityRecord r, boolean newTask, ...) {
...
if (doResume) {
mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
}
}
// ActivityStackSupervisor
boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target, ...) {
stack.resumeTopActivityLocked(null);
...
}
final boolean resumeTopActivityLocked(ActivityRecord prev) {
return resumeTopActivityLocked(prev, null);
}
final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
result = resumeTopActivityInnerLocked(prev, options);
...
}
final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
mStackSupervisor.startSpecificActivityLocked(next, true, true);
...
}
// ActivityStackSupervisor
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
...
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
// ActivityManagerService
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, 0, keepIfLarge, null, null, null, null, null);
}
final ProcessRecord startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr,
String abiOverride, String entryPoint, String[] entryPointArgs) {
...
startProcessLocked(app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);
...
}
// 最終通過 Process.start 請求 zygote
Process.ProcessStartResult startResult = Process.start(entryPoint, app.processName,
uid, uid, gids, debugFlags, mountExternal, app.info.targetSdkVersion,
app.info.seinfo, requiredAbi, instructionSet, app.info.dataDir, entryPointArgs);
// android.os.Process
public static final ProcessStartResult start(final String processClass, final String niceName,
int uid, int gid, int[] gids, int debugFlags, int mountExternal,
int targetSdkVersion, String seInfo, String abi, String instructionSet,
String appDataDir, String[] zygoteArgs) {
try {
return startViaZygote(processClass, niceName, uid, gid, gids, debugFlags,
mountExternal, targetSdkVersion, seInfo, abi, instructionSet,
appDataDir, zygoteArgs);
} catch (ZygoteStartFailedEx ex) {
throw new RuntimeException("Starting VM process through Zygote failed", ex);
}
}
這裡的 processClass 就是待啟動進程的入口類,傳入的是:
"android.app.ActivityThread"
Process 啟動進程的 Native 層實現本文不做展開。要點是:這個方法讓 zygote fork 出新的進程,並執行 ActivityThread 的 main 方法——這也就是我們常說的「進程入口是 ActivityThread.main」的由來。
Android 圖片異步加載實作:用 LruCache 建構一級記憶體快取
為什麼一定要有快取 靠著敗敗圖縮放,我們已經能馴服單張大圖。但真實的 App 面對的不是一張大圖,而是滿版的高清多圖:資訊流、相簿、電商列表,動輒幾十張同時存在。若全部塞
RecyclerView 完全解析(二十八):從基本用法到進階動畫
一、前言 RecyclerView 問世多年,已成為 Android 開發中不可或缺的列表元件。相較於 ListView、GridView,它在資料綁定、Item Vie
為 Android APK 加殼防反編譯:原理、流程與程式碼
APK 天生容易被反編譯,想提高逆向門檻,加殼是常見的思路之一。以下把原理與實作流程完整梳理一遍。 一、什麼是加殼 加殼是在二進位程式裡植入一段程式碼,讓它在執行時優先
仿 QQ 空間中央加號底部選單的實作拆解
網路上搜得到的「仿 QQ 空間底部選單」範例不少,但實際跑起來往往問題一堆,版面裡還塞滿了各種來歷不明的魔法數字。與其硬改別人的程式,不如自己從原理還原一遍。以下是我重新