Android 5.1 SystemServer SystemService 各个系统Manager

一、SystemServer

Zygote如何启动SystemServer就不分析了,主要分析下java层:

先看下主函数

  1. public static void main(String[] args) {  
  2.     new SystemServer().run();  
  3. }  

下面我们看run函数里面的java service的启动:

  1. mSystemServiceManager = new SystemServiceManager(mSystemContext);  
  2. LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);  
  3.   
  4. // Start services.  
  5. try {  
  6.     startBootstrapServices();  
  7.     startCoreServices();  
  8.     startOtherServices();  
  9. catch (Throwable ex) {  
  10.     Slog.e("System""******************************************");  
  11.     Slog.e("System""************ Failure starting system services", ex);  
  12.     throw ex;  
  13. }  

SystemServiceManager这个类只是管理各个service,用SystemServiceManager启动service的时候,会把service加入自己的链表。并且调用service的onStart函数。

  1. public <T extends SystemService> T startService(Class<T> serviceClass) {  
  2.     final String name = serviceClass.getName();  
  3.     Slog.i(TAG, "Starting " + name);  
  4.   
  5.     // Create the service.  
  6.     if (!SystemService.class.isAssignableFrom(serviceClass)) {  
  7.         throw new RuntimeException("Failed to create " + name  
  8.                 + ": service must extend " + SystemService.class.getName());  
  9.     }  
  10.     final T service;  
  11.     try {  
  12.         Constructor<T> constructor = serviceClass.getConstructor(Context.class);  
  13.         service = constructor.newInstance(mContext);  
  14.     } catch (InstantiationException ex) {  
  15.         throw new RuntimeException("Failed to create service " + name  
  16.                 + ": service could not be instantiated", ex);  
  17.     } catch (IllegalAccessException ex) {  
  18.         throw new RuntimeException("Failed to create service " + name  
  19.                 + ": service must have a public constructor with a Context argument", ex);  
  20.     } catch (NoSuchMethodException ex) {  
  21.         throw new RuntimeException("Failed to create service " + name  
  22.                 + ": service must have a public constructor with a Context argument", ex);  
  23.     } catch (InvocationTargetException ex) {  
  24.         throw new RuntimeException("Failed to create service " + name  
  25.                 + ": service constructor threw an exception", ex);  
  26.     }  
  27.   
  28.     // Register it.  
  29.     mServices.add(service);//加入链表  
  30.   
  31.     // Start it.  
  32.     try {  
  33.         service.onStart();//调用service的onStart函数  
  34.     } catch (RuntimeException ex) {  
  35.         throw new RuntimeException("Failed to start service " + name  
  36.                 + ": onStart threw an exception", ex);  
  37.     }  
  38.     return service;  
  39. }  

SystemServer每执行到一个阶段都会调用SystemServiceManager的startBootPhase函数

  1. mActivityManagerService = mSystemServiceManager.startService(  
  2.         ActivityManagerService.Lifecycle.class).getService();  
  3. mActivityManagerService.setSystemServiceManager(mSystemServiceManager);  
  4. mActivityManagerService.setInstaller(installer);  
  5.   
  6. // Power manager needs to be started early because other services need it.  
  7. // Native daemons may be watching for it to be registered so it must be ready  
  8. // to handle incoming binder calls immediately (including being able to verify  
  9. // the permissions for those calls).  
  10. mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);  
  11.   
  12. // Now that the power manager has been started, let the activity manager  
  13. // initialize power management features.  
  14. mActivityManagerService.initPowerManagement();  
  15.   
  16. // Display manager is needed to provide display metrics before package manager  
  17. // starts up.  
  18. mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);  
  19.   
  20. // We need the default display before we can initialize the package manager.  
  21. mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);  

我们下面看下SystemServiceManager的startBootPhase函数,它会把mServices中的service取出来,调用onBootPhase函数

  1. public void startBootPhase(final int phase) {  
  2.     if (phase <= mCurrentPhase) {  
  3.         throw new IllegalArgumentException("Next phase must be larger than previous");  
  4.     }  
  5.     mCurrentPhase = phase;  
  6.   
  7.     Slog.i(TAG, "Starting phase " + mCurrentPhase);  
  8.   
  9.     final int serviceLen = mServices.size();  
  10.     for (int i = 0; i < serviceLen; i++) {  
  11.         final SystemService service = mServices.get(i);  
  12.         try {  
  13.             service.onBootPhase(mCurrentPhase);  
  14.         } catch (Exception ex) {  
  15.             throw new RuntimeException("Failed to boot service "  
  16.                     + service.getClass().getName()  
  17.                     + ": onBootPhase threw an exception during phase "  
  18.                     + mCurrentPhase, ex);  
  19.         }  
  20.     }  
  21. }  


二、SystemService

我们再来SystemService这个类,这个类一般是一些系统service来继承这个类

