Android 基于Linux,而所有的进程都基于init进程。 。
当系统开机时,就会由init进程fork出Zygote进程,它时Android系统中第一个Dalvik虚拟机上的第一个进程,同时负责卵化其他apk的进程。
SystemServer进程,Android系统的第二大进程,也是一个非常重要的进程,它本身也是由Zygote进程卵化出来的。
在ZygoteInit的main方法
public static void main(String argv[]) {
....
try {
....
boolean startSystemServer = false;
String socketName = "zygote";
String abiList = null;
boolean enableLazyPreload = false;
//第一次fork出Zygote时,会让startSystemServer为 true,来开启SystemServer进程
for (int i = 1; i < argv.length; i++) {
if ("start-system-server".equals(argv[i])) {
startSystemServer = true;
} else if ("--enable-lazy-preload".equals(argv[i])) {
enableLazyPreload = true;
} else if (argv[i].startsWith(ABI_LIST_ARG)) {
abiList = argv[i].substring(ABI_LIST_ARG.length());
} else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
socketName = argv[i].substring(SOCKET_NAME_ARG.length());
} else {
throw new RuntimeException("Unknown command line argument: " + argv[i]);
}
}
....
//开启SystemServer进程
if (startSystemServer) {
startSystemServer(abiList, socketName, zygoteServer);
}
zygoteServer.runSelectLoop(abiList);
zygoteServer.closeServerSocket();
} catch (Zygote.MethodAndArgsCaller caller) {
caller.run();
} catch (Throwable ex) {
Log.e(TAG, "System zygote died with exception", ex);
zygoteServer.closeServerSocket();
throw ex;
}
}
private static boolean startSystemServer(String abiList, String socketName, ZygoteServer zygoteServer)
throws Zygote.MethodAndArgsCaller, RuntimeException {
....
int pid;
try {
/* Request to fork the system server process */
//请求发送system serve进程。
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
...
return true;
}
通过Zygote.forkSystemServer,fork出SystemServer进程,就会走SystemServer的main方法
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
try {
...
//准备looper
Looper.prepareMainLooper();
// Initialize native services.
//加载本地服务
System.loadLibrary("android_servers");
// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();
// Initialize the system context.
//创建系统上下文
createSystemContext();
// Create the system service manager.
// 初始化SystemServiceManager对象。用来开启一些基础的系统服务
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.get();
} finally {
traceEnd(); // InitBeforeStartServices
}
//开启必要的系统服务
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");
}
创建系统上下文
private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
调用的是ActivityThread.systemMain();然后设置系统主题
public static ActivityThread systemMain() {
...
//为什么这里需要ActivityThread,它代表的是一个应用的进程
//因为SystemServer进程中,比如关机对话框,本身也是activity,运行在SystemServer进程中,因此也可认为SystemServer是一个特殊的应用进程。
ActivityThread thread = new ActivityThread();
thread.attach(true);
return thread;
}
//初始化系统的Context,系统的Instrumentation 以及系统的Application,并执行onCreate方法。
private void attach(boolean system) {
...
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
//当系统配置发生变化(如语言切换等)时,需要调用该回调
ViewRootImpl.ConfigChangedCallback configChangedCallback
= (Configuration globalConfig) -> {
synchronized (mResourcesManager) {
// We need to apply this change to the resources immediately, because upon returning
// the view hierarchy will be informed about it.
if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
null /* compat */)) {
updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
mResourcesManager.getConfiguration().getLocales());
// This actually changed the resources! Tell everyone about it.
if (mPendingConfiguration == null
|| mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
mPendingConfiguration = globalConfig;
sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
}
}
}
};
//注册Configuration变化的回调通知
ViewRootImpl.addConfigCallback(configChangedCallback);
}
//获取系统的Context
static ContextImpl createSystemContext(ActivityThread mainThread) {
//Loaded代表的是加载到系统中的APK,保存如资源文件位置等
//默认的LoadedApk的packagename 是 android 其实就是framework-res.apk,仅供SystemServer使用
LoadedApk packageInfo = new LoadedApk(mainThread);
//初始化ContextImpl对象
ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
null);
//设置资源信息
context.setResources(packageInfo.getResources());
//初始化资源信息
context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
context.mResourcesManager.getDisplayMetrics());
return context;
}
createSystemContext方法,第一个得了一个ActivityThread对象,第二得了一个Context对象,一个专给SystemServer用的packageName 为“android”的apk。
createSystemContext函数将为SystemServer进程搭建一个和应用进程一样的Android运行环境。
开启必要的核心服务
..
startBootstrapServices();
startCoreServices();
startOtherServices();
// 一些相互需要互相使用的核心服务
private void startBootstrapServices() {
...
traceBeginAndSlog("StartInstaller");
//第一个先是安装服务
Installer installer = mSystemServiceManager.startService(Installer.class);
traceEnd();
//第二个设备管理服务
traceBeginAndSlog("DeviceIdentifiersPolicyService");
mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
traceEnd();
// 第三个这个比较重要的AMS 用来管理四大组件的核心服务
traceBeginAndSlog("StartActivityManager");
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
//2.将SystemServer进程可加到AMS中调度管理
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
traceEnd();
traceBeginAndSlog("StartPowerManager");
// 电源管理服务
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
traceEnd();
....等等
}
//一些不需要相互引用的基础服务
private void startCoreServices() {
//错误日志追踪的服务
traceBeginAndSlog("StartDropBoxManager");
mSystemServiceManager.startService(DropBoxManagerService.class);
traceEnd();
traceBeginAndSlog("StartBatteryService");
// 电池服务
mSystemServiceManager.startService(BatteryService.class);
traceEnd();
// Tracks application usage stats.
traceBeginAndSlog("StartUsageService");
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
traceEnd();
// Tracks whether the updatable WebView is in a ready state and watches for update installs.
traceBeginAndSlog("StartWebViewUpdateService");
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
traceEnd();
}
// 一些别的被重构和组织的东西,如相机服务,闹钟服务,蓝牙服务,同时在ActivityManagerService中开启SystemUi 启动Launcher程序都在这里
//方法非常非常长。。。
private void startOtherServices() {
...
//设置windowManager,内部保存WindowManagerService
mActivityManagerService.setWindowManager(wm);
....
//AMS是系统核心,只有它准备好了,才能调用别的服务的systemReady
mActivityManagerService.systemReady(() -> {
...
traceBeginAndSlog("StartSystemUI");
try {
//开启SysytemUi 状态栏 底部导航栏等
startSystemUi(context, windowManagerF);
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
...
}, BOOT_TIMINGS_TRACE_LOG);
}
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();
}
启动SystemUIService SystemUIService由SystemUi.apk提供,它实现了系统的状态栏,底部导航条。
AMS的systemReady方法
public void systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) {
traceLog.traceBegin("PhaseActivityManagerReady");
synchronized(this) {
if (mSystemReady) {
// If we're done calling all the receivers, run the next "boot phase" passed in
// by the SystemServer
if (goingCallback != null) {
goingCallback.run();
}
return;
}
mLocalDeviceIdleController
= LocalServices.getService(DeviceIdleController.LocalService.class);
mAssistUtils = new AssistUtils(mContext);
mVrController.onSystemReady();
// Make sure we have the current profile info, since it is needed for security checks.
mUserController.onSystemReady();
mRecentTasks.onSystemReadyLocked();
mAppOpsService.systemReady();
mSystemReady = true;
}
....
}
goingCallback这个参数就是run方法。mSystemReady初始值为false,所以 goingCallback.run();不会执行,接着在下面给 mSystemReady = true;
还是systemReady方法
ArrayList<ProcessRecord> procsToKill = null;
synchronized(mPidsSelfLocked) {
//找到先于AMS启动的进程
//这些应用进程一定是APK所在的Java进程,因为只有应用进程才会向AMS注册
//那些声明了persistent为true的进程可能会先于AMS启动。所以一定要先关闭
for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
ProcessRecord proc = mPidsSelfLocked.valueAt(i);
if (!isAllowedWhileBooting(proc.info)){
if (procsToKill == null) {
procsToKill = new ArrayList<ProcessRecord>();
}
procsToKill.add(proc);
}
}
}
synchronized(this) {
if (procsToKill != null) {
for (int i=procsToKill.size()-1; i>=0; i--) {
ProcessRecord proc = procsToKill.get(i);
Slog.i(TAG, "Removing system update proc: " + proc);
//关闭这些先于AMS启动的进程
removeProcessLocked(proc, true, false, "system update done");
}
}
//这里 系统准备完毕
mProcessesReady = true;
}
....
//调用里面的run方法,启动诸如SystemUi等,以及调用其他服务的systemReady函数
if (goingCallback != null) goingCallback.run();
...
//开启第一个Avtivity
startHomeActivityLocked(currentUserId, "systemReady");
启动桌面程序
boolean startHomeActivityLocked(int userId, String reason) {
//设置intent
Intent intent = getHomeIntent();
//向PKMS查询满足条件的ActivityInfo
ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
if (aInfo != null) {
intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
// Don't do this if the home app is currently being
// instrumented.
aInfo = new ActivityInfo(aInfo);
aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
//判断进程存在不 因为刚开机一般是不存在的 所以需要启动
ProcessRecord app = getProcessRecordLocked(aInfo.processName,
aInfo.applicationInfo.uid, true);
if (app == null || app.instr == null) {
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
final int resolvedUserId = UserHandle.getUserId(aInfo.applicationInfo.uid);
// For ANR debugging to verify if the user activity is the one that actually
// launched.
final String myReason = reason + ":" + userId + ":" + resolvedUserId;
//启动Activity--这里最终调用的就是startActivity方法。
mActivityStarter.startHomeActivityLocked(intent, aInfo, myReason);
}
} else {
Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
}
return true;
}
Intent getHomeIntent() {
Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
intent.setComponent(mTopComponent);
intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
//添加Category为HOME类别
intent.addCategory(Intent.CATEGORY_HOME);
}
return intent;
}
到这里,系统已经准备完毕,桌面也启动完成。
总结:
这里主要分析Zygoteinit SystemServer ActivityManagerService这三个主要的类,Zygote进程是由init进程fork出来,是第一个运行在Diavlk虚拟机上的进程,可以说是Android所有进程中的上帝进程,它的职责负责卵化别的应用进程,SystemServer是Android第二大关键进程,它也是由Zygote卵化出来的,它的主要作用是初始化一些核心服务,如AMS WMS 各种熟知的服务等,值得注意的是,在启动这些关键服务之前,它createSystemContext(),之所以需要Context对象,是因为如SystemUi 关机页面这些activity其实就是运行在改进程内,而不是别的进程。最后,由SystemServer进程中ActivityManagerService来完成系统的剩余扫尾工作,同时启动桌面程序。