Android系统中各个进程的前后顺序为:java
init
进程 –-> Zygote
进程 –> SystemServer
进程 –>应用进程其中Zygote
进程由init
进程启动,SystemServer
进程和应用进程由Zygote
进程启动。android
本文依据6.0源码,主要分析SystemServer
进程的启动流程。注意,是启动流程,不是启动过程。启动过程的解析能够移步个人另外一片博文Zygote启动流程源码解析。SystemServer
进程的做用是启动各类核心服务,例如Installer
、ActivityManagerService
、WindowManagerService
、PowerManagerService
等等。这些服务会在开机时启动。因为加载的服务不少,相对很耗时,因此android系统在开机时速度很慢,可是一次加载以后,方便后续全部应用程序调用,因此这个代价仍是很是值得的。因为加载的服务实在太多,故本文不可能分析全部的服务。分析完主要流程后,会适当举例分析,其他服务还请自行查看。从Android Zygote启动流程源码解析一文中能够看到:Zygote
进程fork
出SystemServer
进程后,经过反射调用SystemServer#main()
。以此为切入点,一步步分析。app
源码位置:frameworks/base/services/Java/com/android/server/SystemServer.java
SystemServer#main()ide
/** * The main entry point from zygote. */ public static void main(String[] args) { new SystemServer().run(); } public SystemServer() { // Check for factory test mode. mFactoryTestMode = FactoryTest.getMode(); } private void run() { ... // 建立主线程Looper Looper.prepareMainLooper(); // 加载android_servers.so System.loadLibrary("android_servers"); // 建立Context对象 createSystemContext(); // 建立SystemServiceManager对象 mSystemServiceManager = new SystemServiceManager(mSystemContext); // 将刚建立的SystemServiceManager对象添加进LocalServices属性sLocalServiceObjects LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); // Start services. try { // 启动系统引导相关服务 startBootstrapServices(); // 启动系统核心服务 startCoreServices(); // 启动应用或系统相关的服务 startOtherServices(); } catch (Throwable ex) {...} ... // Loop forever. Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
上面截取了最关键的代码,也是本文重点要分析的内容。能够看到,在Main()
方法中实例化以后直接调用了run()
方法。在run()
方法中首先获取主线程的Looper对象,这也就意味着SystemServer
后续是能够获取主线程中的消息。下面先分析createSystemContext()
。oop
SystemServer#createSystemContext()this
private void createSystemContext() { ActivityThread activityThread = ActivityThread.systemMain(); mSystemContext = activityThread.getSystemContext(); mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar); }
在createSystemContext()
中首先获取了一个ActivityThread
对象,紧接着根据ActivityThread
对象获取了mSystemContext
,mSystemContext
是Context
对象。这可不得了。咱们知道,ActivityThread
其实就是所谓的主线程,看来ActivityThread#systemMain()
这个方法大有搞头。跟进。spa
源码位置:frameworks/base/core/java/android/app/ActivityThread.java
ActivityThread#systemMain().net
public static ActivityThread systemMain() { ... ActivityThread thread = new ActivityThread(); thread.attach(true); return thread; }
在ActivityThread#systemMain()
中直接new
了一个ActivityThread
对象,而后调用ActivityThread#attach()
方法。跟进。线程
ActivityThread() { mResourcesManager = ResourcesManager.getInstance(); } private void attach(boolean system) { sCurrentActivityThread = this; mSystemThread = system; if (!system) { ... } else { ... mInstrumentation = new Instrumentation(); ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo); mInitialApplication = context.mPackageInfo.makeApplication(true, null); mInitialApplication.onCreate(); ... } ...
能够看到,调用ContextImpl
的静态方法createAppContext()
获取一个ContextImpl
对象,而后调用LoadedApk(mPackageInfo是LoadedApk的一个对象)#makeApplication()
建立了Application
,最后调用Application#onCreate()
方法。SystemServer
也是一个Android
进程,由此能够看出,进程建立后最早被调用的是ActivityThread#attach()
,其次才是Application#onCreate()
。code
回到SystemServer#run()
。
private void run() { ... createSystemContext(); // 建立SystemServiceManager对象 mSystemServiceManager = new SystemServiceManager(mSystemContext); // 将刚建立的SystemServiceManager对象添加进LocalServices属性sLocalServiceObjects LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); ... }
获取到Context
对象后,建立mSystemServiceManager
用于管理各类系统服务。接下来就开始启动各类系统服务。文章有限,这里以启动Installer
、ActivityManagerService
和WindowManagerService
为例进行分析,其他还请自行查看。
ActivityThread#startBootstrapServices()
startBootstrapServices(); startCoreServices(); startOtherServices();
private void startBootstrapServices() { Installer installer = mSystemServiceManager.startService(Installer.class); }
经过SystemServiceManager#startService()
方法,就启动了Installer
。跟进。
源码位置:frameworks/base/services/core/java/com/android/server/SystemServerManager.java
SystemServiceManager#startService()
public <T extends SystemService> T startService(Class<T> serviceClass) { if (!SystemService.class.isAssignableFrom(serviceClass)) { throw new RuntimeException("Failed to create " + name + ": service must extend " + SystemService.class.getName()); } final T service; Constructor<T> constructor = serviceClass.getConstructor(Context.class); service = constructor.newInstance(mContext); mServices.add(service); service.onStart(); return service; }
传入的泛型必须是抽象类SystemService
的子类,而且经过反射获得实例。最后添加进ArrayList<SystemService> mServices
中以便管理。最后调用泛型Service
中抽象父类的抽象方法onStart()
的具体实现。跟进。
源码位置:frameworks/base/services/core/java/com/android/server/pm/Installer.java
Installer#onStart()
public void onStart() { mInstaller.waitForConnection(); }
mInstaller
是InstallerConnection
对象。跟进。
源码位置:frameworks/base/services/core/java/com/android/internal/os/InstallerConnection.java
InstallerConnection#waitForConnection()
public void waitForConnection() { for (;;) { if (execute("ping") >= 0) { return; } Slog.w(TAG, "installd not ready"); SystemClock.sleep(1000); } }
这里有个死循环,说明只有execute()
方法执行成功而且返回值大于0以后才会继续启动其余服务。不然一直卡在这里。跟进。
public int execute(String cmd) { String res = transact(cmd); try { return Integer.parseInt(res); } catch (NumberFormatException ex) { return -1; } } public synchronized String transact(String cmd) { if (!connect()) { return "-1"; } if (!writeCommand(cmd)) { if (!connect() || !writeCommand(cmd)) { return "-1"; } } final int replyLength = readReply(); if (replyLength > 0) { String s = new String(buf, 0, replyLength); return s; } else { return "-1"; } } private boolean connect() { if (mSocket != null) { return true; } Slog.i(TAG, "connecting..."); try { mSocket = new LocalSocket(); LocalSocketAddress address = new LocalSocketAddress("installd", LocalSocketAddress.Namespace.RESERVED); mSocket.connect(address); mIn = mSocket.getInputStream(); mOut = mSocket.getOutputStream(); } catch (IOException ex) { disconnect(); return false; } return true; } private boolean writeCommand(String cmdString) { final byte[] cmd = cmdString.getBytes(); final int len = cmd.length; if ((len < 1) || (len > buf.length)) { return false; } buf[0] = (byte) (len & 0xff); buf[1] = (byte) ((len >> 8) & 0xff); try { mOut.write(buf, 0, 2); mOut.write(cmd, 0, len); } catch (IOException ex) { Slog.e(TAG, "write error"); disconnect(); return false; } return true; }
为了方便查看,连续贴了三个相关的方法。稍微显得有些长,不要紧,咱们一个个去分析。首先调用connect()
方法经过Socket
链接installd
服务端。接着调用writeCommand()
方法写入要发送的数据,这里参数cmdString
是ping
,因此len=4
。最后经过readReply()
方法,读取服务端返回的数据,转换成String
形式返回。以后启动其它服务。
private void startBootstrapServices() { mActivityManagerService = mSystemServiceManager.startService( ActivityManagerService.Lifecycle.class).getService(); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); }
这里和启动Installer
不一样,startService()
传入的是ActivityManagerService.Lifecycle.class
,以后调用startService()
返回值的getService()
方法。跟进。
源码位置:frameworks/base/services/core/java/com/android/servicer/am/ActivityManagerService.java
ActivityManagerService$Lifecycle
public static final class Lifecycle extends SystemService { private final ActivityManagerService mService; public Lifecycle(Context context) { super(context); mService = new ActivityManagerService(context); } @Override public void onStart() { mService.start(); } public ActivityManagerService getService() { return mService; } }
Lifecycle
是ActivityManagerService
的一个final类型的静态内部类。在分析SystemServiceManager#startService()
说道:经过反射获得实例。最后添加进ArrayList<SystemService> mServices
中以便管理。最后调用泛型Service
中抽象父类的抽象方法onStart()
的具体实现。因此这里首先会实例化ActivityManagerService
对象,而后调用Lifecycle#onStart()
。在Lifecycle#onStart()
中调用ActivityManagerService#start()
。最后getService()
返回实例化过的ActivityManagerService
对象。因为ActivityManagerService#start()
相关代码太多,这里就不详细展开了。有时间单独写一篇博文解析。
private void startOtherServices() { wm = WindowManagerService.main(context, inputManager, mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL, !mFirstBoot, mOnlyCore); }
这里和启动Installer
、ActivityManagerService
又有些不一样,直接调用WindowManagerService#main()
。真的是简单粗暴。跟进。
public static WindowManagerService main(final Context context, final InputManagerService im, final boolean haveInputMethods, final boolean showBootMsgs, final boolean onlyCore) { final WindowManagerService[] holder = new WindowManagerService[1]; DisplayThread.getHandler().runWithScissors(new Runnable() { @Override public void run() { holder[0] = new WindowManagerService(context, im, haveInputMethods, showBootMsgs, onlyCore); } }, 0); return holder[0]; }
相关代码太长,有时间单独再写一篇。其它服务的启动和上面三种服务启动截然不同,感兴趣的同窗请自行查看。2点多,有些困。明天还要上班,古耐