Android系統之SystemServer

在上一文Android 系統的Zygote初始化過程說到,Zygote初始化的時候會調用RuntimeInit裏面的zygoteInit()方法,在該方法裏面調用了applicationInit()方法,然後通過反射調用了SystemServermain()函數。

SystemServer

SystemServermain函數如下

//frameworks/base/ android-7.1.2_r36/services /java/com/android/SystemServer.java
  public static void main(String[] args) {
        new SystemServer().run();
  }

創建一個SystemServer對象,同時執行run()方法。接下來就是來到run()方法


//frameworks/base/ android-7.1.2_r36/services /java/com/android/SystemServer.java
private void run() {
//...
    System.loadLibrary("android_servers");
    createSystemContext();
    mSystemServiceManager = new SystemServiceManager(mSystemContext);
    mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
//...
}

主要有上面幾個方法
1. 加載了libandroid_servers.so,方法主要對應com_android_server_systemserver,com_android_server_systemserver主要有以下幾個方法:
- start_sensor_service 初始化手機傳感器服務SensorService,並且添加到BinderService

static int start_sensor_service(void* /*unused*/) {
    SensorService::instantiate();`frameworks/native/services/sensorservice/SensorService.h`
    return 0;
}

SensorService.h繼承於BinderService,BnSensorServer,ThreadBinderService 相關代碼如下

//`frameworks/native/include/binder/BinderService.h`
static status_t publish(bool allowIsolated = false) {
        sp<IServiceManager> sm(defaultServiceManager());
        return sm->addService(
                String16(SERVICE::getServiceName()),
                new SERVICE(), allowIsolated);
    }
    static void publishAndJoinThreadPool(bool allowIsolated = false) {
        publish(allowIsolated);
        joinThreadPool();
    }
    static void instantiate() { publish(); }

instantiate調用了publish方法,在publish方法中主要把SensorService服務添加到ServiceManager,ServiceManagerBinder架構組成的組件之一,它是Binder的守護進程,主要維護和管理創建的各種Service

  • android_server_SystemServer_startSensorService
static void android_server_SystemServer_startSensorService(JNIEnv* /* env */, jobject /* clazz */) {
    char propBuf[PROPERTY_VALUE_MAX];
    property_get("system_init.startsensorservice", propBuf, "1");
    if (strcmp(propBuf, "1") == 0) {
        // Start the sensor service in a new thread
        createThreadEtc(start_sensor_service, nullptr,
                        "StartSensorThread", PRIORITY_FOREGROUND);
    }
}

異步啓動手機傳感器服務SensorService的JNI方法

  • register_android_server_SystemServer
int register_android_server_SystemServer(JNIEnv* env)
{
    return jniRegisterNativeMethods(env, "com/android/server/SystemServer",
            gMethods, NELEM(gMethods));
}

通過jni註冊android_server_SystemServer_startSensorService方法,提供給給底層調用該方法啓動傳感器服務

  1. createSystemContext()方法

    // frameworks/base/ android-7.1.2_r36/core/java/android/app/ActivityThread.java
    private void createSystemContext() {
        ActivityThread activityThread = ActivityThread.systemMain();
        mSystemContext = activityThread.getSystemContext();
        mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
    }

    這裏涉及到ActivityThreadActivityThread主要管理應用進程的UI線程的執行,依次產生activities,broadcasts,或者一些其他的操作請求,這裏主要的作用是創建Context。代碼如下

//....
 android.ddm.DdmHandleAppName.setAppName("system_process",
                    UserHandle.myUserId());
            try {
                mInstrumentation = new Instrumentation();
                ContextImpl context = ContextImpl.createAppContext(
                        this, getSystemContext().mLoadedApk);
                mInitialApplication = context.mLoadedApk.makeApplication(true, null);
                mInitialApplication.onCreate();
            } catch (Exception e) {
                throw new RuntimeException(
                        "Unable to instantiate Application():" + e.toString(), e);
            }
//....
  • 設置ddms的應用進程號
  • 通過ContextImpl創建Context
  • 初始化Application,同時調用ApplicationonCreate方法

    1. 創建SystemServiceManager
