Android Application 创建、SystemUI 启动以及系统窗口的添加,源码基于 android-12.1.0_r4;
SystemUI 启动
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 private void startOtherServices (@NonNull TimingsTraceAndSlog t) { t.traceBegin("StartSystemUI" ); try { startSystemUi(context, windowManagerF); } private static void startSystemUi (Context context, WindowManagerService windowManager) { PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class); Intent intent = new Intent (); intent.setComponent(pm.getSystemUiServiceComponent()); intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING); context.startServiceAsUser(intent, UserHandle.SYSTEM); windowManager.onSystemUiStarted(); } public ComponentName getSystemUiServiceComponent () { return ComponentName.unflattenFromString(mContext.getResources().getString( com.android.internal.R.string.config_systemUIServiceComponent)); }
根据 config_systemUIServiceComponent 获取 SystemUIService 服务,并通过 startServiceAsUser()
启动服务;
1 2 3 // frameworks/base/core/res/res/values/config.xml <string name ="config_systemUIServiceComponent" translatable ="false" > com.android.systemui/com.android.systemui.SystemUIService</string >
进程启动后会执行到 ActivityThread.main()
方法中,然后调用 thread.attach()
,attach 通过 binder 调用 AMS.attachApplication() -> attachApplicationLocked() -> thread.bindApplication()/ActivityTaskManagerInternal.attachApplication()
,然后发送 Handler 消息 BIND_APPLICATION/EXECUTE_TRANSACTION,主线程 looper 收到 BIND_APPLICATION 消息后调用 handleBinderApplication()
,接下来从这里分析;
handleBindApplication() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 static final class AppBindData { LoadedApk info; } private void handleBindApplication (AppBindData data) { data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo); Application app; app = data.info.makeApplication(data.restrictedBackupMode, null ); if (!data.restrictedBackupMode) { if (!ArrayUtils.isEmpty(data.providers)) { installContentProviders(app, data.providers); } } try { mInstrumentation.callApplicationOnCreate(app); }
data 是 AppBindData 对象,所以 data.info 则是 LoadedApk 对象,主要工作:
getPackageInfoNoCheck():创建 LoadedApk;
makeApplication():创建 Application;
调用 Application.onCreate();
创建 LoadedApk 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 final ArrayMap<String, WeakReference<LoadedApk>> mPackages = new ArrayMap <>(); public final LoadedApk getPackageInfoNoCheck (ApplicationInfo ai, CompatibilityInfo compatInfo) { return getPackageInfo(ai, compatInfo, null , false , true , false ); } private LoadedApk getPackageInfo (ApplicationInfo aInfo, CompatibilityInfo compatInfo, ClassLoader baseLoader, boolean securityViolation, boolean includeCode, boolean registerPackage) { final boolean differentUser = (UserHandle.myUserId() != UserHandle.getUserId(aInfo.uid)); synchronized (mResourcesManager) { WeakReference<LoadedApk> ref; ... LoadedApk packageInfo = ref != null ? ref.get() : null ; ... packageInfo = new LoadedApk (this , aInfo, compatInfo, baseLoader, securityViolation, includeCode && (aInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0 , registerPackage); if (mSystemThread && "android" .equals(aInfo.packageName)) { packageInfo.installSystemApplicationInfo(aInfo, getSystemContext().mPackageInfo.getClassLoader()); } if (differentUser) { } else if (includeCode) { mPackages.put(aInfo.packageName, new WeakReference <LoadedApk>(packageInfo)); } else {...} return packageInfo; } }
创建 LoadedApk 对象,并把它的弱引用添加到 mPackages 这个 ArrayMap 中,最后返回 pacakgeInfo;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public LoadedApk (ActivityThread activityThread, ApplicationInfo aInfo, CompatibilityInfo compatInfo, ClassLoader baseLoader, boolean securityViolation, boolean includeCode, boolean registerPackage) { mActivityThread = activityThread; setApplicationInfo(aInfo); mPackageName = aInfo.packageName; mBaseClassLoader = baseLoader; mSecurityViolation = securityViolation; mIncludeCode = includeCode; mRegisterPackage = registerPackage; mDisplayAdjustments.setCompatibilityInfo(compatInfo); mAppComponentFactory = createAppFactory(mApplicationInfo, mBaseClassLoader); }
LoadedApk 对象构造函数中创建了 AppComponentFactory 对象;
创建 SystemUIApplication - makeApplication() 接下来看一下 makeApplication();
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public Application makeApplication (boolean forceDefaultAppClass, Instrumentation instrumentation) { if (mApplication != null ) { return mApplication; } Application app = null ; String appClass = mApplicationInfo.className; try { final java.lang.ClassLoader cl = getClassLoader(); ... ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this ); ... app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext); appContext.setOuterContext(app); } catch (Exception e) {...} mActivityThread.mAllApplications.add(app); mApplication = app; ... return app; }
又调用了 Instrumentation.newApplication();
1 2 3 4 5 6 7 8 9 10 11 public Application newApplication (ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException { Application app = getFactory(context.getPackageName()) .instantiateApplication(cl, className); app.attach(context); return app; }
先执行 getFactory()
获取 AppComponentFactory 对象;
再执行 instantiateApplication()
获取 SystemUIApplication 对象;
获取 AppComponentFactory 对象 1 2 3 4 5 6 7 8 private AppComponentFactory getFactory (String pkg) { ... LoadedApk apk = mThread.peekPackageInfo(pkg, true ); if (apk == null ) apk = mThread.getSystemContext().mPackageInfo; return apk.getAppFactory(); }
getFactory() 通过 LoadedApk.getAppFactory() 来获取 AppComponentFactory 对象;
1 2 3 4 5 private AppComponentFactory mAppComponentFactory; public AppComponentFactory getAppFactory () { return mAppComponentFactory; }
getAppFactory() 返回 AppComponentFactory 对象,前面讲到在 LoadedApk 的构造函数中通过 LoadedApk.createAppFactory()
创建了 AppComponentFactory 这个对象;
创建 AppComponentFactory 对象 1 2 3 4 5 6 7 8 9 10 11 12 private AppComponentFactory createAppFactory (ApplicationInfo appInfo, ClassLoader cl) { if (mIncludeCode && appInfo.appComponentFactory != null && cl != null ) { try { return (AppComponentFactory) cl.loadClass(appInfo.appComponentFactory).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { Slog.e(TAG, "Unable to instantiate appComponentFactory" , e); } } return AppComponentFactory.DEFAULT; }
如果 appInfo.appComponentFactory 不等于 null,通过 ClassLoader 加载对应的类创建实例,否则返回 AppComponentFactory.DEFAULT,那么 AppComponentFactory 是什么呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class AppComponentFactory { public @NonNull ClassLoader instantiateClassLoader (...) public @NonNull Application instantiateApplication (@NonNull ClassLoader cl, @NonNull String className) ... { return (Application) cl.loadClass(className).newInstance(); } public @NonNull Activity instantiateActivity (...) public @NonNull BroadcastReceiver instantiateReceiver (...) public @NonNull ContentProvider instantiateProvider (...) public static final AppComponentFactory DEFAULT = new AppComponentFactory ();
从注释可以看出,这个类是用于控制清单元素(AndroidManifest.xml)实例化的接口,简单说就是允许应用内部创建 AppComponentFactory 实现类,重写 AppComponentFactory 类中的方法,用来执行诸如依赖注入或者对这些类进行类加载器修改 ,插件化就是用到了这里;
SystemUIAppComponentFactory 看一下 SystemUI 的 AndroidManifest.xml
1 2 3 4 5 6 <application android:name =".SystemUIApplication" ... tools:replace ="android:appComponentFactory" android:appComponentFactory =".SystemUIAppComponentFactory" >
这样配置以后,PKMS 会将 android:appComponentFactory 解析到 appInfo.appComponentFactory,系统在创建 Application 和四大组件的时候就会调用到这里配置的类,如果没有配置,就会直接使用 AppComponentFactory.DEFAULT 变量,所以前面 createAppFactory()
返回的就是这里配置的类 ;
先看一下这个 SystemUIAppComponentFactory;
1 2 3 4 5 import androidx.core.app.AppComponentFactory;public class SystemUIAppComponentFactory extends AppComponentFactory { ... }
需要注意的是这里 SystemUIAppComponentFactory 继承的是 androidx.core.app.AppComponentFactory ,不是 android.app.AppComponentFactory ,前者继承了后者;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package androidx.core.app;@RequiresApi(28) public class AppComponentFactory extends android .app.AppComponentFactory { @Override public final Application instantiateApplication ( @NonNull ClassLoader cl, @NonNull String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return checkCompatWrapper(instantiateApplicationCompat(cl, className)); } public @NonNull Application instantiateApplicationCompat (@NonNull ClassLoader cl, @NonNull String className) ...{ try { return Class.forName(className, false , cl).asSubclass(Application.class) .getDeclaredConstructor().newInstance(); } ... }
在 instantiateApplication() 内部调用了 instantiateApplicationCompat()
,这里其实是调用 SystemUIAppComponentFactory.instantiateApplicationCompat()
,因为 SystemUIAppComponentFactory 重写了 AppComponentFactory.instantiateApplicationCompat()
,最后创建并返回了 Application 实例;
所以最终 getFactory()
根据包名得到了在 AndroidManifest.xml 中定义的继承自 AppComponentFactory 的 SystemUIAPpComponentFactory 对象;
获取 SystemUIApplication 对象 接下来回到 Instrumentation.newApplication() 中;
1 2 3 4 5 6 7 public Application newApplication (ClassLoader cl, String className, Context context) ... { Application app = getFactory(context.getPackageName()) .instantiateApplication(cl, className); app.attach(context); return app; }
获取到 SystemUIAppComponentFactory 对象后,调用 instantiateApplication()
方法,这里调用到父类 AppComponentFactory 的 instantiateApplication()
方法,前面分析得知其中又调用到子类 SystemUIAppComponentFactory.instantiateApplicationCompat()
方法,
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 public class SystemUIAppComponentFactory extends AppComponentFactory { @Override public Application instantiateApplicationCompat ( @NonNull ClassLoader cl, @NonNull String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException { Application app = super .instantiateApplicationCompat(cl, className); if (app instanceof ContextInitializer) { ((ContextInitializer) app).setContextAvailableCallback( context -> { SystemUIFactory.createFromConfig(context); SystemUIFactory.getInstance().getSysUIComponent().inject( SystemUIAppComponentFactory.this ); } ); } return app; } public interface ContextAvailableCallback { void onContextAvailable (Context context) ; } public interface ContextInitializer { void setContextAvailableCallback (ContextAvailableCallback callback) ; } }
这里做了三件事:
调用父类的 instantiateApplicationCompat()
方法实例化 Application 对象;
调用 SystemUIApplication.setContextAvailableCallback()
;
返回 Application 实例;
SystemUIApplication 实现了 SystemUIAppComponentFactory.ContextInitializer
接口,
1 2 3 4 5 6 7 8 9 public class SystemUIApplication extends Application implements SystemUIAppComponentFactory .ContextInitializer { private SystemUIAppComponentFactory.ContextAvailableCallback mContextAvailableCallback; @Override public void setContextAvailableCallback ( SystemUIAppComponentFactory.ContextAvailableCallback callback) { mContextAvailableCallback = callback; }
把传入的 callback 参数传递给了 mContextAvailableCallback,从前面分析 handleBindApplication()
得知,先创建 Application 对象,然后执行 Application.onCreate()
方法,至此已经创建了 SystemUIApplication,接下来看 SystemUIApplication.onCreate() 方法;
SystemUIApplication.onCreate() 1 2 3 4 5 6 @Override public void onCreate () { super .onCreate(); ... mContextAvailableCallback.onContextAvailable(this );
这里回调了 onContextAvailable()
方法,在上面传递 ContextAvailableCallback 给 SystemUIApplication 的时候定义了这个方法,此时则执行到了这段代码:
1 2 3 4 5 6 7 8 9 10 11 12 public class SystemUIAppComponentFactory extends AppComponentFactory { @Override public Application instantiateApplicationCompat (...) ...{ ... if (app instanceof ContextInitializer) { ((ContextInitializer) app).setContextAvailableCallback( context -> { SystemUIFactory.createFromConfig(context); SystemUIFactory.getInstance().getSysUIComponent().inject( SystemUIAppComponentFactory.this );
做了两个工作:
SystemUIFactory.createFromConfig()
SystemUIFactory.getInstance().getSysUIComponent().inject(SystemUIAppComponentFactory.this):初始化 depency 中含 @inject 的变量;
createFromConfig() 1 2 3 4 5 6 7 8 9 10 11 12 13 public class SystemUIFactory { public static void createFromConfig (Context context, boolean fromTest) { ... final String clsName = context.getString(R.string.config_systemUIFactoryComponent); ... try { Class<?> cls = null ; cls = context.getClassLoader().loadClass(clsName); mFactory = (SystemUIFactory) cls.newInstance(); mFactory.init(context, fromTest); } catch (Throwable t) {...} }
创建 SystemUIFactory 实例,执行其 init() 方法,context 是 SystemUIApplication 对象;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 private GlobalRootComponent mRootComponent; private SysUIComponent mSysUIComponent; public void init (Context context, boolean fromTest) ... { mRootComponent = buildGlobalRootComponent(context); SysUIComponent.Builder builder = mRootComponent.getSysUIComponent(); mSysUIComponent = builder.build(); if (mInitializeComponents) { mSysUIComponent.init(); } Dependency dependency = mSysUIComponent.createDependency(); dependency.start(); } public SysUIComponent getSysUIComponent () { return mSysUIComponent; }
获取 SystemUI 的 dagger 组件,创建 dependency 对象,Dependency 管理各式各样的依赖,被依赖的实例通过 Map 管理,但并不是在初始化的时候就缓存它们。而先将各实例对应的懒加载回调缓存进去。其后在各实例确实需要使用的时候通过注入的懒加载获取和缓存;
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 @SysUISingleton public class Dependency { private final ArrayMap<Object, Object> mDependencies = new ArrayMap <>(); private final ArrayMap<Object, LazyDependencyCreator> mProviders = new ArrayMap <>(); @Inject DumpManager mDumpManager; @Inject Lazy<StatusBarWindowController> mTempStatusBarWindowController; @Inject Lazy<IStatusBarService> mIStatusBarService; @Inject Lazy<StatusBarStateController> mStatusBarStateController; protected void start () { mProviders.put(StatusBarWindowController.class, mTempStatusBarWindowController::get); mProviders.put(IStatusBarService.class, mIStatusBarService::get); mProviders.put(StatusBarStateController.class, mStatusBarStateController::get); ... } private synchronized <T> T getDependencyInner (Object key) { @SuppressWarnings("unchecked") T obj = (T) mDependencies.get(key); if (obj == null ) { obj = createDependency(key); mDependencies.put(key, obj); } return obj; } public <T> T createDependency (Object cls) { Preconditions.checkArgument(cls instanceof DependencyKey<?> || cls instanceof Class<?>); @SuppressWarnings("unchecked") LazyDependencyCreator<T> provider = mProviders.get(cls); if (provider == null ) { throw new IllegalArgumentException ("Unsupported dependency " + cls + ". " + mProviders.size() + " providers known." ); } return provider.createDependency(); } private interface LazyDependencyCreator <T> { T createDependency () ; }
执行 Dependency.start() 方法;
getSysUIComponent.inject() 1 2 3 4 5 6 7 private SysUIComponent mSysUIComponent; public SysUIComponent getSysUIComponent () { return mSysUIComponent; } void inject (SystemUIAppComponentFactory factory) ;
获取上面得到的 mSysUIComponent,执行其中的 inject() 方法,参数为 SystemUIAppComponentFactory.this,所以是初始化 SystemUIAppComponentFactory 中标注 @Inject 的变量;
Application 创建后,接下来就会执行到 SystemUIService 中的逻辑,进入 SystemUIService.onCreate();
SystemUIService.onCreate() 1 2 3 4 5 6 public void onCreate () { super .onCreate(); ((SystemUIApplication) getApplication()).startServicesIfNeeded();
调用 SystemUIApplication#startServicesIfNeeded()
1 2 3 4 5 6 public void startServicesIfNeeded () { String[] names = SystemUIFactory.getInstance().getSystemUIServiceComponents(getResources()); startServicesIfNeeded( "StartServices" , names); }
获取所有 SystemUI 中的服务组件,并在后续依次启动;
1 2 3 4 public String[] getSystemUIServiceComponents(Resources resources) { return resources.getStringArray(R.array.config_systemUIServiceComponents); }
config_systemUIServiceComponents 定义了 SystemUI 的子类组件,状态栏对应 StatusBar 这个;
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 <string-array name ="config_systemUIServiceComponents" translatable ="false" > <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.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.shortcut.ShortcutKeyDispatcher</item > <item > @string/config_systemUIVendorServiceComponent</item > <item > com.android.systemui.util.leak.GarbageMonitor$Service</item > <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.SliceBroadcastRelayHandler</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 > <item > com.android.systemui.wmshell.WMShell</item > </string-array >
根据 config_systemUIServiceComponents 获取包含继承自 SystemUI 的子类名 的数组,作为参数传入 startServicesIfNeeded();
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 private void startServicesIfNeeded (String metricsPrefix, String[] services) { if (mServicesStarted) { return ; } mServices = new SystemUI [services.length]; ... final int N = services.length; 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 { SystemUI obj = mComponentHelper.resolveSystemUI(clsName); if (obj == null ) { Constructor constructor = Class.forName(clsName).getConstructor(Context.class); obj = (SystemUI) constructor.newInstance(this ); } mServices[i] = obj; } catch (...) { throw new RuntimeException (ex); } if (DEBUG) Log.d(TAG, "running: " + mServices[i]); mServices[i].start(); if (mBootCompleteCache.isBootComplete()) { mServices[i].onBootCompleted(); } ... mServicesStarted = true ; }
遍历 SystemUI 子类对象,根据类名通过反射获取子类实例,将实例赋值给 mServices 数组,并执行子类 start()
方法,这里以 StatusBar 为例,执行 StatusBar.start()
;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public void start () { ... mStatusBarStateController.addCallback(mStateListener, SysuiStatusBarStateController.RANK_STATUS_BAR); mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); ... mWindowManagerService = WindowManagerGlobal.getWindowManagerService(); ... RegisterStatusBarResult result = null ; try { result = mBarService.registerStatusBar(mCommandQueue); } catch (RemoteException ex) { ex.rethrowFromSystemServer(); } createAndAddWindows(result);
调用 createAndAddWindows();
1 2 3 4 5 6 7 8 public void createAndAddWindows (@Nullable RegisterStatusBarResult result) { makeStatusBarView(result); mNotificationShadeWindowController.attach(); mStatusBarWindowController.attach(); }
在前面 Depency.java 中看到其中有 StatusBarWindowController,在 StatusBarWindowController 构造函数中初始化了 mStatusBarWindowView对象,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @Inject public StatusBarWindowController (...) { mContext = context; mWindowManager = windowManager; mIWindowManager = iWindowManager; mContentInsetsProvider = contentInsetsProvider; mStatusBarWindowView = statusBarWindowView; mLaunchAnimationContainer = mStatusBarWindowView.findViewById( R.id.status_bar_launch_animation_container); mLpChanged = new WindowManager .LayoutParams(); mResources = resources; if (mBarHeight < 0 ) { mBarHeight = SystemBarUtils.getStatusBarHeight(mContext); } }
随后调用 attach() 函数把 StatusBarWindowView 添加到 WindowManager 中;
1 2 3 4 5 6 7 private final WindowManager mWindowManager;public void attach () { ... mWindowManager.addView(mStatusBarWindowView, mLp); ... }
后面的工作就和Activity 窗口添加-第二小节 一样了;