参考:
https://zhuanlan.zhihu.com/p/467904594
https://blog.csdn.net/u014529755/article/details/78374374
https://blog.csdn.net/lmh_19941113/article/details/85403030
https://www.csdn.net/tags/NtTaUg3sNDA2ODgtYmxvZwO0O0OO0O0O.html
上一篇:
http://www.gaohaiyan.com/4098.html
梳理了 frameworks/base/services/java/com/android/server/SystemServer.java 中的流程,其中的 main 方法,创建SystemServer的实例,并继续调用run方法。
run() --> startOtherServices(t) --> startSystemUi(context, windowManagerF) --> Intent(SystemUIService) 。
然后到本文内容。
1. SystemUIService
frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUIService.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
// 66行 @Override public void onCreate() { super.onCreate(); Slog.e("aosp-acer", "SystemUIService被onCreate了"); // Start all of SystemUI. 启动 frameworks/base/packages/SystemUI/src/com/android/systemui/ 下的一堆SystemUI。 // frameworks/base/core/java/android/app/Service.java,343行。getApplication() //【--- 2 ---】frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUIApplication.java,141行。startServicesIfNeeded() ((SystemUIApplication) getApplication()).startServicesIfNeeded(); // Finish initializing dump logic mLogBufferFreezer.attach(mBroadcastDispatcher); // If configured, set up a battery notification. 如果配置了,设置电池状态通知 // frameworks/base/packages/SystemUI/res/values/config.xml:585:false if (getResources().getBoolean(R.bool.config_showNotificationForUnknownBatteryState)) { mBatteryStateNotifier.startListening(); } // For debugging RescueParty. 救援程序 https://zhuanlan.zhihu.com/p/108864944 if (Build.IS_DEBUGGABLE && SystemProperties.getBoolean("debug.crash_sysui", false)) { throw new RuntimeException(); } if (Build.IS_ENG) { // 如果手机是ENG版本。其它:eng、user、userdebug // b/71353150 - looking for leaked binder proxies BinderInternal.nSetBinderProxyCountEnabled(true); BinderInternal.nSetBinderProxyCountWatermarks(1000,900); BinderInternal.setBinderProxyCountCallback( new BinderInternal.BinderProxyLimitListener() { @Override public void onLimitReached(int uid) { Slog.w(SystemUIApplication.TAG, "uid " + uid + " sent too many Binder proxies to uid " + Process.myUid()); } }, mMainHandler); } Slog.e("aosp-acer", "SystemUIService,onCreate,启动SystemUIAuxiliaryDumpService"); // Bind the dump service so we can dump extra info during a bug report. 绑定dump服务,以便在错误报告期间保存更多信息 // frameworks/base/packages/SystemUI/src/com/android/systemui/dump/SystemUIAuxiliaryDumpService.java 堆栈信息辅助统计工具 // frameworks/base/core/java/android/content/ContextWrapper.java,736行 // frameworks/base/core/java/android/content/Context.java,3133行,abstract方法。 //【--- 3 ---】frameworks/base/core/java/android/app/ContextImpl.java,1686行,startServiceAsUser(,) startServiceAsUser( new Intent(getApplicationContext(), SystemUIAuxiliaryDumpService.class), UserHandle.SYSTEM ); } |
2. SystemUIApplication
frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUIApplication.java
整个第2步,是为了启动一堆系统UI组件,比如按音量键时弹出的音量控制面板。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
/** 141行 * Makes sure that all the SystemUI services are running. If they are already running, this is a no-op. * This is needed to conditinally start all the services, as we only need to have it in the main process. * <p>This method must only be called from the main thread.</p> * 确保所有SystemUI服务都在运行。如果他们已经在运行就无需操作。这里须是主流程中有条件地启动所有服务。此方法只能从主线程调用。 */ public void startServicesIfNeeded() { // frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java,128行,getSystemUIServiceComponents() String[] names = SystemUIFactory.getInstance().getSystemUIServiceComponents(getResources()); //【--- 2.1 ---】 startServicesIfNeeded(/* metricsPrefix= */ "StartServices", names); // 158行 } // 158行 private void startServicesIfNeeded(String metricsPrefix, String[] services) { if (mServicesStarted) { return; } mServices = new SystemUI[services.length]; // frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUI.java if (!mBootCompleteCache.isBootComplete()) { // check to see if maybe it was already completed long before we began see ActivityManagerService.finishBooting(). // 检查BootCompleteCache是否已在ActivityManagerService.finishBooting()之前完成。 if ("1".equals(SystemProperties.get("sys.boot_completed"))) { mBootCompleteCache.setBootComplete(); if (DEBUG) { Log.v(TAG, "BOOT_COMPLETED was already sent"); } } } final DumpManager dumpManager = mRootComponent.createDumpManager(); Log.v(TAG, "Starting SystemUI services for user " + Process.myUserHandle().getIdentifier() + "."); TimingsTraceLog log = new TimingsTraceLog("SystemUIBootTiming", Trace.TRACE_TAG_APP); log.traceBegin(metricsPrefix); final int N = services.length; Log.e("aosp-acer", "SystemUIApplication,startServicesIfNeeded,启动 " + N + " 个SystemUI组件"); for (int i = 0; i < N; i++) { // 遍历,挨个启动 String clsName = services[i]; if (DEBUG) Log.d(TAG, "loading: " + clsName); log.traceBegin(metricsPrefix + clsName); long ti = System.currentTimeMillis(); // 计时 try { // interface接口 frameworks/base/packages/SystemUI/src/com/android/systemui/dagger/ContextComponentHelper.java // 实现类 frameworks/base/packages/SystemUI/src/com/android/systemui/dagger/ContextComponentResolver.java,约92行 SystemUI obj = mComponentHelper.resolveSystemUI(clsName); // 将类名转换为类的实例或返回null。 if (obj == null) { Constructor constructor = Class.forName(clsName).getConstructor(Context.class); // 反射 构造方法 obj = (SystemUI) constructor.newInstance(this); // 实例 } mServices[i] = obj; } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { throw new RuntimeException(ex); } if (DEBUG) Log.d(TAG, "running: " + mServices[i]); Log.e("aosp-acer", "SystemUIApplication启动组件:" + clsName); mServices[i].start(); // 启动服务 【--- 2.2 ---】 log.traceEnd(); // Warn if initialization of component takes too long. ti = System.currentTimeMillis() - ti; if (ti > 1000) { Log.w(TAG, "Initialization of " + clsName + " took " + ti + " ms"); } if (mBootCompleteCache.isBootComplete()) { mServices[i].onBootCompleted(); } dumpManager.registerDumpable(mServices[i].getClass().getName(), mServices[i]); } mRootComponent.getInitController().executePostInitTasks(); log.traceEnd(); mServicesStarted = true; } |
2.1. SystemUIFactory
frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java
1 2 3 4 5 |
// 128行 Returns the list of system UI components that should be started. public String[] getSystemUIServiceComponents(Resources resources) { // frameworks/base/packages/SystemUI/res/values/config.xml,303行 return resources.getStringArray(R.array.config_systemUIServiceComponents); //【--- 2.1.1 ---】 } |
2.1.1. config_systemUIServiceComponents
frameworks/base/packages/SystemUI/res/values/config.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<!-- 303行。SystemUI Services: The classes of the stuff to start. --> <string-array name="config_systemUIServiceComponents" translatable="false"> <!-- 都在 frameworks/base/packages/SystemUI/src/ 下 --> <item>com.android.systemui.util.NotificationChannels</item> <item>com.android.systemui.keyguard.KeyguardViewMediator</item> <item>com.android.systemui.recents.Recents</item> <item>com.android.systemui.volume.VolumeUI</item> <item>com.android.systemui.stackdivider.Divider</item> <item>com.android.systemui.statusbar.phone.StatusBar</item> <item>com.android.systemui.usb.StorageNotification</item> <item>com.android.systemui.power.PowerUI</item> <item>com.android.systemui.media.RingtonePlayer</item> <item>com.android.systemui.keyboard.KeyboardUI</item> <item>com.android.systemui.pip.PipUI</item> <item>com.android.systemui.shortcut.ShortcutKeyDispatcher</item> <item>@string/config_systemUIVendorServiceComponent</item> <item>com.android.systemui.util.leak.GarbageMonitor$Service</item> <!-- 内部类Service. --> <item>com.android.systemui.LatencyTester</item> <item>com.android.systemui.globalactions.GlobalActionsComponent</item> <item>com.android.systemui.ScreenDecorations</item> <item>com.android.systemui.biometrics.AuthController</item> <item>com.android.systemui.biometrics.FODCircleViewImpl</item> <item>com.android.systemui.SliceBroadcastRelayHandler</item> <item>com.android.systemui.SizeCompatModeActivityController</item> <item>com.android.systemui.statusbar.notification.InstantAppNotifier</item> <item>com.android.systemui.theme.ThemeOverlayController</item> <item>com.android.systemui.accessibility.WindowMagnification</item> <item>com.android.systemui.accessibility.SystemActions</item> <item>com.android.systemui.toast.ToastUI</item> </string-array> <!-- SystemUI vender service, used in config_systemUIServiceComponents. --> <string name="config_systemUIVendorServiceComponent" translatable="false">com.android.systemui.VendorServices</string> |
2.2. SystemUI
frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUI.java
已经在应用层,《2.1.1》中列出的类都继承自SystemUI。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
/** * A top-level module of system UI code (sometimes called "system UI services" elsewhere in code). * Which SystemUI modules are loaded can be controlled via a config resource. * 系统UI代码的顶级模块(有时在代码的其它地方称为“系统UI服务”)。可以通过配置资源控制加载哪些SystemUI模块。 * @see SystemUIApplication#startServicesIfNeeded() */ public abstract class SystemUI implements Dumpable { protected final Context mContext; public SystemUI(Context context) { mContext = context; } public abstract void start(); // 启动当前这个系统UI组件,做必要的初始化 protected void onConfigurationChanged(Configuration newConfig) { // 关于屏幕切换时的处理 android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout" } @Override public void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter pw, @NonNull String[] args) { // 实现Dumpable接口后,响应“ adb shell dumpsys”指令,打印堆栈信息 } protected void onBootCompleted() { // 按需做启动完成后的扫尾工作 } public static void overrideNotificationAppName(Context context, Notification.Builder n, boolean system) { // frameworks/base/core/res/res/values-XXX/strings.xml final Bundle extras = new Bundle(); String appName = system ? context.getString(com.android.internal.R.string.notification_app_name_system) // “系统”二字对应的国际化翻译 : context.getString(com.android.internal.R.string.notification_app_name_settings); // “设置”二字对应的国际化翻译 extras.putString(Notification.EXTRA_SUBSTITUTE_APP_NAME, appName); n.addExtras(extras); } } |
3. ContextImpl
frameworks/base/core/java/android/app/ContextImpl.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// 1686行 @Override public ComponentName startServiceAsUser(Intent service, UserHandle user) { return startServiceCommon(service, false, user); // 1695行 } // 1695行 private ComponentName startServiceCommon(Intent service, boolean requireForeground, UserHandle user) { try { validateServiceIntent(service); // 检查intent可用 service.prepareToLeaveProcess(this); // 数据序列化处理,因为要启动到其它进程 ComponentName cn = ActivityManager.getService() //【--- 3.1 ---】frameworks/base/core/java/android/app/ActivityManager.java,4545行 .startService( //【--- 3.2 ---】frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java,15006行 mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(getContentResolver()), requireForeground, getOpPackageName(), getAttributionTag(), user.getIdentifier() ); if (cn != null) { if (cn.getPackageName().equals("!")) { throw new SecurityException("Not allowed to start service " + service + " without permission " + cn.getClassName()); } else if (cn.getPackageName().equals("!!")) { throw new SecurityException("Unable to start service " + service + ": " + cn.getClassName()); } else if (cn.getPackageName().equals("?")) { throw new IllegalStateException("Not allowed to start service " + service + ": " + cn.getClassName()); } } return cn; } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } |
3.1. ActivityManager
frameworks/base/core/java/android/app/ActivityManager.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/** 4545行 * @hide */ @UnsupportedAppUsage public static IActivityManager getService() { return IActivityManagerSingleton.get(); // 4554行。new Singleton<IActivityManager>(); } // 4554行 @UnsupportedAppUsage private static final Singleton<IActivityManager> IActivityManagerSingleton = new Singleton<IActivityManager>() { // android.util.Singleton 单例工具类。 @Override protected IActivityManager create() { final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE); final IActivityManager am = IActivityManager.Stub.asInterface(b); return am; } }; |
3.2. ActivityManagerService
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
// 15006行 @Override public ComponentName startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, String callingFeatureId, int userId) throws TransactionTooLargeException { enforceNotIsolatedCaller("startService"); // 3267行。 // Refuse possible leaked file descriptors. 拒绝可能泄漏的文件描述符 if (service != null && service.hasFileDescriptors() == true) { throw new IllegalArgumentException("File descriptors passed in Intent"); } if (callingPackage == null) { throw new IllegalArgumentException("callingPackage cannot be null"); } if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground); Slog.e("aosp-acer", "ActivityManagerService,startService,启动服务:" + service); synchronized(this) { final int callingPid = Binder.getCallingPid(); final int callingUid = Binder.getCallingUid(); final long origId = Binder.clearCallingIdentity(); ComponentName res; try { //【--- 3.3 ---】frameworks/base/services/core/java/com/android/server/am/ActiveServices.java,495行 res = mServices.startServiceLocked(caller, service, resolvedType, callingPid, callingUid, requireForeground, callingPackage, callingFeatureId, userId); } finally { Binder.restoreCallingIdentity(origId); } return res; } } |
3.3. ActiveServices
frameworks/base/services/core/java/com/android/server/am/ActiveServices.java
https://blog.csdn.net/lmh_19941113/article/details/85403030
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
// 495行 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int callingPid, int callingUid, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, final int userId) throws TransactionTooLargeException { return startServiceLocked(caller, service, resolvedType, callingPid, callingUid, fgRequired, callingPackage, callingFeatureId, userId, false); // 503行 } // 503行 ComponentName startServiceLocked( IApplicationThread caller, Intent service, String resolvedType, int callingPid, int callingUid, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, final int userId, boolean allowBackgroundActivityStarts) throws TransactionTooLargeException { // ...... ServiceRecord r; // service备案 ServiceMap smap; // map boolean callerFg; // 是否是前台应用 boolean addToStarting; // 立即启动 // ...... ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting); // 788行。 setFgsRestrictionLocked(callingPackage, callingPid, callingUid, r, allowBackgroundActivityStarts); return cmp; } // end startServiceLocked(10个参数) // 788行 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r, boolean callerFg, boolean addToStarting) throws TransactionTooLargeException { // ...... // 2938行 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false); // ...... } // 2938行 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg, boolean whileRestarting, boolean permissionsReviewRequired) throws TransactionTooLargeException { // ...... // 如果已经启动就回调一下, // 如果未启动,就调用ActivityManagerService启动之。见其它 Service启动相关的 篇章。 // ...... } |
- end
本文由崔维友 威格灵 cuiweiyou vigiles cuiweiyou 原创,转载请注明出处:http://www.gaohaiyan.com/4106.html
承接App定制、企业web站点、办公系统软件 设计开发,外包项目,毕设