1. 概述:

1. Zygote进程是Android Java世界的开创者,所有的Java应用程序进程都由Zygote进程创建;

2. Zygote创建应用程序进程过程其实就是复制自身进程地址空间作为应用程序进程的地址空间,因此在Zygote进程中加载的类和资源都可以共享给所有由Zygote进程孵化的应用程序,应用程序进程只需加载自身私有资源就可以正常运行;

3. Zygote进程是所有Android Java应用程序进程的父进程,Zygote进程和普通应用程序进程之间的关系正是面向对象编程语言中的继承关系,应用程序进程继承Zygote进程的所有资源,Zygote进程在启动时加载所有应用程序进程运行所需的公共资源,即应用程序运行的共性资源;由于普通应用程序有自己的特性资源,因此普通应用程序在启动时,只需要加载自身特性资源就可以了。Linux进程间这种继承关系加快了普通应用程序启动的速度,也简化了应用程序进程的创建过程。既然所有Java应用程序进程都是由Zygote进程创建,那么Android系统是如何请求Zygote进程创建一个新的应用程序进程的呢?在之前,我们介绍了Zygote进程在启动过程中,会根据启动参数创建第一Java进程,它就是SystemServer进程,它是Android系统至关重要的进程,运行中Android系统的绝大部分服务;

4. 普通应用程序进程是无法直接请求Zygote进程孵化新进程的,所有的进程创建请求都是由SystemServer进程发出的。本文依据源码,详细分析SystemServer进程的启动过程。在Zygote进程进入循环监听Socket模式前,会根据Zygote启动参数来选择是否启动SystemServer进程,而Zygote进程的启动是在Android的启动脚本init.rc文件中配置的:

 

2. 从zygote到SystemServer(没看懂,预留)

看的不是很懂,大概知道是zygote会fork一个子进程去启动SystemServer,然后中途会加载各类资源,最后通过反射,跳转至SystemServer

i.mx6 Android5.1.1 Zygote这篇文章的第七章节可知,SystemServer是由zygote产生的

在frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

private static boolean startSystemServer(String abiList, String socketName)
throws MethodAndArgsCaller, RuntimeException {
long capabilities = posixCapabilitiesAsBits(
OsConstants.CAP_BLOCK_SUSPEND,
OsConstants.CAP_KILL,
OsConstants.CAP_NET_ADMIN,
OsConstants.CAP_NET_BIND_SERVICE,
OsConstants.CAP_NET_BROADCAST,
OsConstants.CAP_NET_RAW,
OsConstants.CAP_SYS_MODULE,
OsConstants.CAP_SYS_NICE,
OsConstants.CAP_SYS_RESOURCE,
OsConstants.CAP_SYS_TIME,
OsConstants.CAP_SYS_TTY_CONFIG
);
/* Hardcoded command line to start the system server */
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1032,3001,3002,3003,3006,3007",
"--capabilities=" + capabilities + "," + capabilities,
"--runtime-init",
"--nice-name=system_server",
"com.android.server.SystemServer",
};
ZygoteConnection.Arguments parsedArgs = null; int pid; try {
parsedArgs = new ZygoteConnection.Arguments(args);
ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs); /* Request to fork the system server process */
       //这里fork一个子进程
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
} /* For child process */
     //当为子进程时,跳转
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
} handleSystemServerProcess(parsedArgs);
} return true;
}

3. SystemServer.java

frameworks/base/services/java/com/android/server/SystemServer.java

上面各种调来调取,最后会首先调到SystemServer.java里的main方法

public static void main(String[] args) {
new SystemServer().run();
}

然后新建一个对象接着调用run方法

private void run() {
// 如果设置的时间比1970更早,就设置为1970
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
} // Here we go!
Slog.i(TAG, "Entered the Android system server!");
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis()); //后面几个都是跟虚拟机相关的,设置一些参数属性之类的吧。
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary()); // Enable the sampling profiler.
if (SamplingProfilerIntegration.isEnabled()) {
SamplingProfilerIntegration.start();
mProfilerSnapshotTimer = new Timer();
mProfilerSnapshotTimer.schedule(new TimerTask() {
@Override
public void run() {
SamplingProfilerIntegration.writeSnapshot("system_server", null);
}
}, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
} // Mmmmmm... more memory!
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); // Some devices rely on runtime fingerprint generation, so make sure
// we've defined it before booting further.
Build.ensureFingerprintProperty(); // Within the system server, it is an error to access Environment paths without
// explicitly specifying a user.
Environment.setUserRequired(true); // Ensure binder calls into the system always run at foreground priority.
BinderInternal.disableBackgroundScheduling(true); // Prepare the main looper thread (this thread).
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper(); // Initialize native services.
     //加载动态库libandroid_servers.so,这个是重点!!!!注册了很多本地服务
