Android系统之SystemServer

come from : https://www.jianshu.com/p/ed798bc172f2

在上一文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世界的两大支柱

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值