android启动之SystemServer启动
SystemServer是Android系统的核心,APK应用中可以直接交互的大部分系统服务都在该进程中执行,常见的比方WindowManagerServer(Wms)、ActivityManagerSystemService(AmS)、 PackageManagerServer(PmS)等,这些系统服务都是以一个线程的方式存在于SystemServer进程中。
startSystemServer
systemServer是通过zygote启动的时候fork启动的,我们先看回到ZygoteInit.java类中看一下SystemServer的启动。在zygote启动过程中,通过调用startSystemServer启动systemServer:
private static boolean startSystemServer()
throws MethodAndArgsCaller, RuntimeException {
/* 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,3001,3002,3003,3006,3007",
"--capabilities=130104352,130104352",
"--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 */
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) {
handleSystemServerProcess(parsedArgs);
} return true;
}
首先通过Zygote.forkSystemServer fork出一个子进程来,并传入了一些參数来设置新进程的一些信息,如uid、gid等,函数返回后,假设是子进程pid=0,进入handleSystemServerProcess函数,例如以下:
private static void handleSystemServerProcess(
ZygoteConnection.Arguments parsedArgs)
throws ZygoteInit.MethodAndArgsCaller { closeServerSocket(); // set umask to 0077 so new files and directories will default to owner-only permissions.
Libcore.os.umask(S_IRWXG | S_IRWXO); //ps能够看到system 261 98 391508 49008 ffffffff 4005c880 S system_server,此处system_server就是那个parsedArgs.niceName
if (parsedArgs.niceName != null) {
Process.setArgV0(parsedArgs.niceName);
} if (parsedArgs.invokeWith != null) {
WrapperInit.execApplication(parsedArgs.invokeWith,
parsedArgs.niceName, parsedArgs.targetSdkVersion,
null, parsedArgs.remainingArgs);
} else {
/*
* Pass the remaining arguments to SystemServer.
*/
RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs);
} /* should never reach here 注意不应该执行到这里*/
}
在此函数中首先调用 closeServerSocket()关闭从父进程zygote复制来的socket服务,由于仅仅要zygote去监听处理socket请求就够了。然后继续执行,RuntimeInit.zygoteInit()会通过JNI调用app_main.cpp中的onZygoteInit,启动线程池处理Binder事件 。最后通过invokeStaticMain()函数抛出异常MethodAndArgsCaller。
public static class MethodAndArgsCaller extends Exception implements Runnable {
/** method to call */
private final Method mMethod; /** argument array */
private final String[] mArgs; public MethodAndArgsCaller(Method method, String[] args) {
mMethod = method;
mArgs = args;
} public void run() {
try {
mMethod.invoke(null, new Object[] { mArgs });
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
}
throw new RuntimeException(ex);
}
}
}
这个类继承自Exception,实现了Runnable。该异常被ZygoteInit.java类的main函数catch,并运行run()函数,通过反射启动SystemServer的main函数。
以下是ZygoteInit.java类的main函数捕获异常的代码:
} catch (MethodAndArgsCaller caller) {
caller.run();
}
这样我们就启动了SystemServer.java的main函数了,源代码在 (base\services\java\com\android\server)。
SystemServer.java
让我们来看看这个类中的部分代码:
/**
* This method is called from Zygote to initialize the system. This will cause the native
* services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back
* up into init2() to start the Android services.
*/
native public static void init1(String[] args); public static void main(String[] args) {
//首先检查系统时间设置和SamplingProfiler
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
// If a device's clock is before 1970 (before 0), a lot of
// APIs crash dealing with negative numbers, notably
// java.io.File#setLastModified, so instead we fake it and
// hope that time from cell towers or NTP fixes it
// shortly.
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
} if (SamplingProfilerIntegration.isEnabled()) {
SamplingProfilerIntegration.start();
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
SamplingProfilerIntegration.writeSnapshot("system_server", null);
}
}, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
} // Mmmmmm... more memory!
dalvik.system.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); //载入动态库libandroid_servers.so
System.loadLibrary("android_servers");
//init1()函数是一个native函数,通过JNI终于调用system_init.cpp中的system_init()函数,内部会进行一些与Dalvik虚拟机相关的初始化工作。该函数运行完毕后,其内部会调用Java端的init2()函数,这就是为什么Java源代码中没有引用init2()的地方.
init1(args);
} //基本的系统服 务都是在init2()函数中完毕的。
public static final void init2() {
Slog.i(TAG, "Entered the Android system server!");
//该函数首先创建了一个ServerThread对象,该对象是一个线程,然后直接运行该线程,从ServerThread的run()方法内部開始真正启动各种服务线程。
Thread thr = new ServerThread();
thr.setName("android.server.ServerThread");
thr.start();
}
main()函数首先会运行init1()函数,init1()函数是一个native函数,通过JNI终于调用system_init.cpp中的system_init()函数:
extern "C" status_t system_init()
{
ALOGI("Entered system_init()");
sp<ProcessState> proc(ProcessState::self());
sp<IServiceManager> sm = defaultServiceManager();
ALOGI("ServiceManager: %p\n", sm.get()); sp<GrimReaper> grim = new GrimReaper();
sm->asBinder()->linkToDeath(grim, grim.get(), 0); char propBuf[PROPERTY_VALUE_MAX];
property_get("system_init.startsurfaceflinger", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
//启动SurfaceFlinger
SurfaceFlinger::instantiate();
} property_get("system_init.startsensorservice", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
//启动sensor service
SensorService::instantiate();
} // And now start the Android runtime. We have to do this bit
// of nastiness because the Android runtime initialization requires
// some of the core system services to already be started.
// All other servers should just start the Android runtime at
// the beginning of their processes's main(), before calling
// the init function.
ALOGI("System server: starting Android runtime.\n");
AndroidRuntime* runtime = AndroidRuntime::getRuntime(); ALOGI("System server: starting Android services.\n");
JNIEnv* env = runtime->getJNIEnv();
if (env == NULL) {
return UNKNOWN_ERROR;
}
//通过“com/android/server/SystemServer”找到SystemServer.java的类
jclass clazz = env->FindClass("com/android/server/SystemServer");
if (clazz == NULL) {
return UNKNOWN_ERROR;
}
//找到SystemServer.java的类的init2方法
jmethodID methodId = env->GetStaticMethodID(clazz, "init2", "()V");
if (methodId == NULL) {
return UNKNOWN_ERROR;
}
//执行init2()函数
env->CallStaticVoidMethod(clazz, methodId); ALOGI("System server: entering thread pool.\n");
ProcessState::self()->startThreadPool();
IPCThreadState::self()->joinThreadPool();
ALOGI("System server: exiting thread pool.\n"); return NO_ERROR;
}
system_init()函数回调init2()函数,init2()函数启动ServerThread线程来加入各种服务以及其它的一些初始化工作,ServerThread是一个内部类,大体代码例如以下;
class ServerThread extends Thread { ... @Override
public void run() {
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,
SystemClock.uptimeMillis());
Looper.prepareMainLooper(); ... String factoryTestStr = SystemProperties.get("ro.factorytest");
int factoryTest = "".equals(factoryTestStr) ? SystemServer.FACTORY_TEST_OFF
: Integer.parseInt(factoryTestStr);
final boolean headless = "1".equals(SystemProperties.get("ro.config.headless", "0")); //定义变量,初始化服务,创建各种服务实例,如:电源、网络、Wifi、蓝牙,USB等
...
Context context = null;
... // Create a shared handler thread for UI within the system server.
// This thread is used by at least the following components:
// - WindowManagerPolicy
// - KeyguardViewManager
// - DisplayManagerService
HandlerThread uiHandlerThread = new HandlerThread("UI");
uiHandlerThread.start();
Handler uiHandler = new Handler(uiHandlerThread.getLooper());
uiHandler.post(new Runnable() {
@Override
public void run() {
//Looper.myLooper().setMessageLogging(new LogPrinter(
// Log.VERBOSE, "WindowManagerPolicy", Log.LOG_ID_SYSTEM));
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false); // For debug builds, log event loop stalls to dropbox for analysis.
if (StrictMode.conditionallyEnableDebugLogging()) {
Slog.i(TAG, "Enabled StrictMode logging for UI Looper");
}
}
}); // Create a handler thread just for the window manager to enjoy.
HandlerThread wmHandlerThread = new HandlerThread("WindowManager");
wmHandlerThread.start();
Handler wmHandler = new Handler(wmHandlerThread.getLooper());
wmHandler.post(new Runnable() {
@Override
public void run() {
//Looper.myLooper().setMessageLogging(new LogPrinter(
// android.util.Log.DEBUG, TAG, android.util.Log.LOG_ID_SYSTEM));
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_DISPLAY);
android.os.Process.setCanSelfBackground(false); // For debug builds, log event loop stalls to dropbox for analysis.
if (StrictMode.conditionallyEnableDebugLogging()) {
Slog.i(TAG, "Enabled StrictMode logging for WM Looper");
}
}
}); // Critical services...
boolean onlyCore = false;
try {
// Wait for installd to finished starting up so that it has a chance to
// create critical directories such as /data/user with the appropriate
// permissions. We need this to complete before we initialize other services.
Slog.i(TAG, "Waiting for installd to be ready.");
installer = new Installer();
installer.ping(); //原来的EntropyService,熵混淆,添加随机数的不可预測性
Slog.i(TAG, "Entropy Mixer");
ServiceManager.addService("entropy", new EntropyMixer());//用Context.getSystemService (String name) 才获取到对应的服务 //向ServiceManager加入电源管理服务
Slog.i(TAG, "Power Manager");
power = new PowerManagerService();
ServiceManager.addService(Context.POWER_SERVICE, power); //启动ActivityManagerService,注意返回了一个context
Slog.i(TAG, "Activity Manager");
context = ActivityManagerService.main(factoryTest); //使用uiHandler、wmHandler
Slog.i(TAG, "Display Manager");
display = new DisplayManagerService(context, wmHandler, uiHandler);
ServiceManager.addService(Context.DISPLAY_SERVICE, display, true); ...
//使用wmHandler
Slog.i(TAG, "Input Manager");
inputManager = new InputManagerService(context, wmHandler); //使用uiHandler、wmHandler
Slog.i(TAG, "Window Manager");
wm = WindowManagerService.main(context, power, display, inputManager,
uiHandler, wmHandler,
factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL,
!firstBoot, onlyCore);
ServiceManager.addService(Context.WINDOW_SERVICE, wm);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager); ActivityManagerService.setSystemProcess(); ... Slog.i(TAG, "System Content Providers");
ActivityManagerService.installSystemProviders();
... // only initialize the power service after we have started the lights service, content providers and the battery service.
power.init(context, lights, ActivityManagerService.self(), battery,
BatteryStatsService.getService(), display); ... Slog.i(TAG, "Init Watchdog");
Watchdog.getInstance().init(context, battery, power, alarm,
ActivityManagerService.self()); ... ActivityManagerService.self().setWindowManager(wm); ... //使用wmHandler
if (context.getResources().getBoolean(
com.android.internal.R.bool.config_dreamsSupported)) {
try {
Slog.i(TAG, "Dreams Service");
// Dreams (interactive idle-time views, a/k/a screen savers)
dreamy = new DreamManagerService(context, wmHandler);
ServiceManager.addService(DreamService.DREAM_SERVICE, dreamy);
} catch (Throwable e) {
reportWtf("starting DreamManagerService", e);
}
}
} catch (RuntimeException e) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting core service", e);
} ... try {
Slog.i(TAG, "NetworkPolicy Service");
networkPolicy = new NetworkPolicyManagerService(
context, ActivityManagerService.self(), power,
networkStats, networkManagement);
ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
} catch (Throwable e) {
reportWtf("starting NetworkPolicy Service", e);
} ...
} ... if (safeMode) {
ActivityManagerService.self().showSafeModeOverlay();
} ... //系统服务初始化准备就绪,通知各个模块
ActivityManagerService.self().systemReady(new Runnable() {
public void run() {
Slog.i(TAG, "Making services ready"); if (!headless) startSystemUi(contextF);
try {
if (mountServiceF != null) mountServiceF.systemReady();
} catch (Throwable e) {
reportWtf("making Mount Service ready", e);
} ... try {
if (telephonyRegistryF != null) telephonyRegistryF.systemReady();
} catch (Throwable e) {
reportWtf("making TelephonyRegistry ready", e);
}
}
}); // 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();
Slog.d(TAG, "System ServerThread is exiting!");
} static final void startSystemUi(Context context) {
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.android.systemui",
"com.android.systemui.SystemUIService"));
//Slog.d(TAG, "Starting service: " + intent);
context.startServiceAsUser(intent, UserHandle.OWNER);
}
}
到这里系统ApplicationFramework层的XxxServiceManager准备就绪
android启动之SystemServer启动的更多相关文章
- Android服务之PackageManagerService启动源码分析
了解了Android系统的启动过程的读者应该知道,Android的所有Java服务都是通过SystemServer进程启动的,并且驻留在SystemServer进程中.SystemServer进程在启 ...
- Android应用程序进程启动过程(前篇)
在此前我讲过Android系统的启动流程,系统启动后,我们就比较关心应用程序是如何启动的,这一篇我们来一起学习Android7.0 应用程序进程启动过程,需要注意的是“应用程序进程启动过程”,而不是应 ...
- Android5 Zygote 与 SystemServer 启动流程分析
Android5 Zygote 与 SystemServer 启动流程分析 Android5 Zygote 与 SystemServer 启动流程分析 前言 zygote 进程 解析 zygoterc ...
- 如何在android studio 1.0 启动时设置代理【解决WARN - ateSettings.impl.UpdateChecker - Connection failed.】
今天第一次用android studio,下了个比较新的1.0.1 linux版本,结果启动时老是出现以下错误: [ 6987] WARN - ateSettings.impl.UpdateCheck ...
- Android开发之---Activity启动模式
在Android开发中,启动一个新的activity我们可以使用startActivity或startActivityForResult,Android系统使用栈的方式来管理一个APP的页面显示与保存 ...
- Android中Activity的启动模式
简介 Android中的活动启动方式分为4种:standard, singleTop, singleTask, singleInstance.可以在AndroidManifest.xml中通过给< ...
- Android service介绍和启动方式
1.Android service的作用: service通常是用来处理一些耗时操作,或后台执行不提供用户交互界面的操作,例如:下载.播放音乐. 2.Android service的生命周期: ser ...
- 【Android】应用程序启动过程源码分析
在Android系统中,应用程序是由Activity组成的,因此,应用程序的启动过程实际上就是应用程序中的默认Activity的启动过程,本文将详细分析应用程序框架层的源代码,了解Android应用程 ...
- init进程 && 解析Android启动脚本init.rc && 修改它使不启动android && init.rc中启动一个sh文件
Android启动后,系统执行的第一个进程是一个名称为init 的可执行程序.提供了以下的功能:设备管理.解析启动脚本.执行基本的功能.启动各种服务.代码的路径:system/core/init,编译 ...
随机推荐
- Linux删除除了今天以外的文件
[背景] 开发到日志记录功能时,每天都会产生当天的一个日志,久而久之就会产生累积,想要查看的时候,tab键无法自动补全,还要自己额外输入. 比较麻烦. [命令] 经过查找和实验,找到了以下的方法: 1 ...
- git配置用户名跟邮箱
因为我有两个git账号 所以我现在要改变我的默认用户名跟邮件 我就需要去终端设置用户名跟邮箱 具体的命令行就是 设置git的用户名 git config --global user.name &quo ...
- 新版Java为什么要修改substring的实现
Java字符串的截取操作可以通过substring来完成.有意思的是,这个方法从jdk1.0开始,一直到1.6都没有变化,但到了1.7实现方式却发生了改变.你可能会认为之所以要对一个成熟且稳定的方法做 ...
- 深度学习方法(十一):卷积神经网络结构变化——Google Inception V1-V4,Xception(depthwise convolution)
欢迎转载,转载请注明:本文出自Bin的专栏blog.csdn.net/xbinworld. 技术交流QQ群:433250724,欢迎对算法.机器学习技术感兴趣的同学加入. 上一篇讲了深度学习方法(十) ...
- EF – 1.模式
3种数据库 code first model first database first 创建EF http://www.cnblogs.com/tangge/p/3834578.html DbSet ...
- PhpStorm设置函数注释模板
*设置位置:"Settings"->"file templates"; 如下图,设置头部注释.类注释以及函数注释,时间.用户名.文件名称等随机改变的属性, ...
- Selenium--testNG下载地址
TestNG - http://beust.com/eclipse http://testng.org/doc/eclipse.html http://testng.org/doc/seleniu ...
- ie6 css 返回顶部图标固定在浏览器右下角
比较常用记录一下. #e_float{ _position:absolute; _bottom:auto; _right:50%; _margin-right:-536px; _top:express ...
- JOYOI 西瓜种植 [差分约束系统]
题目传送门 西瓜种植 题目限制 时间限制 内存限制 评测方式 题目来源 1000ms 131072KiB 标准比较器 Local 题目背景 笨笨:小西瓜,小西瓜~路人甲:不会呀,这西瓜明明就大着啊…… ...
- LCA:倍增与tarjan
学了好久(一两个星期)都没彻底搞懂的lca,今天总算理解了.就来和大家分享下我自己的心得 首先,如果你还不懂什么是lca,出门左转自行百度 首先讲倍增 倍增的思想很简单,首先进行预处理,用一个深搜将每 ...