System.loadLibrary("android_servers");
     //初始化本地服务(里面其实就是Sensor服务),见第4章
nativeInit(); //hj sensormanager libandroid_servers.so // 查看上次关机是否失败,该方法可能不会返回
performPendingShutdown(); // Initialize the system context.
//创建context对象,见第5章
createSystemContext();// Create the system service manager.
//创建SystemServiceManager,并把它加入的LocalServices当中(注意:这里不是加入到ServiceManager)
     mSystemServiceManager = new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); // Start services.
try {
        //启动系统引导服务
startBootstrapServices();
       //启动核心服务
startCoreServices();
     //启动其他服务(我们所需的基本都在这里面)
startOtherServices();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} // For debug builds, log event loop stalls to dropbox for analysis.
if (StrictMode.conditionallyEnableDebugLogging()) {
Slog.i(TAG, "Enabled StrictMode for system server main thread.");
} //循环.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}

4. System.loadLibrary("android_servers")

在这里加载了非常多的本地服务,加载的是libandroid_servers.so,对应到的函数接口为onload.cpp;后面会有一个博客讲解相关技术

frameworks/base/services/core/jni/onload.cpp

extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint result = -; if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
ALOGE("GetEnv failed!");
return result;
}
ALOG_ASSERT(env, "Could not retrieve the env!");
   //注册的本地服务,有了这些,就可以通过JNI去调用了
register_android_server_PowerManagerService(env);
register_android_server_SerialService(env);
register_android_server_InputApplicationHandle(env);
register_android_server_InputWindowHandle(env);
register_android_server_InputManager(env);
register_android_server_LightsService(env);
register_android_server_AlarmManagerService(env);
register_android_server_UsbDeviceManager(env);
register_android_server_UsbHostManager(env);
register_android_server_VibratorService(env);
register_android_server_SystemServer(env);
register_android_server_location_GpsLocationProvider(env);
register_android_server_location_FlpHardwareProvider(env);
register_android_server_connectivity_Vpn(env);
register_android_server_AssetAtlasService(env);
register_android_server_ConsumerIrService(env);
register_android_server_BatteryStatsService(env);
register_android_server_hdmi_HdmiCecController(env);
register_android_server_tv_TvInputHal(env);
register_android_server_PersistentDataBlockService(env);
register_android_server_fingerprint_FingerprintService(env);
register_android_server_Watchdog(env); return JNI_VERSION_1_4;
}

5. nativeInit

frameworks/base/services/core/jni/com_android_server_SystemServer.cpp

这是一个本地服务,搜索全局,可以查到,功能一句话说就是实例化SensorService,并把它添加进ServiceManager

static JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
{ "nativeInit", "()V", (void*) android_server_SystemServer_nativeInit },
};

接着查看

static void android_server_SystemServer_nativeInit(JNIEnv* env, jobject clazz) {
char propBuf[PROPERTY_VALUE_MAX];
property_get("system_init.startsensorservice", propBuf, "");
if (strcmp(propBuf, "") == ) {
// Start the sensor service
SensorService::instantiate();
}
}

frameworks/native/include/binder/BinderService.h

static void instantiate() { publish(); }

在这个函数就不接着往下追了,下面的可以查看博客:SensorService那一篇,总之:在这里就是实例化了SensorService并将它添加进ServiceManager

static status_t publish(bool allowIsolated = false) {
     //得到ServiceManager的对象sm
sp<IServiceManager> sm(defaultServiceManager());
     //将SensorService添加进ServiceManager
return sm->addService(
String16(SERVICE::getServiceName()),
new SERVICE(), allowIsolated);
}

6. createSystemContext

createSystemContext的创建过程可以看看: Android vibrator服务(从APP到kernel driver完全解析)

private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
}

7. SystemServiceManager(还没分析清楚)

8. startBootstrapServices(启动引导服务)

