Android systemserver 解析
16lz
2021-01-23
System Server是Android系统的核心,他在Dalvik虚拟机启动后立即开始初始化和运行。其它的系统服务在System Server进程的环境中运行。/base/services/java/com/android/server/SystemServer.java
Java代码- /**
- *ThismethodiscalledfromZygotetoinitializethesystem.Thiswillcausethenative
- *services(SurfaceFlinger,AudioFlinger,etc..)tobestarted.Afterthatitwillcallback
- *upintoinit2()tostarttheAndroidservices.
- */
- native public static void init1(String[]args);
- public static void main(String[]args){
- if (System.currentTimeMillis()<EARLIEST_SUPPORTED_TIME){
- //Ifadevice'sclockisbefore1970(before0),alotof
- //APIscrashdealingwithnegativenumbers,notably
- //java.io.File#setLastModified,soinsteadwefakeitand
- //hopethattimefromcelltowersorNTPfixesit
- //shortly.
- Slog.w(TAG,"Systemclockisbefore1970;settingto1970." );
- 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" );
- }
- },SNAPSHOT_INTERVAL,SNAPSHOT_INTERVAL);
- }
- //Thesystemserverhastorunallofthetime,soitneedstobe
- //asefficientaspossiblewithitsmemoryusage.
- VMRuntime.getRuntime().setTargetHeapUtilization(0 .8f);
- System.loadLibrary("android_servers" );
- init1(args);
- }
- public static final void init2(){
- Slog.i(TAG,"EnteredtheAndroidsystemserver!" );
- Threadthr=new ServerThread();
- thr.setName("android.server.ServerThread" );
- thr.start();
- }
在main函数中,首先检查系统时间设置和SamplingProfiler。然后加载一个叫android_servers的本地库,他提供本 地方法的接口(源程序在framework/base/services/jni/目录中)。然后调用本地方法设置服务。具体执行设置的代码在 frameworks/base/cmds/system_server/library/system_init.cpp中。
C代码- extern "C" status_tsystem_init()
- {
- LOGI("Enteredsystem_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){
- //StarttheSurfaceFlinger
- SurfaceFlinger::instantiate();
- }
- //Startthesensorservice
- SensorService::instantiate();
- //Onthesimulator,audioflingeretaldon'tgetstartedthe
- //samewayasonthedevice,andweneedtostartthemhere
- if (!proc->supportsProcesses()){
- //StarttheAudioFlinger
- AudioFlinger::instantiate();
- //Startthemediaplaybackservice
- MediaPlayerService::instantiate();
- //Startthecameraservice
- CameraService::instantiate();
- //Starttheaudiopolicyservice
- AudioPolicyService::instantiate();
- }
- //AndnowstarttheAndroidruntime.Wehavetodothisbit
- //ofnastinessbecausetheAndroidruntimeinitializationrequires
- //someofthecoresystemservicestoalreadybestarted.
- //AllotherserversshouldjuststarttheAndroidruntimeat
- //thebeginningoftheirprocesses'smain(),beforecalling
- //theinitfunction.
- LOGI("Systemserver:startingAndroidruntime.\n" );
- AndroidRuntime*runtime=AndroidRuntime::getRuntime();
- LOGI("Systemserver:startingAndroidservices.\n" );
- runtime->callStatic("com/android/server/SystemServer" , "init2" );
- //Ifrunninginourownprocess,justgointothethread
- //pool.Otherwise,calltheinitializationfinished
- //functoletthisprocesscontinueitsinitilization.
- if (proc->supportsProcesses()){
- LOGI("Systemserver:enteringthreadpool.\n" );
- ProcessState::self()->startThreadPool();
- IPCThreadState::self()->joinThreadPool();
- LOGI("Systemserver:exitingthreadpool.\n" );
- }
- return NO_ERROR;
- }
等初始化传感器,视频,音频等服务后,调用一个回调方法init2 (在SystemServer.java中)。在上面的代码可以看到,这个方法开启了ServerThread来初始化其它的服务。
Java代码- public void run(){
- EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,
- SystemClock.uptimeMillis());
- Looper.prepare();
- android.os.Process.setThreadPriority(
- android.os.Process.THREAD_PRIORITY_FOREGROUND);
- BinderInternal.disableBackgroundScheduling(true );
- android.os.Process.setCanSelfBackground(false );
- //Checkwhetherwefailedtoshutdownlasttimewetried.
- {
- final StringshutdownAction=SystemProperties.get(
- ShutdownThread.SHUTDOWN_ACTION_PROPERTY,"" );
- if (shutdownAction!= null &&shutdownAction.length()> 0 ){
- boolean reboot=(shutdownAction.charAt( 0 )== '1' );
- final Stringreason;
- if (shutdownAction.length()> 1 ){
- reason=shutdownAction.substring(1 ,shutdownAction.length());
- }else {
- reason=null ;
- }
- ShutdownThread.rebootOrShutdown(reboot,reason);
- }
- }
- StringfactoryTestStr=SystemProperties.get("ro.factorytest" );
- int factoryTest= "" .equals(factoryTestStr)?SystemServer.FACTORY_TEST_OFF
- :Integer.parseInt(factoryTestStr);
- LightsServicelights=null ;
- PowerManagerServicepower=null ;
- BatteryServicebattery=null ;
- ConnectivityServiceconnectivity=null ;
- IPackageManagerpm=null ;
- Contextcontext=null ;
- WindowManagerServicewm=null ;
- BluetoothServicebluetooth=null ;
- BluetoothA2dpServicebluetoothA2dp=null ;
- HeadsetObserverheadset=null ;
- DockObserverdock=null ;
- UsbServiceusb=null ;
- UiModeManagerServiceuiMode=null ;
- RecognitionManagerServicerecognition=null ;
- ThrottleServicethrottle=null ;
- //Criticalservices...
- try {
- Slog.i(TAG,"EntropyService" );
- ServiceManager.addService("entropy" , new EntropyService());
- Slog.i(TAG,"PowerManager" );
- power=new PowerManagerService();
- ServiceManager.addService(Context.POWER_SERVICE,power);
- Slog.i(TAG,"ActivityManager" );
- context=ActivityManagerService.main(factoryTest);
- Slog.i(TAG,"TelephonyRegistry" );
- ServiceManager.addService("telephony.registry" , new TelephonyRegistry(context));
- AttributeCache.init(context);
- Slog.i(TAG,"PackageManager" );
- pm=PackageManagerService.main(context,
- factoryTest!=SystemServer.FACTORY_TEST_OFF);
- ActivityManagerService.setSystemProcess();
- mContentResolver=context.getContentResolver();
- //TheAccountManagermustcomebeforetheContentService
- try {
- Slog.i(TAG,"AccountManager" );
- ServiceManager.addService(Context.ACCOUNT_SERVICE,
- new AccountManagerService(context));
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingAccountManager" ,e);
- }
- Slog.i(TAG,"ContentManager" );
- ContentService.main(context,
- factoryTest==SystemServer.FACTORY_TEST_LOW_LEVEL);
- Slog.i(TAG,"SystemContentProviders" );
- ActivityManagerService.installSystemProviders();
- Slog.i(TAG,"BatteryService" );
- battery=new BatteryService(context);
- ServiceManager.addService("battery" ,battery);
- Slog.i(TAG,"LightsService" );
- lights=new LightsService(context);
- Slog.i(TAG,"VibratorService" );
- ServiceManager.addService("vibrator" , new VibratorService(context));
- //onlyinitializethepowerserviceafterwehavestartedthe
- //lightsservice,contentprovidersandthebatteryservice.
- power.init(context,lights,ActivityManagerService.getDefault(),battery);
- Slog.i(TAG,"AlarmManager" );
- AlarmManagerServicealarm=new AlarmManagerService(context);
- ServiceManager.addService(Context.ALARM_SERVICE,alarm);
- Slog.i(TAG,"InitWatchdog" );
- Watchdog.getInstance().init(context,battery,power,alarm,
- ActivityManagerService.self());
- Slog.i(TAG,"WindowManager" );
- wm=WindowManagerService.main(context,power,
- factoryTest!=SystemServer.FACTORY_TEST_LOW_LEVEL);
- ServiceManager.addService(Context.WINDOW_SERVICE,wm);
- ((ActivityManagerService)ServiceManager.getService("activity" ))
- .setWindowManager(wm);
- //SkipBluetoothifwehaveanemulatorkernel
- //TODO:Useamorereliablechecktoseeifthisproductshould
- //supportBluetooth-seebug988521
- if (SystemProperties.get( "ro.kernel.qemu" ).equals( "1" )){
- Slog.i(TAG,"RegisteringnullBluetoothService(emulator)" );
- ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE,null );
- }else if (factoryTest==SystemServer.FACTORY_TEST_LOW_LEVEL){
- Slog.i(TAG,"RegisteringnullBluetoothService(factorytest)" );
- ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE,null );
- }else {
- Slog.i(TAG,"BluetoothService" );
- bluetooth=new BluetoothService(context);
- ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE,bluetooth);
- bluetooth.initAfterRegistration();
- bluetoothA2dp=new BluetoothA2dpService(context,bluetooth);
- ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,
- bluetoothA2dp);
- int bluetoothOn=Settings.Secure.getInt(mContentResolver,
- Settings.Secure.BLUETOOTH_ON,0 );
- if (bluetoothOn> 0 ){
- bluetooth.enable();
- }
- }
- }catch (RuntimeExceptione){
- Slog.e("System" , "Failurestartingcoreservice" ,e);
- }
- DevicePolicyManagerServicedevicePolicy=null ;
- StatusBarManagerServicestatusBar=null ;
- InputMethodManagerServiceimm=null ;
- AppWidgetServiceappWidget=null ;
- NotificationManagerServicenotification=null ;
- WallpaperManagerServicewallpaper=null ;
- LocationManagerServicelocation=null ;
- if (factoryTest!=SystemServer.FACTORY_TEST_LOW_LEVEL){
- try {
- Slog.i(TAG,"DevicePolicy" );
- devicePolicy=new DevicePolicyManagerService(context);
- ServiceManager.addService(Context.DEVICE_POLICY_SERVICE,devicePolicy);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingDevicePolicyService" ,e);
- }
- try {
- Slog.i(TAG,"StatusBar" );
- statusBar=new StatusBarManagerService(context);
- ServiceManager.addService(Context.STATUS_BAR_SERVICE,statusBar);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingStatusBarManagerService" ,e);
- }
- try {
- Slog.i(TAG,"ClipboardService" );
- ServiceManager.addService(Context.CLIPBOARD_SERVICE,
- new ClipboardService(context));
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingClipboardService" ,e);
- }
- try {
- Slog.i(TAG,"InputMethodService" );
- imm=new InputMethodManagerService(context,statusBar);
- ServiceManager.addService(Context.INPUT_METHOD_SERVICE,imm);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingInputManagerService" ,e);
- }
- try {
- Slog.i(TAG,"NetStatService" );
- ServiceManager.addService("netstat" , new NetStatService(context));
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingNetStatService" ,e);
- }
- try {
- Slog.i(TAG,"NetworkManagementService" );
- ServiceManager.addService(
- Context.NETWORKMANAGEMENT_SERVICE,
- NetworkManagementService.create(context));
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingNetworkManagementService" ,e);
- }
- try {
- Slog.i(TAG,"ConnectivityService" );
- connectivity=ConnectivityService.getInstance(context);
- ServiceManager.addService(Context.CONNECTIVITY_SERVICE,connectivity);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingConnectivityService" ,e);
- }
- try {
- Slog.i(TAG,"ThrottleService" );
- throttle=new ThrottleService(context);
- ServiceManager.addService(
- Context.THROTTLE_SERVICE,throttle);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingThrottleService" ,e);
- }
- try {
- Slog.i(TAG,"AccessibilityManager" );
- ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
- new AccessibilityManagerService(context));
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingAccessibilityManager" ,e);
- }
- try {
- /*
- *NotificationManagerServiceisdependantonMountService,
- *(formedia/usbnotifications)sowemuststartMountServicefirst.
- */
- Slog.i(TAG,"MountService" );
- ServiceManager.addService("mount" , new MountService(context));
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingMountService" ,e);
- }
- try {
- Slog.i(TAG,"NotificationManager" );
- notification=new NotificationManagerService(context,statusBar,lights);
- ServiceManager.addService(Context.NOTIFICATION_SERVICE,notification);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingNotificationManager" ,e);
- }
- try {
- Slog.i(TAG,"DeviceStorageMonitor" );
- ServiceManager.addService(DeviceStorageMonitorService.SERVICE,
- new DeviceStorageMonitorService(context));
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingDeviceStorageMonitorservice" ,e);
- }
- try {
- Slog.i(TAG,"LocationManager" );
- location=new LocationManagerService(context);
- ServiceManager.addService(Context.LOCATION_SERVICE,location);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingLocationManager" ,e);
- }
- try {
- Slog.i(TAG,"SearchService" );
- ServiceManager.addService(Context.SEARCH_SERVICE,
- new SearchManagerService(context));
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingSearchService" ,e);
- }
- if (INCLUDE_DEMO){
- Slog.i(TAG,"Installingdemodata..." );
- (new DemoThread(context)).start();
- }
- try {
- Slog.i(TAG,"DropBoxService" );
- ServiceManager.addService(Context.DROPBOX_SERVICE,
- new DropBoxManagerService(context, new File( "/data/system/dropbox" )));
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingDropBoxManagerService" ,e);
- }
- try {
- Slog.i(TAG,"WallpaperService" );
- wallpaper=new WallpaperManagerService(context);
- ServiceManager.addService(Context.WALLPAPER_SERVICE,wallpaper);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingWallpaperService" ,e);
- }
- try {
- Slog.i(TAG,"AudioService" );
- ServiceManager.addService(Context.AUDIO_SERVICE,new AudioService(context));
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingAudioService" ,e);
- }
- try {
- Slog.i(TAG,"HeadsetObserver" );
- //Listenforwiredheadsetchanges
- headset=new HeadsetObserver(context);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingHeadsetObserver" ,e);
- }
- try {
- Slog.i(TAG,"DockObserver" );
- //Listenfordockstationchanges
- dock=new DockObserver(context,power);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingDockObserver" ,e);
- }
- try {
- Slog.i(TAG,"USBService" );
- //ListenforUSBchanges
- usb=new UsbService(context);
- ServiceManager.addService(Context.USB_SERVICE,usb);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingUsbService" ,e);
- }
- try {
- Slog.i(TAG,"UIModeManagerService" );
- //ListenforUImodechanges
- uiMode=new UiModeManagerService(context);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingUiModeManagerService" ,e);
- }
- try {
- Slog.i(TAG,"BackupService" );
- ServiceManager.addService(Context.BACKUP_SERVICE,
- new BackupManagerService(context));
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingBackupService" ,e);
- }
- try {
- Slog.i(TAG,"AppWidgetService" );
- appWidget=new AppWidgetService(context);
- ServiceManager.addService(Context.APPWIDGET_SERVICE,appWidget);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingAppWidgetService" ,e);
- }
- try {
- Slog.i(TAG,"RecognitionService" );
- recognition=new RecognitionManagerService(context);
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingRecognitionService" ,e);
- }
- try {
- Slog.i(TAG,"DiskStatsService" );
- ServiceManager.addService("diskstats" , new DiskStatsService(context));
- }catch (Throwablee){
- Slog.e(TAG,"FailurestartingDiskStatsService" ,e);
- }
- }
- //makesuretheADB_ENABLEDsettingvaluematchesthesecurepropertyvalue
- Settings.Secure.putInt(mContentResolver,Settings.Secure.ADB_ENABLED,
- "1" .equals(SystemProperties.get( "persist.service.adb.enable" ))? 1 : 0 );
- //registerobservertolistenforsettingschanges
- mContentResolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.ADB_ENABLED),
- false , new AdbSettingsObserver());
- //Beforethingsstartrolling,besurewehavedecidedwhether
- //weareinsafemode.
- final boolean safeMode=wm.detectSafeMode();
- if (safeMode){
- try {
- ActivityManagerNative.getDefault().enterSafeMode();
- //PostthesafemodestateintheZygoteclass
- Zygote.systemInSafeMode=true ;
- //DisabletheJITforthesystem_serverprocess
- VMRuntime.getRuntime().disableJitCompilation();
- }catch (RemoteExceptione){
- }
- }else {
- //EnabletheJITforthesystem_serverprocess
- VMRuntime.getRuntime().startJitCompilation();
- }
- //Itisnowtimetostartuptheappprocesses...
- if (devicePolicy!= null ){
- devicePolicy.systemReady();
- }
- if (notification!= null ){
- notification.systemReady();
- }
- if (statusBar!= null ){
- statusBar.systemReady();
- }
- wm.systemReady();
- power.systemReady();
- try {
- pm.systemReady();
- }catch (RemoteExceptione){
- }
- //Theseareneededtopropagatetotherunnablebelow.
- final StatusBarManagerServicestatusBarF=statusBar;
- final BatteryServicebatteryF=battery;
- final ConnectivityServiceconnectivityF=connectivity;
- final DockObserverdockF=dock;
- final UsbServiceusbF=usb;
- final ThrottleServicethrottleF=throttle;
- final UiModeManagerServiceuiModeF=uiMode;
- final AppWidgetServiceappWidgetF=appWidget;
- final WallpaperManagerServicewallpaperF=wallpaper;
- final InputMethodManagerServiceimmF=imm;
- final RecognitionManagerServicerecognitionF=recognition;
- final LocationManagerServicelocationF=location;
- //Wenowtelltheactivitymanageritisokaytorunthirdparty
- //code.Itwillcallbackintousonceithasgottentothestate
- //wherethirdpartycodecanreallyrun(butbeforeithasactually
- //startedlaunchingtheinitialapplications),forustocompleteour
- //initialization.
- ((ActivityManagerService)ActivityManagerNative.getDefault())
- .systemReady(new Runnable(){
- public void run(){
- Slog.i(TAG,"Makingservicesready" );
- 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();
- //Itisnowokaytoletthevarioussystemservicesstarttheir
- //thirdpartycode...
- 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();
- }
- });
- //Fordebugbuilds,logeventloopstallstodropboxforanalysis.
- if (StrictMode.conditionallyEnableDebugLogging()){
- Slog.i(TAG,"EnabledStrictModeforsystemservermainthread." );
- }
- Looper.loop();
- Slog.d(TAG,"SystemServerThreadisexiting!" );
- }
这里启动的没一个进程都作为一个Dalvik线程而存在于SystemServer进程里面。
更多相关文章
- Android软键盘挡住输入框的问题及解决方法
- Android Studio制作简易计算器源代码及详解
- Android 代码实现logcat输出到文件
- Android ColorStateList使用方法
- 修改android项目sdk版本的方法
- Android,TextView的所有属性和方法