System server的启动过程参考下面流程图,具体细节可以参考zygote的启动过程。本文主要描述system server从初始化到启动Home的过程。
systemServer进程主函数入口:
frameworks/base/services/java/com/android/server/SystemServer.java
- public static void main(String[] args) {
- // 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);
- System.loadLibrary("android_servers"); //Load JNI library here that is used by SystemServer
- init1(args); //这里调用到android_server_SystemServer_init1@com_android_server_SystemServer.cpp
- }
systemServer初始化函数1,用来启动进程内所有的native服务,因为其他java服务依赖这些服务。
frameworks/base/services/jni/com_android_server_SystemServer.cpp
- static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
- {
- system_init();
- }
frameworks/base/cmds/system_server/library/system_init.cpp
- extern "C" status_t system_init()
- {
- sp<ProcessState> proc(ProcessState::self());
- sp<IServiceManager> sm = defaultServiceManager();
- LOGI("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是否run在systemserver里
- // Start the SurfaceFlinger
- SurfaceFlinger::instantiate();
- }
- // Start the sensor service
- SensorService::instantiate(); //启动SensorService
- // On the simulator, audioflinger et al don't get started the
- // same way as on the device, and we need to start them here
- if (!proc->supportsProcesses()) { //在phone上,这些service在mediaserver中创建。模拟器上,以下service在此进程创建
- // Start the AudioFlinger
- AudioFlinger::instantiate();
- // Start the media playback service
- MediaPlayerService::instantiate();
- // Start the camera service
- CameraService::instantiate();
- // Start the audio policy service
- AudioPolicyService::instantiate();
- }
- AndroidRuntime* runtime = AndroidRuntime::getRuntime();
- runtime->callStatic("com/android/server/SystemServer", "init2");//调用init2@SystemServer.java,在这里创建工作线程以启动各java服务并进入循环处理各service请求
- if (proc->supportsProcesses()) {
- ProcessState::self()->startThreadPool(); //启动线程池,注意:由于前面已经调用过startThreadPool,故此次调用不做任何事情
- IPCThreadState::self()->joinThreadPool(); //主线程加入到线程池里
- }
- return NO_ERROR;
- }
进程初始化函数init2,用来启动进程内所有的java服务。
frameworks/base/services/java/com/android/server/SystemServer.java
- public class SystemServer
- {
- public static final void init2() {
- Slog.i(TAG, "Entered the Android system server!");
- Thread thr = new ServerThread(); //创建新线程
- thr.setName("android.server.ServerThread");
- thr.start(); //启动工作线程,在此线程启动各种服务
- }
此工作线程(线程1)实现Java Service注册初始化及进入SystemServer事件处理循环。
- class ServerThread extends Thread {
- @Override
- public void run() {
- Looper.prepare(); //在此线程内处理system server相关消息
- android.os.Process.setThreadPriority(
- android.os.Process.THREAD_PRIORITY_FOREGROUND);
- BinderInternal.disableBackgroundScheduling(true);
- android.os.Process.setCanSelfBackground(false);
- // Critical services...
- try {
- ServiceManager.addService("entropy", new EntropyService()); //注册Service到ServiceManager
- power = new PowerManagerService();
- ServiceManager.addService(Context.POWER_SERVICE, power);
- context = ActivityManagerService.main(factoryTest); //注意:此处启动ActivityManagerService
- ...
- pm = PackageManagerService.main(context,factoryTest != SystemServer.FACTORY_TEST_OFF);
- ActivityManagerService.setSystemProcess();
- ...
- ContentService.main(context,factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
- ActivityManagerService.installSystemProviders()
- ...
- wm = WindowManagerService.main(context, power,factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL); //启动Windows Manager
- ServiceManager.addService(Context.WINDOW_SERVICE, wm);
- ((ActivityManagerService)ServiceManager.getService("activity")).setWindowManager(wm);
- ...
- wm.systemReady(); //通知SystemReady
- power.systemReady();
- try {
- pm.systemReady();
- } catch (RemoteException e) {
- }
- ...
- // 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.
- ((ActivityManagerService)ActivityManagerNative.getDefault())
- .systemReady(new Runnable() {
- public void run() {
- if (statusBarF != null) statusBarF.systemReady2();
- if (batteryF != null) batteryF.systemReady();
- if (connectivityF != null) connectivityF.systemReady();
- if (dockF != null) dockF.systemReady();
- if (usbF != null) usbF.systemReady();
- if (uiModeF != null) uiModeF.systemReady();
- if (recognitionF != null) recognitionF.systemReady();
- Watchdog.getInstance().start();
- // It is now okay to let the various system services start their
- // third party code...
- if (appWidgetF != null) appWidgetF.systemReady(safeMode);
- if (wallpaperF != null) wallpaperF.systemReady();
- if (immF != null) immF.systemReady();
- if (locationF != null) locationF.systemReady();
- if (throttleF != null) throttleF.systemReady();
- }
- ...
- Looper.loop(); //进入循环,处理请求
- }
- }
ActivityManagerService主入口:
frameworks/base/services/java/com/android/server/am/ActivityManagerService.java
- <span style="font-size:18px;"> public static final Context main(int factoryTest) {
- AThread thr = new AThread(); //创建工作线程2
- thr.start(); //启动线程
- synchronized (thr) { //等待</span><span style="font-size:16px;"><span style="font-size:18px;">ActivityManagerService对象创建完成
- while (thr.mService == null) {
- try {
- thr.wait();
- } catch (InterruptedException e) {
- }
- }
- }</span>
- ActivityManagerService m = thr.mService;
- mSelf = m;
- ActivityThread at = ActivityThread.systemMain(); //加载system应用,并把此线程(工作线程1)作为SystemServer进程的system线程
- mSystemThread = at;
- Context context = at.getSystemContext();
- m.mContext = context;
- m.mFactoryTest = factoryTest;
- m.mMainStack = new ActivityStack(m, context, true);
- m.mBatteryStatsService.publish(context);
- m.mUsageStatsService.publish(context);
- synchronized (thr) {
- thr.mReady = true;
- thr.notifyAll();
- }
- m.startRunning(null, null, null, null); //初始化变量并设置system ready为true
- return context;
- }</span>
线程2中作为ActivityManager的工作线程,在其中处理ActivityManager相关的消息。
- static class AThread extends Thread {
- ActivityManagerService mService;
- boolean mReady = false;
- public AThread() {
- super("ActivityManager");
- }
- public void run() {
- Looper.prepare();
- android.os.Process.setThreadPriority(
- android.os.Process.THREAD_PRIORITY_FOREGROUND);
- android.os.Process.setCanSelfBackground(false);
- ActivityManagerService m = new ActivityManagerService();
- synchronized (this) {
- mService = m;
- notifyAll();
- }
- synchronized (this) {
- while (!mReady) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
- }
- }
- Looper.loop();
- }
- }
ActivityThread.systemMain()将加载系统应用apk:
ActivityThread.java
- public static final ActivityThread systemMain() {
- ActivityThread thread = new ActivityThread();
- thread.attach(true); //加载system应用
- return thread;
- }
- private final void attach(boolean system) {
- sThreadLocal.set(this);
- mSystemThread = system;
- if (!system) {...
- } else {
- // Don't set application object here -- if the system crashes,
- // we can't display an alert, we just want to die die die.
- android.ddm.DdmHandleAppName.setAppName("system_process");
- try {
- mInstrumentation = new Instrumentation();
- ContextImpl context = new ContextImpl();
- context.init(getSystemContext().mPackageInfo, null, this);
- Application app = Instrumentation.newApplication(Application.class, context); //创建Application对象并实例化android.app.Application对象
- mAllApplications.add(app);
- mInitialApplication = app;
- app.onCreate(); //调用onCreate
- } catch (Exception e) {
- throw new RuntimeException(
- "Unable to instantiate Application():" + e.toString(), e);
- }
- }
ActivityManagerService.java
- public final void startRunning(String pkg, String cls, String action,
- String data) {
- synchronized(this) {
- if (mStartRunning) {
- return;
- }
- mStartRunning = true;
- mTopComponent = pkg != null && cls != null
- ? new ComponentName(pkg, cls) : null;
- mTopAction = action != null ? action : Intent.ACTION_MAIN;
- mTopData = data;
- if (!mSystemReady) {
- return;
- }
- }
- systemReady(null); //设置system ready为true,但此句似乎无用因为mSystemReady此时必然为true,故调用systemReady(null)什么事也不做
- }
public void systemReady(final Runnable goingCallback) {...
- synchronized(this) {
- if (mSystemReady) {
- if (goingCallback != null) goingCallback.run(); //如果有Runnable要运行
- return;
- }
- // Check to see if there are any update receivers to run.
- if (!mDidUpdate) {
- if (mWaitingUpdate) {
- return;
- }
- Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
- List<ResolveInfo> ris = null;
- try {
- ris = AppGlobals.getPackageManager().queryIntentReceivers(
- intent, null, 0);
- } catch (RemoteException e) {
- }
- if (ris != null) {
- for (int i=ris.size()-1; i>=0; i--) {
- if ((ris.get(i).activityInfo.applicationInfo.flags
- &ApplicationInfo.FLAG_SYSTEM) == 0) {
- ris.remove(i);
- }
- }
- intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
- ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
- final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
- for (int i=0; i<ris.size(); i++) {
- ActivityInfo ai = ris.get(i).activityInfo;
- ComponentName comp = new ComponentName(ai.packageName, ai.name);
- if (lastDoneReceivers.contains(comp)) {
- ris.remove(i);
- i--;
- }
- }
- for (int i=0; i<ris.size(); i++) {
- ActivityInfo ai = ris.get(i).activityInfo;
- ComponentName comp = new ComponentName(ai.packageName, ai.name);
- doneReceivers.add(comp);
- intent.setComponent(comp);
- IIntentReceiver finisher = null;
- if (i == ris.size()-1) {
- finisher = new IIntentReceiver.Stub() {
- public void performReceive(Intent intent, int resultCode,
- String data, Bundle extras, boolean ordered,
- boolean sticky) {
- // The raw IIntentReceiver interface is called
- // with the AM lock held, so redispatch to
- // execute our code without the lock.
- mHandler.post(new Runnable() {
- public void run() {
- synchronized (ActivityManagerService.this) {
- mDidUpdate = true;
- }
- writeLastDonePreBootReceivers(doneReceivers);
- systemReady(goingCallback);
- }
- });
- }
- };
- }
- broadcastIntentLocked(null, null, intent, null, finisher,
- 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID);
- if (finisher != null) {
- mWaitingUpdate = true;
- }
- }
- }
- if (mWaitingUpdate) {
- return;
- }
- mDidUpdate = true;
- }
- mSystemReady = true; //置位
- // silent reboot bit will be off on normal power down
- if (mContext.getResources().getBoolean(com.android.internal.R.bool.config_poweron_sound)) {
- ConfigInfo.pwrSnd_setSilentreboot(1);
- } else if (mContext.getResources()
- .getBoolean(com.android.internal.R.bool.config_mute_poweron_sound)) {
- // Request that the next BootAnimation plays its sound.
- ConfigInfo.pwrSnd_setSilentreboot(0);
- }
- if (!mStartRunning) { //如果ActivityManagerService.startRunning已运行过,则无需继续
- return;
- }
- }
- ArrayList<ProcessRecord> procsToKill = null;
- synchronized(mPidsSelfLocked) {
- for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
- ProcessRecord proc = mPidsSelfLocked.valueAt(i);
- if (!isAllowedWhileBooting(proc.info)){ //检查FLAG_PERSISTENT是否为真
- if (procsToKill == null) {
- procsToKill = new ArrayList<ProcessRecord>();
- }
- procsToKill.add(proc); //如果应用未指明为persistent,则不能在system ready前运行
- }
- }
- }
- 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);
- removeProcessLocked(proc, true); //杀掉所有已运行的非persistent应用
- }
- }
- // Now that we have cleaned up any update processes, we
- // are ready to start launching real processes and know that
- // we won't trample on them any more.
- mProcessesReady = true; //为真时,才允许launch正常的应用
- }...
- synchronized(this) {
- // Make sure we have no pre-ready processes sitting around.
- ...
- retrieveSettings();
- if (goingCallback != null) goingCallback.run();
- synchronized (this) {
- if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
- try {
- List apps = AppGlobals.getPackageManager().
- getPersistentApplications(STOCK_PM_FLAGS);
- if (apps != null) {
- int N = apps.size();
- int i;
- for (i=0; i<N; i++) {
- ApplicationInfo info
- = (ApplicationInfo)apps.get(i);
- if (info != null &&
- !info.packageName.equals("android")) {
- addAppLocked(info); //启动所有标为persistent的且package名字为android的应用
- }
- }
- }
- } catch (RemoteException ex) {
- // pm is in same process, this will never happen.
- }
- }
- // Start up initial activity.
- mBooting = true;
- try {
- if (AppGlobals.getPackageManager().hasSystemUidErrors()) { //如果/data/system文件夹的uid和当前system UID不匹配
- Message msg = Message.obtain();
- msg.what = SHOW_UID_ERROR_MSG;
- mHandler.sendMessage(msg);
- }
- } catch (RemoteException e) {
- }
- mMainStack.resumeTopActivityLocked(null); //启动初始进程Home
- }
- }