private void startBootstrapServices() {
     //启动Installer服务
Installer installer = mSystemServiceManager.startService(Installer.class); //启动ActivityManagerService服务
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);      //启动PowerManagerService服务
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class); //初始化power management
mActivityManagerService.initPowerManagement(); //启动DisplayManagerService
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class); // We need the default display before we can initialize the package manager.
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY); // Only run "core" apps if we're encrypting the device.
String cryptState = SystemProperties.get("vold.decrypt");
if (ENCRYPTING_STATE.equals(cryptState)) {
Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
mOnlyCore = true;
} else if (ENCRYPTED_STATE.equals(cryptState)) {
Slog.w(TAG, "Device encrypted - only parsing core apps");
mOnlyCore = true;
} // Start the package manager.
Slog.i(TAG, "Package Manager");
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager(); Slog.i(TAG, "User Service");
ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance()); // Initialize attribute cache used to cache resources from packages.
AttributeCache.init(mSystemContext); // Set up the Application instance for the system process and get started.
mActivityManagerService.setSystemProcess();
}

9. startCoreServices(启动核心服务)

private void startCoreServices() {
// Manages LEDs and display backlight.
mSystemServiceManager.startService(LightsService.class); // Tracks the battery level. Requires LightService.
mSystemServiceManager.startService(BatteryService.class); // Tracks application usage stats.
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
// Update after UsageStatsService is available, needed before performBootDexOpt.
mPackageManagerService.getUsageStatsIfNoPackageUsageInfo(); // Tracks whether the updatable WebView is in a ready state and watches for update installs.
mSystemServiceManager.startService(WebViewUpdateService.class);
}

10. startOtherServices(启动其他服务)

基本上我们需要启动的其他大部分服务都在这里了

private void startOtherServices() {
final Context context = mSystemContext;
AccountManagerService accountManager = null;
ContentService contentService = null;
VibratorService vibrator = null;
。。。boolean disableStorage = SystemProperties.getBoolean("config.disable_storage", false);
boolean disableMedia = SystemProperties.getBoolean("config.disable_media", false);
boolean disableBluetooth = SystemProperties.getBoolean("config.disable_bluetooth", false);
boolean disableTelephony = SystemProperties.getBoolean("config.disable_telephony", false);
boolean disableLocation = SystemProperties.getBoolean("config.disable_location", false);
boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false);
boolean disableNonCoreServices = SystemProperties.getBoolean("config.disable_noncore", false);
boolean disableNetwork = SystemProperties.getBoolean("config.disable_network", false);
boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime", false);
boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1"); try {
Slog.i(TAG, "Reading configuration...");
SystemConfig.getInstance(); Slog.i(TAG, "Scheduling Policy");
ServiceManager.addService("scheduling_policy", new SchedulingPolicyService()); mSystemServiceManager.startService(TelecomLoaderService.class); Slog.i(TAG, "Telephony Registry");
telephonyRegistry = new TelephonyRegistry(context);
ServiceManager.addService("telephony.registry", telephonyRegistry); Slog.i(TAG, "Entropy Mixer");
ServiceManager.addService("entropy", new EntropyMixer(context)); 。。。// These are needed to propagate to the runnable below.
final MountService mountServiceF = mountService;
final NetworkManagementService networkManagementF = networkManagement;
final NetworkStatsService networkStatsF = networkStats;
final NetworkPolicyManagerService networkPolicyF = networkPolicy;
final ConnectivityService connectivityF = connectivity;
final NetworkScoreService networkScoreF = networkScore;
final WallpaperManagerService wallpaperF = wallpaper;
final InputMethodManagerService immF = imm;
final LocationManagerService locationF = location;
final CountryDetectorService countryDetectorF = countryDetector;
final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;
final TextServicesManagerService textServiceManagerServiceF = tsms;
final StatusBarManagerService statusBarF = statusBar;
final AssetAtlasService atlasF = atlas;
final InputManagerService inputManagerF = inputManager;
final TelephonyRegistry telephonyRegistryF = telephonyRegistry;
final MediaRouterService mediaRouterF = mediaRouter;
final AudioService audioServiceF = audioService;
final MmsServiceBroker mmsServiceF = mmsService; // We now tell the activity manager it is okay to run third party
// code. It will call back into us once it has gotten to the state
// where third party code can really run (but before it has actually
// started launching the initial applications), for us to complete our
// initialization.
mActivityManagerService.systemReady(new Runnable() {
@Override
public void run() {
Slog.i(TAG, "Making services ready");
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY); try {
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
} 。。。
}
});
}

11. loop

public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
     //死循环
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
} // This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
} msg.target.dispatchMessage(msg); if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
} // Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
} msg.recycleUnchecked();
}
}

