日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > Android >内容正文

Android

Android SystemServiceManager分析

發(fā)布時(shí)間:2025/3/15 Android 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android SystemServiceManager分析 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1. SystemServiceManger啟動(dòng)

分析過(guò)SystemServer的朋友應(yīng)該都有記憶,SystemServiceManager就是在SystemServer中啟動(dòng)的,下面是SystemServiceManager的啟動(dòng)代碼:

[SystemServer.java] // Create the system service manager. mSystemServiceManager = new SystemServiceManager(mSystemContext); LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

這里直接通過(guò)new一個(gè)SystemServiceManager對(duì)象,然后將新new的對(duì)象保存到mSystemServiceManager中,以備后用。

??SystemServiceManager的代碼如下:

public SystemServiceManager(Context context) {mContext = context; }

這里只要將context保存到mContext中即可,現(xiàn)在SystemServiceManager就初始化完畢了。

2. SystemServiceManager代碼分析

2.1 SystemServiceManager中的startService函數(shù)

/*** Starts a service by class name.** @return The service instance.*/ @SuppressWarnings("unchecked") public SystemService startService(String className) {// SystemrService類的class對(duì)象final Class<SystemService> serviceClass;try {// 通過(guò)Class.forName,傳入String型類名,得到對(duì)應(yīng)類名的class對(duì)象serviceClass = (Class<SystemService>)Class.forName(className);} catch (ClassNotFoundException ex) {Slog.i(TAG, "Starting " + className);throw new RuntimeException("Failed to create service " + className+ ": service class not found, usually indicates that the caller should "+ "have called PackageManager.hasSystemFeature() to check whether the "+ "feature is available on this device before trying to start the "+ "services that implement it", ex);}// 調(diào)用另一個(gè)startService重載函數(shù)return startService(serviceClass); }/*** Creates and starts a system service. The class must be a subclass of* {@link com.android.server.SystemService}.** @param serviceClass A Java class that implements the SystemService interface.* @return The service instance, never null.* @throws RuntimeException if the service fails to start.*/ @SuppressWarnings("unchecked") // 模板類函數(shù),其中serviceClass必須是SystemService的子類 public <T extends SystemService> T startService(Class<T> serviceClass) {final String name = serviceClass.getName();Slog.i(TAG, "Starting " + name);// Create the service.// 再次確認(rèn)serviceClass是SystemService的子類if (!SystemService.class.isAssignableFrom(serviceClass)) {throw new RuntimeException("Failed to create " + name+ ": service must extend " + SystemService.class.getName());}final T service;try {// 獲取service的構(gòu)造函數(shù)Constructor<T> constructor = serviceClass.getConstructor(Context.class);// 創(chuàng)建service對(duì)象service = constructor.newInstance(mContext);} catch (InstantiationException ex) {throw new RuntimeException("Failed to create service " + name+ ": service could not be instantiated", ex);} catch (IllegalAccessException ex) {throw new RuntimeException("Failed to create service " + name+ ": service must have a public constructor with a Context argument", ex);} catch (NoSuchMethodException ex) {throw new RuntimeException("Failed to create service " + name+ ": service must have a public constructor with a Context argument", ex);} catch (InvocationTargetException ex) {throw new RuntimeException("Failed to create service " + name+ ": service constructor threw an exception", ex);}// Register it.// 將service添加到mServices ArrayList中mServices.add(service);// Start it.try {// 啟動(dòng)serviceservice.onStart();} catch (RuntimeException ex) {throw new RuntimeException("Failed to start service " + name+ ": onStart threw an exception", ex);}return service; }

2.2 SystemServiceManager中的startBootPhase函數(shù)

/*** Starts the specified boot phase for all system services that have been started up to* this point.** @param phase The boot phase to start.*/ public void startBootPhase(final int phase) {if (phase <= mCurrentPhase) {throw new IllegalArgumentException("Next phase must be larger than previous");}mCurrentPhase = phase;Slog.i(TAG, "Starting phase " + mCurrentPhase);// 輪詢mServices中所有的servicefinal int serviceLen = mServices.size();for (int i = 0; i < serviceLen; i++) {final SystemService service = mServices.get(i);try {/// M: Service operation time log @{long startTime = 0;if (!IS_USER_BUILD) startTime = SystemClock.elapsedRealtime();/// @}// 調(diào)用service的onBootPhase方法service.onBootPhase(mCurrentPhase);/// M: Service operation time log @{if (!IS_USER_BUILD) {checkTime(startTime, "Phase " + mCurrentPhase, service.getClass().getName());}/// @}} catch (Exception ex) {throw new RuntimeException("Failed to boot service "+ service.getClass().getName()+ ": onBootPhase threw an exception during phase "+ mCurrentPhase, ex);}} }

??startBootPhase也比較簡(jiǎn)單,因?yàn)橛行﹕ervice的啟動(dòng)需要以來(lái)其他的service,所以Systemserver會(huì)將設(shè)備啟動(dòng)分成幾個(gè)階段,每個(gè)階段啟動(dòng)不同的service,而這些就是由startBootPhase這個(gè)方法來(lái)實(shí)現(xiàn)的。如果檢測(cè)到當(dāng)前的phase達(dá)到service的設(shè)定值,service就會(huì)完成相應(yīng)的工作。下面是BatteryService的onBootPhase方法,可以知道當(dāng)設(shè)備啟動(dòng)到PHASE_ACTIVITY_MANAGER_READY,該方法就會(huì)調(diào)用執(zhí)行相應(yīng)的操作。

public void onBootPhase(int phase) {if (phase == PHASE_ACTIVITY_MANAGER_READY) {// check our power situation now that it is safe to display the shutdown dialog.synchronized (mLock) {mBootCompleted = true;ContentObserver obs = new ContentObserver(mHandler) {@Overridepublic void onChange(boolean selfChange) {synchronized (mLock) {updateBatteryWarningLevelLocked();}}};final ContentResolver resolver = mContext.getContentResolver();resolver.registerContentObserver(Settings.Global.getUriFor(Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL),false, obs, UserHandle.USER_ALL);updateBatteryWarningLevelLocked();}} }

2.3 SystemServiceManager中剩余關(guān)于user的函數(shù)

??SystemServiceManager中剩余一下關(guān)于特定user的函數(shù),具體的使用場(chǎng)景在SystemService.java中有描述,大家可以看下面代碼中的注釋,簡(jiǎn)單明了。

/*** Called when switching to a different foreground user, for system services that have* special behavior for whichever user is currently in the foreground. This is called* before any application processes are aware of the new user.* @param userHandle The identifier of the user.*/ public void onSwitchUser(int userHandle) {}/*** Called when an existing user is stopping, for system services to finalize any per-user* state they maintain for running users. This is called prior to sending the SHUTDOWN* broadcast to the user; it is a good place to stop making use of any resources of that* user (such as binding to a service running in the user).* @param userHandle The identifier of the user.*/ public void onStopUser(int userHandle) {}/*** Called when an existing user is stopping, for system services to finalize any per-user* state they maintain for running users. This is called after all application process* teardown of the user is complete.* @param userHandle The identifier of the user.*/ public void onCleanupUser(int userHandle) {}

3. 看看SystemService的內(nèi)容

??系統(tǒng)中存在部分service是systemservice的子類,所以就順便看看Systemservice的代碼都有哪些:

public abstract class SystemService {// 列出設(shè)備啟動(dòng)的各個(gè)階段/** Boot Phases*/public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100; // maybe should be a dependency?/*** After receiving this boot phase, services can obtain lock settings data.*/public static final int PHASE_LOCK_SETTINGS_READY = 480;/*** After receiving this boot phase, services can safely call into core system services* such as the PowerManager or PackageManager.*/public static final int PHASE_SYSTEM_SERVICES_READY = 500;/*** After receiving this boot phase, services can broadcast Intents.*/public static final int PHASE_ACTIVITY_MANAGER_READY = 550;/*** After receiving this boot phase, services can start/bind to third party apps.* Apps will be able to make Binder calls into services at this point.*/public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;/*** After receiving this boot phase, services can allow user interaction with the device.* This phase occurs when boot has completed and the home application has started.* System services may prefer to listen to this phase rather than registering a* broadcast receiver for ACTION_BOOT_COMPLETED to reduce overall latency.*/public static final int PHASE_BOOT_COMPLETED = 1000;private final Context mContext;/*** Initializes the system service.* * Subclasses must define a single argument constructor that accepts the context* and passes it to super.* ** @param context The system server context.*/// systemservice的構(gòu)造函數(shù)public SystemService(Context context) {mContext = context;}/*** Gets the system context.*/public final Context getContext() {return mContext;}/*** Returns true if the system is running in safe mode.* TODO: we should define in which phase this becomes valid*/public final boolean isSafeMode() {return getManager().isSafeMode();}/*** Called when the dependencies listed in the @Service class-annotation are available* and after the chosen start phase.* When this method returns, the service should be published.*/public abstract void onStart();/*** Called on each phase of the boot process. Phases before the service's start phase* (as defined in the @Service annotation) are never received.** @param phase The current boot phase.*/public void onBootPhase(int phase) {}/*** Called when a new user is starting, for system services to initialize any per-user* state they maintain for running users.* @param userHandle The identifier of the user.*/public void onStartUser(int userHandle) {}/*** Called when switching to a different foreground user, for system services that have* special behavior for whichever user is currently in the foreground. This is called* before any application processes are aware of the new user.* @param userHandle The identifier of the user.*/public void onSwitchUser(int userHandle) {}/*** Called when an existing user is stopping, for system services to finalize any per-user* state they maintain for running users. This is called prior to sending the SHUTDOWN* broadcast to the user; it is a good place to stop making use of any resources of that* user (such as binding to a service running in the user).* @param userHandle The identifier of the user.*/public void onStopUser(int userHandle) {}/*** Called when an existing user is stopping, for system services to finalize any per-user* state they maintain for running users. This is called after all application process* teardown of the user is complete.* @param userHandle The identifier of the user.*/public void onCleanupUser(int userHandle) {}/*** Publish the service so it is accessible to other services and apps.*/protected final void publishBinderService(String name, IBinder service) {publishBinderService(name, service, false);}/*** Publish the service so it is accessible to other services and apps.*/protected final void publishBinderService(String name, IBinder service,boolean allowIsolated) {ServiceManager.addService(name, service, allowIsolated);}/*** Get a binder service by its name.*/protected final IBinder getBinderService(String name) {return ServiceManager.getService(name);}/*** Publish the service so it is only accessible to the system process.*/protected final void publishLocalService(Class type, T service) {LocalServices.addService(type, service);}/*** Get a local service by interface.*/protected final T getLocalService(Class type) {return LocalServices.getService(type);}private SystemServiceManager getManager() {return LocalServices.getService(SystemServiceManager.class);} }

??其中比較感興趣的是publishBinderService這個(gè)方法,在之前看到這個(gè)函數(shù)還不知道是做什么用的,現(xiàn)在看到這個(gè)方法的代碼,瞬間清晰了,這個(gè)方法最終也還是會(huì)調(diào)用ServiceManager.addService方法,將service添加到ServiceManager中。

??另一個(gè)感興趣的方法是publishLocalService,這個(gè)方法將一些要在system process中用到的service添加到LocalServices static類對(duì)象中,這個(gè)類內(nèi)部通過(guò)ArrayMap將這些service記錄起來(lái),到后面需要使用就可以非常快速方便的取出來(lái)了。


http://blog4jimmy.com/2018/01/330.html

總結(jié)

以上是生活随笔為你收集整理的Android SystemServiceManager分析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。