先看看PowerManagerService

  1. public final class PowerManagerService extends SystemService  
  2.         implements Watchdog.Monitor {  

其中实现了onStart和onBootPhase函数

扫描二维码关注公众号,回复: 592827 查看本文章
  1. @Override  
  2. public void onStart() {  
  3.     publishBinderService(Context.POWER_SERVICE, new BinderService());  
  4.     publishLocalService(PowerManagerInternal.classnew LocalService());  
  5.   
  6.     Watchdog.getInstance().addMonitor(this);  
  7.     Watchdog.getInstance().addThread(mHandler);  
  8. }  
  9.   
  10. @Override  
  11. public void onBootPhase(int phase) {  
  12.     synchronized (mLock) {  
  13.         if (phase == PHASE_BOOT_COMPLETED) {  
  14.             final long now = SystemClock.uptimeMillis();  
  15.             mBootCompleted = true;  
  16.             mDirty |= DIRTY_BOOT_COMPLETED;  
  17.             userActivityNoUpdateLocked(  
  18.                     now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);  
  19.             updatePowerStateLocked();  
  20.         }  
  21.     }  
  22. }  

其中publishBinderService函数是SystemService中的函数,最后是调用了ServiceManager.addService。

  1. protected final void publishBinderService(String name, IBinder service) {  
  2.     publishBinderService(name, service, false);  
  3. }  
  4.   
  5. /** 
  6.  * Publish the service so it is accessible to other services and apps. 
  7.  */  
  8. protected final void publishBinderService(String name, IBinder service,  
  9.         boolean allowIsolated) {  
  10.     ServiceManager.addService(name, service, allowIsolated);  
  11. }  


三、ServiceManager

而ServiceManager 这个类,是java层用来和serviceManager进程通信的。

  1. public final class ServiceManager {  
  2.     private static final String TAG = "ServiceManager";  
  3.   
  4.     private static IServiceManager sServiceManager;  
  5.     private static HashMap<String, IBinder> sCache = new HashMap<String, IBinder>();  
  6.   
  7.     private static IServiceManager getIServiceManager() {  
  8.         if (sServiceManager != null) {  
  9.             return sServiceManager;  
  10.         }  
  11.   
  12.         // Find the service manager  
  13.         sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());  
  14.         return sServiceManager;  
  15.     }  
  16.   
  17.     /** 
  18.      * Returns a reference to a service with the given name. 
  19.      *  
  20.      * @param name the name of the service to get 
  21.      * @return a reference to the service, or <code>null</code> if the service doesn't exist 
  22.      */  
  23.     public static IBinder getService(String name) {  
  24.         try {  
  25.             IBinder service = sCache.get(name);  
  26.             if (service != null) {  
  27.                 return service;  
  28.             } else {  
  29.                 return getIServiceManager().getService(name);  
  30.             }  
  31.         } catch (RemoteException e) {  
  32.             Log.e(TAG, "error in getService", e);  
  33.         }  
  34.         return null;  
  35.     }  
  36.   
  37.     /** 
  38.      * Place a new @a service called @a name into the service 
  39.      * manager. 
  40.      *  
  41.      * @param name the name of the new service 
  42.      * @param service the service object 
  43.      */  
  44.     public static void addService(String name, IBinder service) {  
  45.         try {  
  46.             getIServiceManager().addService(name, service, false);  
  47.         } catch (RemoteException e) {  
  48.             Log.e(TAG, "error in addService", e);  
  49.         }  
  50.     }  


四、系统的各个Manager

再来看看ContextImpl里面对各个Manager的注册,下面是PMS的注册

  1. registerService(POWER_SERVICE, new ServiceFetcher() {  
  2.         public Object createService(ContextImpl ctx) {  
  3.             IBinder b = ServiceManager.getService(POWER_SERVICE);  
  4.             IPowerManager service = IPowerManager.Stub.asInterface(b);  
  5.             if (service == null) {  
  6.                 Log.wtf(TAG, "Failed to get power manager service.");  
  7.             }  
  8.             return new PowerManager(ctx.getOuterContext(),  
  9.                     service, ctx.mMainThread.getHandler());  
  10.         }});  
再来看看getSystemService,比如获取PowerManager等
  1. @Override  
  2. public Object getSystemService(String name) {  
  3.     ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);  
  4.     return fetcher == null ? null : fetcher.getService(this);  
  5. }  
下面ServiceFetcher 中createService就是上面在注册各个Manager的时候定义的。
  1. /*package*/ static class ServiceFetcher {  
  2.     int mContextCacheIndex = -1;  
  3.   
  4.     /** 
  5.      * Main entrypoint; only override if you don't need caching. 
  6.      */  
  7.     public Object getService(ContextImpl ctx) {  
  8.         ArrayList<Object> cache = ctx.mServiceCache;  
  9.         Object service;  
  10.         synchronized (cache) {  
  11.             if (cache.size() == 0) {  
  12.                 // Initialize the cache vector on first access.  
  13.                 // At this point sNextPerContextServiceCacheIndex  
  14.                 // is the number of potential services that are  
  15.                 // cached per-Context.  
  16.                 for (int i = 0; i < sNextPerContextServiceCacheIndex; i++) {  
  17.                     cache.add(null);  
  18.                 }  
  19.             } else {  
  20.                 service = cache.get(mContextCacheIndex);  
  21.                 if (service != null) {  
  22.                     return service;  
  23.                 }  
  24.             }  
  25.             service = createService(ctx);  
  26.             cache.set(mContextCacheIndex, service);  
  27.             return service;  
  28.         }  
  29.     }  
  30.   
  31.     /** 
  32.      * Override this to create a new per-Context instance of the 
  33.      * service.  getService() will handle locking and caching. 
  34.      */  
  35.     public Object createService(ContextImpl ctx) {  
  36.         throw new RuntimeException("Not implemented");  
  37.     }  
  38. }  

猜你喜欢

转载自blog.csdn.net/u010144805/article/details/80051069