i.mx6 Android5.1.1 System server的更多相关文章

  1. i.mx6 Android5.1.1 初始化流程之框架

    Android启动过程分为以下几个步骤: 1.  Boot ROM:  上电后启动芯片固话代码. 2.  BootLoader:固话代码会根据启动模式启动bootloader,(一般为启动引脚的电平的 ...

  2. i.mx6 Android5.1.1 servicemanager本地服务

    接在之前的 i.mx6 Android5.1.1 初始化流程之init进程 i.mx6 Android5.1.1 初始化流程之init.rc解析 servicemanager是由init创建的本地服务 ...

  3. i.mx6 Android5.1.1 初始化流程之init进程(未完成)

    概述: 接在i.mx6 Android5.1.1 初始化流程之框架之后 参考资料:http://blog.csdn.net/mr_raptor/article/category/799879 相关源码 ...

  4. i.mx6 Android5.1.1 初始化流程之init.rc解析(未完成)

    接上一篇:i.mx6 Android5.1.1 初始化流程之init进程 参考资料:http://blog.csdn.net/mr_raptor/article/category/799879 这个博 ...

  5. 图解Android - Zygote, System Server 启动分析

    Init 是所有Linux程序的起点,而Zygote于Android,正如它的英文意思,是所有java程序的'孵化池'(玩过星际虫族的兄弟都晓得的).用ps 输出可以看到 >adb shell ...

  6. i.mx6 Android5.1.1 Zygote

    0. 总结: 0.1 相关源码目录: framework/base/cmds/app_process/app_main.cppframeworks/base/core/jni/AndroidRunti ...

  7. i.mx6 Android5.1.1 vibrator系统服务流程

    0. 概述 0.1 小结 下面来从APP一直分析到kernel的driver,因为vibrator是我所知的最简单的系统服务,分析过程过来,可以获取整个安卓服务的运行思路,把相关知识点都串联起来,又不 ...

  8. i.mx6 Android5.1.1 系统属性

    属性变更的请求时init事件循环处理的另一个事件,在Android平台中,为了让运行中的所有进程共享系统运行时所需要的各种设置值,系统开辟了属性存储区域,并提供了访问该区域的API.属性由键(key) ...

  9. i.mx6 Android5.1.1 build解析

    参考资料:理解 Android Build 系统 把总结放前面: 1. 常用编译命令 make clean 执行清理,等同于:rm -rf out/. make sdk 编译出 Android 的 S ...

随机推荐

  1. spring 3.0版本以上jar包使用以及依赖关系

    本文转载自:http://blog.csdn.net/huiwenjie168/article/details/8477837 spring.jar是包含有完整发布的单个jar包,spring.jar ...

  2. 解决vs2017调试出现脚本错误(/Community/Common7/IDE/PrivateAssemblies/plugin.vs.js) 方法

    原文地址:http://bkcoding.cn/post_1204.html 新装的vs2017编译时出现当前页面脚本错误 url:/Community/Common7/IDE/PrivateAsse ...

  3. artemplate模板

    artTemplate 介绍 最近使用了一款模板,学习成本比较低,性能也不错.觉得很好用,所以推荐给大家. artTemplate 是新一代 javascript 模板引擎,它采用预编译方式让性能有了 ...

  4. 【12c OCP】CUUG OCP认证071考试原题解析(36)

    36.choose the best answer View the Exhibits and examine the structures of the PRODUCTS, SALES, and C ...

  5. 【OCP-12c】CUUG 071题库考试原题及答案解析(24)

    24. choose the best answer In the EMPLOYEES table there are 1000 rows and employees are working in t ...

  6. 在myeclipse中有的项目上有个红色感叹号

    之前做项目的时候遇到过这个问题,最后确定原因是项目引用了很多放在D盘或E盘上的jar包,但是我们不小心把这些jar包删除或移动路径了,因此myeclipse识别不了出现红色的感叹号,解决方式是在mye ...

  7. jenkins详解(一)

    还是以以下几个问题来学习这个软件: 1.jenkins是什么? 2.为什么要用jenkins? 3.怎么用jenkins? 1.jenkins是什么? Jenkins是一个开源的.提供友好操作界面的持 ...

  8. Xcode 编译更改 Build 输出路径

    Xcode新建一个工程,build之后,可执行文件一般在 ~/Library/Developer/Xcode/DerivedData 下. 可以把这个路径指定为当前工程目录.  指定方法 Xcode ...

  9. mybatis的执行流程

    1.SqlSessionFactoryBuilder与SqlSessionFactory 我们一般在使用mybatis是都会通过new SqlSessionFactoryBuilder.build(. ...

  10. iOS关于代码风格问题

    cocoapods管理第三方库,详见cocoapods安装及使用 OC代码风格需要规范,所有第三方依赖需要用cocoapods管理.代码风格需要: 1. pod 'CodeFormatter', :g ...