//...
       mSystemServiceManager = new SystemServiceManager(mSystemContext);
       mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
       LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
//...

創建system service manager並且添加到LocalServicesSystemServiceManager源碼位於SystemService同目錄下面,注意SystemServerSystemService的區別,SystemServer產生Android的各種服務,SystemService維護Service的生命週期的一個抽象類。它主要是通過ArrayList保存SystemService,在調用裏面startService方法的時候添加並且開始執行運行


 @SuppressWarnings("unchecked")
    public <T extends SystemService> T startService(Class<T> serviceClass) {
        try {
          //...
            // Register it.
            mServices.add(service);
            // Start it.
            try {
                service.onStart();
            } catch (RuntimeException ex) {
                throw new RuntimeException("Failed to start service " + name
                        + ": onStart threw an exception", ex);
            }
            return service;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }

LocalServices指的是本地服務,它跟隨主進程,不是一個獨立的進程。主進程結束後,相應的本地服務也會相應的結束。主要定義了一個ArrayMap來保存本地服務。

private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =
            new ArrayMap<Class<?>, Object>();
  1. 啓動一些其他服務
//...
 try {
            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
            startBootstrapServices();
            startCoreServices();
            startOtherServices();
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
//...
  • startBootstrapServices,代碼如下
  private void startBootstrapServices() {
        //...
        mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
          //...
        mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
        //...
        mSystemServiceManager.startService(LightsService.class);
        //...
        mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
     //...
        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    //...
        if (!mOnlyCore) {
            boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
                    false);
            if (!disableOtaDexopt) {
                traceBeginAndSlog("StartOtaDexOptService");
                try {
                    OtaDexoptService.main(mSystemContext, mPackageManagerService);
                } catch (Throwable e) {
                    reportWtf("starting OtaDexOptService", e);
                } finally {
                    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
                }
            }
        }
        //...
        mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
            //...
        startSensorService();
    }

通過SystemServiceManagerstartService方法,啓動了ActivityManagerServicePowerManagerService,LightsServiceDisplayManagerService,PackageManagerServiceOtaDexoptServiceSensorService等等

  • startCoreServices 代碼如下
private void startCoreServices() {
        mSystemServiceManager.startService(BatteryService.class);
        mSystemServiceManager.startService(UsageStatsService.class);
        mActivityManagerService.setUsageStatsManager(
                LocalServices.getService(UsageStatsManagerInternal.class));
        // Tracks whether the updatable WebView is in a ready state and watches for update installs.
        mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
    }

也是通過SystemServiceManagerstartService方法,啓動了BatteryServiceUsageStatsService,LightsServiceDisplayManagerService,UsageStatsManagerInternalWebViewUpdateService等等

  • startOtherServices 代碼如下
    private void startOtherServices() {
        final Context context = mSystemContext;
        VibratorService vibrator = null;
        IMountService mountService = null;
        NetworkManagementService networkManagement = null;
        NetworkStatsService networkStats = null;
        NetworkPolicyManagerService networkPolicy = null;
        ConnectivityService connectivity = null;
        NetworkScoreService networkScore = null;
        NsdService serviceDiscovery= null;
        WindowManagerService wm = null;
        SerialService serial = null;
        NetworkTimeUpdateService networkTimeUpdater = null;
        CommonTimeManagementService commonTimeMgmtService = null;
        InputManagerService inputManager = null;
        TelephonyRegistry telephonyRegistry = null;
        ConsumerIrService consumerIr = null;
        MmsServiceBroker mmsService = null;
        HardwarePropertiesManagerService hardwarePropertiesService = null;

        StatusBarManagerService statusBar = null;
        INotificationManager notification = null;
        LocationManagerService location = null;
        CountryDetectorService countryDetector = null;
        ILockSettings lockSettings = null;
        AssetAtlasService atlas = null;
        MediaRouterService mediaRouter = null;
//...
}

這裏就是Android的各種Service了。

總的來說SystemServerAndroid提供了各種Service服務,它和Zygote號稱Android世界的兩大支柱

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章