對於Android開發,幹上幾年後,都要進階,或者直接轉行了。若是你還在幹Android,想要進階 對Framework的瞭解是必不可少的過程,下面就開始進入今天的主題吧。java
咱們知道,對於任何程序語言而言,入口通常都是main函數。android
那Android的程序入口在哪呢? 他的main函數是怎麼啓動起來的呢?c++
可能熟悉Android的同窗,知道一個應用程序的入口在ActivityThread中,那有個問題,ActivityThread中的main函數是什麼時候被誰被調用的呢?程序員
將從本文中找到以上答案,若是已經熟悉了此過程的同窗,能夠在溫習一下。bash
Android 平臺的基礎是 Linux 內核。Android Runtime (ART/Dalvik) 依靠 Linux 內核來執行底層功能,例如線程和低層內存管理等。網絡
而在Android Runtime之上就是咱們常常接觸的Java API Framework層, 以下圖是Android的系統架構圖架構
今天的主題不是此架構圖的各個部分解釋,而是離應用層更近的Framework層啓動過程分析。app
若是咱們這裏拋開Android架構圖,那狹義的Framewrok主要包含那些內容呢?socket
按個人理解,能夠分爲三個部分 服務端,客戶端,和依賴Linux底層能力的驅動部分。ide
主要是ActivityManagerService(AMS), WindowManagerService(WMS),PackageM anerService(PMS)
還有用來處理觸摸消息的兩個類KeyInputQueue和InputDispatchThread,一個用來讀消息,一個用來分發消息.
主要包括ActivityThread,Activity,DecodeView及父類View,PhoneWindow,ViewRootImpl及內部類W等
主要是SurfaceFlingger(SF)和Binder驅動
系統中運行的第一個Dalvik虛擬機程序叫作zygote,該名稱的意義是「一個卵」,,由於接下來的全部 Dalvik虛擬機進程都是經過這個「卵」 孵化出來的。
zygote進程中包含兩個主要模塊,分別以下:
zygote進程對應的具體程序是app_rocess,該程序存在於system/bin目錄下,啓動該程序的指令是 在 init.rc中進行配置的。
Zygote 有️兩個優秀的特色
zygote孵化出的第一個Dalvik進程叫作SystemServer,SystemServer僅僅是該進程的別名,而該進程具體對應的程序依然是app_process,由於SystemServer是從app_process中孵化出來的。
SystemServer中建立了一個Socket客戶端,並有AmS負責管理該客戶端,以後全部的Dalvik進程都將經過該Socket客戶端間接被啓動。當須要啓動新的APK進程時,AmS中會經過該Socket客戶端向 zygote進程的Socket服務端發送一個啓動命令,然 後 zygote會孵化出新的進程。 上面提到的服務端,AMS,PMS,WMS等都是在SystemServer中啓動的.
操做系統的通常啓動流程,分爲三個步驟
Android 系統是基於Linux 內核Kernel,前面Linux bootloader這裏不作介紹,直接介紹操做系統內核初始化,在這個時候,它會加載init.rc文件.
在Android根目錄下面,能夠直接找到init.rc
generic_x86:/ # ls
acct bin cache config data dev init init.rc init.usb.rc lost+found mnt oem product sdcard sys ueventd.rc
adb_keys bugreports charger d default.prop etc init.environ.rc init.usb.configfs.rc init.zygote32.rc metadata odm proc sbin storage system vendor
複製代碼
打開init.rc
generic_x86:/ # cat init.rc
# ..... 省略其餘
# Now we can start zygote for devices with file based encryption
trigger zygote-start
# It is recommended to put unnecessary data/ initialization from post-fs-data
# to start-zygote in device's init.rc to unblock zygote start.
on zygote-start
# A/B update verifier that marks a successful boot.
exec_start update_verifier_nonencrypted
start netd
start zygote
start zygote_secondary
on property:vold.decrypt=trigger_restart_framework
stop surfaceflinger
# 啓動SF
start surfaceflinger
# ..... 省略其餘 media(媒體) network(網絡)等啓動
複製代碼
也就是在 init.rc時,啓動Android 內核。
Android 內核也是main方法開始,他的main方法在 frameworks/base/cmds/app_process/app_main.cpp下
int main(int argc, char* const argv[]) {
...
//初始化AndroidRuntime
AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
bool zygote = false;
bool startSystemServer = false;
bool application = false;
String8 niceName;
String8 className;
// 根據參數具體判斷啓動那個服務
++i; // Skip unused "parent dir" argument.
while (i < argc) {
const char* arg = argv[i++];
if (strcmp(arg, "--zygote") == 0) {
zygote = true;
niceName = ZYGOTE_NICE_NAME;
} else if (strcmp(arg, "--start-system-server") == 0) {
startSystemServer = true;
} else if (strcmp(arg, "--application") == 0) {
application = true;
} else if (strncmp(arg, "--nice-name=", 12) == 0) {
niceName.setTo(arg + 12);
} else if (strncmp(arg, "--", 2) != 0) {
className.setTo(arg);
break;
} else {
--i;
break;
}
}
if (!className.isEmpty()) {
args.add(application ? String8("application") : String8("tool"));
runtime.setClassNameAndArgs(className, argc - i, argv + i);
}else{
....
//啓動SystemServer
if (startSystemServer) {
args.add(String8("start-system-server"));
}
}
....
if (zygote) {
//啓動Zygote
runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
} else if (className) {
runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
} else {
fprintf(stderr, "Error: no class name or --zygote supplied.\n");
app_usage();
LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
}
}
複製代碼
在這個Main方法中,先初始化了AppRuntime,他的父類是AndroidRuntime。而後咱們看到了啓動了Java類ZygoteInit。
那c++代碼裏怎麼啓動Java類呢,咱們繼續看 start方法
void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
{
...
//啓動Java虛擬機
if (startVm(&mJavaVM, &env, zygote, primary_zygote) != 0) {
return;
}
...
//找到Java 裏面的Main方法
jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
"([Ljava/lang/String;)V");
if (startMeth == NULL) {
ALOGE("JavaVM unable to find main() in '%s'\n", className);
/* keep going */
} else {
//執行Main方法
env->CallStaticVoidMethod(startClass, startMeth, strArray);
}
....
}
複製代碼
能夠看到最後先建立了Java虛擬機,調用了Java的main方法,是否是感受有些熟悉感了。
上面介紹到,會啓動Java的ZygoteInit類,那他裏面幹了些什麼呢? 咱們來看一下關鍵代碼,仍是從Main方法開始
//ZygoteInit.java
public static void main(String argv[]) {
ZygoteServer zygoteServer = new ZygoteServer();
ZygoteHooks.startZygoteNoThreadCreation();
//建立socket
zygoteServer.createZygoteSocket(socketName);
Zygote.createBlastulaSocket(blastulaSocketName);
if (!enableLazyPreload) {
bootTimingsTraceLog.traceBegin("ZygotePreload");
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
SystemClock.uptimeMillis());
//預加載系統資源
preload(bootTimingsTraceLog);
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
SystemClock.uptimeMillis());
bootTimingsTraceLog.traceEnd(); // ZygotePreload
} else {
Zygote.resetNicePriority();
}
//fork SystemServer進程
if (startSystemServer) {
Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
// child (system_server) process.
if (r != null) {
r.run();
return;
}
}
//等待Socket的接入
if (caller == null) {
Log.i(TAG, "Accepting command socket connections");
// The select loop returns early in the child process after a fork and
// loops forever in the zygote.
caller = zygoteServer.runSelectLoop(abiList);
}
複製代碼
註釋寫了大概Zygote 啓動裏面的初始化內容
下面繼續看SystemServer 啓動的過程,從Main方法開始
//SystemServer.java
/** * The main entry point from zygote. */
public static void main(String[] args) {
new SystemServer().run();
}
複製代碼
很簡單,建立一個本身的對象,並執行run方法,看一下run方法
private void run() {
...
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
VMRuntime.getRuntime().clearGrowthLimit();
// The system server has to run all of the time, so it needs to be
// as efficient as possible with its memory usage.
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
try {
traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
複製代碼
run方法裏面主要進行了設置手機時間,設置虛擬機內存大小,建立消息循環Looper,建立SystemServiceManager等,最主要的是啓動了各種服務,咱們接着看一下startBootstrapServices ,startCoreServices,startOtherServices方法
private void startBootstrapServices() {
Installer installer = mSystemServiceManager.startService(Installer.class);
mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
....
}
private void startCoreServices() {
...
mSystemServiceManager.startService(BatteryService.class);
...
}
private void startOtherServices() {
final Context context = mSystemContext;
VibratorService vibrator = null;
DynamicAndroidService dynamicAndroid = null;
IStorageManager storageManager = null;
NetworkManagementService networkManagement = null;
IpSecService ipSecService = null;
NetworkStatsService networkStats = null;
NetworkPolicyManagerService networkPolicy = null;
ConnectivityService connectivity = null;
NsdService serviceDiscovery= null;
WindowManagerService wm = null;
SerialService serial = null;
NetworkTimeUpdateService networkTimeUpdater = null;
InputManagerService inputManager = null;
TelephonyRegistry telephonyRegistry = null;
ConsumerIrService consumerIr = null;
MmsServiceBroker mmsService = null;
HardwarePropertiesManagerService hardwarePropertiesService = null;
....
}
複製代碼
在這些方法中啓動了,咱們的核心服務,和經常使用服務。 代碼中也能夠看到AMS,PMS,WMS等相關服務.
通常服務啓動完成後,就會想繼調用systemReady()方法。 在SysytemServer startOtherServices中看到一個監聽回調
mActivityManagerService.systemReady(() -> {
try {
startSystemUi(context, windowManagerF);
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
}
}
static final void startSystemUi(Context context, WindowManagerService windowManager) {
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.android.systemui",
"com.android.systemui.SystemUIService"));
intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
//Slog.d(TAG, "Starting service: " + intent);
context.startServiceAsUser(intent, UserHandle.SYSTEM);
windowManager.onSystemUiStarted();
}
複製代碼
而Ams啓動完成後,顯示Launcher
//AMS.java
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
...
startHomeActivityLocked(currentUserId, "systemReady");
//
mStackSupervisor.resumeFocusedStackTopActivityLocked();
...
}
複製代碼
其實到這裏大體流程就介紹完了,可是文章開始的ActivityThread的main方法是什麼時候被調用的,還沒回答,這裏不詳細展開,簡略回答一些.
AMS是管理Activity的啓動結束等,查看AMS代碼,噹噹前啓動的APP沒有建立進程時,會最終調用到ZygoteProcess,而後向 Zygote發送一個socket請求。
resumeTopActivityLocked -> startProcessLocked -> Process.start() -> ZygoteProcess.start() -> ZygoteProcess.startViaZygote() —> ZygoteProcess.zygoteSendArgsAndGetResult()
接下來,看一下大體代碼
//AMS.java
private final boolean startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
//這裏entryPoint爲ActivityThread
final String entryPoint = "android.app.ActivityThread";
return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
startTime);
}
複製代碼
//ZygoteProcess.java
private Process.ProcessStartResult startViaZygote(final String processClass,... ){
ArrayList<String> argsForZygote = new ArrayList<String>();
argsForZygote.add("--runtime-args");
argsForZygote.add("--setuid=" + uid);
argsForZygote.add("--setgid=" + gid);
argsForZygote.add("--runtime-flags=" + runtimeFlags);
argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
if (startChildZygote) {
argsForZygote.add("--start-child-zygote");
}
argsForZygote.add(processClass);
synchronized(mLock) {
return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
useBlastulaPool,
argsForZygote);
}
}
//發起Socket請求,給Zygote
private static Process.ProcessStartResult zygoteSendArgsAndGetResult( ArrayList<String> args,..){
blastulaSessionSocket = zygoteState.getBlastulaSessionSocket();
final BufferedWriter blastulaWriter = new BufferedWriter(
new OutputStreamWriter(blastulaSessionSocket.getOutputStream()),
Zygote.SOCKET_BUFFER_SIZE);
final DataInputStream blastulaReader =
new DataInputStream(blastulaSessionSocket.getInputStream());
blastulaWriter.write(msgStr);
blastulaWriter.flush();
...
}
複製代碼
最終 Zygote收到請求調用ZygoteInit中zygoteinit方法
//ZygoteInit.java
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
if (RuntimeInit.DEBUG) {
Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
}
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
RuntimeInit.redirectLogStreams();
RuntimeInit.commonInit();
ZygoteInit.nativeZygoteInit();
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}
複製代碼
在 RuntimeInit中findStaticMain,最後在ZygoteInit中執行最終返回的這個Runnable,達到調用main方法的目的.
protected static Runnable applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
nativeSetExitWithoutCleanup(true);
VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
final Arguments args = new Arguments(argv);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
protected static Runnable findStaticMain(String className, String[] argv, ClassLoader classLoader) {
..
m = cl.getMethod("main", new Class[] { String[].class });
return new MethodAndArgsCaller(m, argv);
}
複製代碼
若是你都看到這了,但願幫忙點個贊,謝謝啦。 由於本人水平有限,各路大佬如看到文中有錯誤,歡迎指出,在此表示感謝。
《Android 內核剖析》 柯元旦