Android 12系统源码_SystemUI系统状态栏StatusBar的创建流程

Posted AFinalStone

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 12系统源码_SystemUI系统状态栏StatusBar的创建流程相关的知识,希望对你有一定的参考价值。

前言

上一篇我们具体分析了SystemUI的启动流程,在SystemServer的startOtherServices方法中,会启动SystemUIService服务,SystemUIService服务的onCreate方法会继续调用SystemUIApplication的startServicesIfNeeded方法,在该方法中会获取SystemUI组件各个类的具体路径,并通过和dagger2相关的ComponentHelper关键接口,获取SystemUI组件对应的实例对象,然后依次调用每个组件的start() 方法启动相关类的服务,启动完成后,又会再次调用该组件的onBootCompleted( ) 方法。

frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUIApplication.java

    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];//具体SystemUI组件类的完整路径
            long ti = System.currentTimeMillis();
            try 
                SystemUI obj = mComponentHelper.resolveSystemUI(clsName);//ComponentHelper的resolveSystemUI方法可以通过类名拿到具体的SystemUI实例对象
                if (obj == null) //如果通过ComponentHelper的resolveSystemUI没有成功获取到实例对象,则通过反射创建,代码基本上不会走这里。
                    Constructor constructor = Class.forName(clsName).getConstructor(Context.class);
                    obj = (SystemUI) constructor.newInstance(this);//通过反射创建实例对象
                
                mServices[i] = obj;//将获取的obj实例对象赋值到数组中。
             catch (ClassNotFoundException
                    | NoSuchMethodException
                    | IllegalAccessException
                    | InstantiationException
                    | InvocationTargetException ex) 
                throw new RuntimeException(ex);
            
            ...代码省略...     
            mServices[i].start();
    		...代码省略...     
            if (mBootCompleteCache.isBootComplete()) 
                mServices[i].onBootCompleted();
            
    		...代码省略...     
        
    	...代码省略...   
        mServicesStarted = true;//服务已经被启动
    

frameworks/base/packages/SystemUI/res/values/config.xml

    <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><!--监听 USB 连接状态并发送通知进行提示-->
        <item>com.android.systemui.power.PowerUI</item><!--监听电量状态并在低电量时发送通知-->
        <item>com.android.systemui.media.RingtonePlayer</item><!--用于播放铃声-->
        <item>com.android.systemui.keyboard.KeyboardUI</item><!--键盘锁 UI-->
        <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><!--仅在 debug 环境执行,用于监听系统测试延迟的模拟动作-->
        <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><!--允许打开设置App-->
        <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>

本篇文章我们主要来分析一下com.android.systemui.statusbar.phone.StatusBar所对应的状态栏类的创建过程。

一、StatusBar的构造方法

1、通过前面的分析我们知道,SystemUI的所有组件实例都是通过和dagger2相关的ComponentHelper类得到的,该类中的的SystemUI组件实例最初是通过dagger2的依赖注入得到的,而dagger2在实例化SystemUI组件的时候,会调用对应组件的构造方法,StatusBar的构造方法如下所示:

frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java

public class StatusBar extends SystemUI implements ActivityStarter, LifecycleOwner 
  
  public StatusBar(
            Context context,
            NotificationsController notificationsController,
            FragmentService fragmentService,
            LightBarController lightBarController,
            AutoHideController autoHideController,
            StatusBarWindowController statusBarWindowController,//状态栏控制器
            KeyguardUpdateMonitor keyguardUpdateMonitor,
            StatusBarSignalPolicy statusBarSignalPolicy,
            PulseExpansionHandler pulseExpansionHandler,
            NotificationWakeUpCoordinator notificationWakeUpCoordinator,
            KeyguardBypassController keyguardBypassController,
            KeyguardStateController keyguardStateController,
            HeadsUpManagerPhone headsUpManagerPhone,
            DynamicPrivacyController dynamicPrivacyController,
            BypassHeadsUpNotifier bypassHeadsUpNotifier,
            FalsingManager falsingManager,
            FalsingCollector falsingCollector,
            BroadcastDispatcher broadcastDispatcher,
            NotifShadeEventSource notifShadeEventSource,
            NotificationEntryManager notificationEntryManager,
            NotificationGutsManager notificationGutsManager,
            NotificationLogger notificationLogger,
            NotificationInterruptStateProvider notificationInterruptStateProvider,
            NotificationViewHierarchyManager notificationViewHierarchyManager,
            PanelExpansionStateManager panelExpansionStateManager,
            KeyguardViewMediator keyguardViewMediator,
            DisplayMetrics displayMetrics,
            MetricsLogger metricsLogger,
            @UiBackground Executor uiBgExecutor,
            NotificationMediaManager notificationMediaManager,
            NotificationLockscreenUserManager lockScreenUserManager,
            NotificationRemoteInputManager remoteInputManager,
            UserSwitcherController userSwitcherController,
            NetworkController networkController,
            BatteryController batteryController,
            SysuiColorExtractor colorExtractor,
            ScreenLifecycle screenLifecycle,
            WakefulnessLifecycle wakefulnessLifecycle,
            SysuiStatusBarStateController statusBarStateController,
            Optional<BubblesManager> bubblesManagerOptional,
            Optional<Bubbles> bubblesOptional,
            VisualStabilityManager visualStabilityManager,
            DeviceProvisionedController deviceProvisionedController,
            NavigationBarController navigationBarController,
            AccessibilityFloatingMenuController accessibilityFloatingMenuController,
            Lazy<AssistManager> assistManagerLazy,
            ConfigurationController configurationController,
            NotificationShadeWindowController notificationShadeWindowController,
            DozeParameters dozeParameters,
            ScrimController scrimController,
            Lazy<LockscreenWallpaper> lockscreenWallpaperLazy,
            LockscreenGestureLogger lockscreenGestureLogger,
            Lazy<BiometricUnlockController> biometricUnlockControllerLazy,
            DozeServiceHost dozeServiceHost,
            PowerManager powerManager,
            ScreenPinningRequest screenPinningRequest,
            DozeScrimController dozeScrimController,
            VolumeComponent volumeComponent,
            CommandQueue commandQueue,
            CollapsedStatusBarFragmentLogger collapsedStatusBarFragmentLogger,
            StatusBarComponent.Factory statusBarComponentFactory,//状态栏组件工厂
            PluginManager pluginManager,
            Optional<LegacySplitScreen> splitScreenOptional,
            LightsOutNotifController lightsOutNotifController,
            StatusBarNotificationActivityStarter.Builder
                    statusBarNotificationActivityStarterBuilder,
            ShadeController shadeController,
            StatusBarKeyguardViewManager statusBarKeyguardViewManager,
            ViewMediatorCallback viewMediatorCallback,
            InitController initController,
            @Named(TIME_TICK_HANDLER_NAME) Handler timeTickHandler,
            PluginDependencyProvider pluginDependencyProvider,
            KeyguardDismissUtil keyguardDismissUtil,
            ExtensionController extensionController,
            UserInfoControllerImpl userInfoControllerImpl,
            OperatorNameViewController.Factory operatorNameViewControllerFactory,
            PhoneStatusBarPolicy phoneStatusBarPolicy,
            KeyguardIndicationController keyguardIndicationController,
            DemoModeController demoModeController,
            Lazy<NotificationShadeDepthController> notificationShadeDepthControllerLazy,
            StatusBarTouchableRegionManager statusBarTouchableRegionManager,
            NotificationIconAreaController notificationIconAreaController,
            BrightnessSliderController.Factory brightnessSliderFactory,
            WallpaperController wallpaperController,
            OngoingCallController ongoingCallController,
            SystemStatusAnimationScheduler animationScheduler,
            StatusBarLocationPublisher locationPublisher,
            StatusBarIconController statusBarIconController,
            StatusBarHideIconsForBouncerManager statusBarHideIconsForBouncerManager,
            LockscreenShadeTransitionController lockscreenShadeTransitionController,
            FeatureFlags featureFlags,
            KeyguardUnlockAnimationController keyguardUnlockAnimationController,
            @Main Handler mainHandler,
            @Main DelayableExecutor delayableExecutor,
            @Main MessageRouter messageRouter,
            WallpaperManager wallpaperManager,
            UnlockedScreenOffAnimationController unlockedScreenOffAnimationController,
            Optional<StartingSurface> startingSurfaceOptional,
            TunerService tunerService,
            DumpManager dumpManager,
            ActivityLaunchAnimator activityLaunchAnimator) 
        super(context);
        mNotificationsController = notificationsController;
        mFragmentService = fragmentService;
        mLightBarController = lightBarController;
        mAutoHideController = autoHideController;
        mStatusBarWindowController = statusBarWindowController;
        mKeyguardUpdateMonitor = keyguardUpdateMonitor;
        mPulseExpansionHandler = pulseExpansionHandler;
        mWakeUpCoordinator = notificationWakeUpCoordinator;
        mKeyguardBypassController = keyguardBypassController;
        mKeyguardStateController = keyguardStateController;
        mHeadsUpManager = headsUpManagerPhone;
        mOperatorNameViewControllerFactory = operatorNameViewControllerFactory;
        mKeyguardIndicationController = keyguardIndicationController;
        mStatusBarTouchableRegionManager = statusBarTouchableRegionManager;
        mDynamicPrivacyController = dynamicPrivacyController;
        mBypassHeadsUpNotifier = bypassHeadsUpNotifier;
        mFalsingCollector = falsingCollector;
        mFalsingManager = falsingManager;
        mBroadcastDispatcher = broadcastDispatcher;
        mNotifShadeEventSource = notifShadeEventSource;
        mEntryManager = notificationEntryManager;
        mGutsManager = notificationGutsManager;
        mNotificationLogger = notificationLogger;
        mNotificationInterruptStateProvider = notificationInterruptStateProvider;
        mViewHierarchyManager = notificationViewHierarchyManager;
        mPanelExpansionStateManager = panelExpansionStateManager;
        mKeyguardViewMediator = keyguardViewMediator;
        mDisplayMetrics = displayMetrics;
        mMetricsLogger = metricsLogger;
        mUiBgExecutor = uiBgExecutor;
        mMediaManager = notificationMediaManager;
        mLockscreenUserManager = lockScreenUserManager;
        mRemoteInputManager = remoteInputManager;
        mUserSwitcherController = userSwitcherController;
        mNetworkController = networkController;
        mBatteryController = batteryController;
        mColorExtractor = colorExtractor;
        mScreenLifecycle = screenLifecycle;
        mWakefulnessLifecycle = wakefulnessLifecycle;
        mStatusBarStateController = statusBarStateController;
        mBubblesManagerOptional = bubblesManagerOptional;
        mBubblesOptional = bubblesOptional;
        mVisualStabilityManager = visualStabilityManager;
        mDeviceProvisionedController = deviceProvisionedController;
        mNavigationBarController = navigationBarController;
        mAccessibilityFloatingMenuController = accessibilityFloatingMenuController;
        mAssistManagerLazy = assistManagerLazy;
        mConfigurationController = configurationController;
        mNotificationShadeWindowController = notificationShadeWindowController;
        mDozeServiceHost = dozeServiceHost;
        mPowerManager = powerManager;
        mDozeParameters = dozeParameters;
        mScrimController = scrimController;
        mLockscreenWallpaperLazy = lockscreenWallpaperLazy;
        mLockscreenGestureLogger = lockscreenGestureLogger;
        mScreenPinningRequest = screenPinningRequest;
        mDozeScrimController = dozeScrimController;
        mBiometricUnlockControllerLazy = biometricUnlockControllerLazy;
        mNotificationShadeDepthControllerLazy = notificationShadeDepthControllerLazy;
        mVolumeComponent = volumeComponent;
        mCommandQueue = commandQueue;
        mCollapsedStatusBarFragmentLogger = collapsedStatusBarFragmentLogger;
        mStatusBarComponentFactory = statusBarComponentFactory;
        mPluginManager = pluginManager;
        mSplitScreenOptional = splitScreenOptional;
        mStatusBarNotificationActivityStarterBuilder = statusBarNotificationActivityStarterBuilder;
        mShadeController = shadeController;
        mLightsOutNotifController =  lightsOutNotifController;
        mStatusBarKeyguardViewManager = statusBarKeyguardViewManager;
        mKeyguardViewMediatorCallback = viewMediatorCallback;
        mInitController = initController;
        mPluginDependencyProvider = pluginDependencyProvider;
        mKeyguardDismissUtil = keyguardDismissUtil;
        mExtensionController = extensionController;
        mUserInfoControllerImpl = userInfoControllerImpl;
        mIconPolicy = phoneStatusBarPolicy;
        mDemoModeController = demoModeController;
        mNotificationIconAreaController = notificationIconAreaController;
        mBrightnessSliderFactory = brightnessSliderFactory;
        mWallpaperController = wallpaperController;
        mOngoingCallController = ongoingCallController;
        mAnimationScheduler = animationScheduler;
        mStatusBarSignalPolicy = statusBarSignalPolicy;
        mStatusBarLocationPublisher = locationPublisher;
        mStatusBarIconController = statusBarIconController;
        mStatusBarHideIconsForBouncerManager = statusBarHideIconsForBouncerManager;
        mFeatureFlags = featureFlags;
        mKeyguardUnlockAnimationController = keyguardUnlockAnimationController;
        mMainHandler = mainHandler;
        mMainExecutor = delayableExecutor;
        mMessageRouter = messageRouter;
        mWallpaperManager = wallpaperManager;
        mUnlockedScreenOffAnimationController = unlockedScreenOffAnimationController;
        mTunerService = tunerService;

        mLockscreenShadeTransitionController = lockscreenShadeTransitionController;
        mStartingSurfaceOptional = startingSurfaceOptional;
        lockscreenShadeTransitionController.setStatusbar(this);

        mPanelExpansionStateManager.addExpansionListener(this::onPanelExpansionChanged);

        mBubbleExpandListener =
                (isExpanding, key) -> mContext.getMainExecutor().execute(() -> 
                    mNotificationsController.requestNotificationUpdate("onBubbleExpandChanged");
                    updateScrimController();
                );

        mActivityIntentHelper = new ActivityIntentHelper(mContext);
        mActivityLaunchAnimator = activityLaunchAnimator;

        // The status bar background may need updating when the ongoing call status changes.
        mOngoingCallController.addCallback((animate) -> maybeUpdateBarMode());

        // TODO(b/190746471): Find a better home for this.
        DateTimeView.setReceiverHandler(timeTickHandler);

        mMessageRouter.subscribeTo(KeyboardShortcutsMessage.class,
                data -> toggleKeyboardShortcuts(data.mDeviceId));
        mMessageRouter.subscribeTo(MSG_DISMISS_KEYBOARD_SHORTCUTS_MENU,
                id -> dismissKeyboardShortcuts());
        mMessageRouter.subscribeTo(AnimateExpandSettingsPanelMessage.class,
                data -> mCommandQueueCallbacks.animateExpandSettingsPanel(data.mSubpanel));
        mMessageRouter.subscribeTo(MSG_LAUNCH_TRANSITION_TIMEOUT,
                id -> onLaunchTransitionTimeout());
    
 

StatusBar的构造方法乍一看简直恐怖如斯,因为它的参数居然足足有100多个,这种代码要是放在以前,肯定妥妥的被骂翻!构造方法参数如此之多别人要如何创建对象实例?幸好现在有了Dagger2框架的加持,该框架会自动帮我们创建对象实例并传入StatusBar需要的所有参数,我们直接在StatusBar中用就是了,所以构造方法就算有再多参数也不是什么大问题了。

二、从StatusBar的start方法到状态栏视图窗口StatusBarWindowView的创建

1、结合前面SystemUIApplication的startServicesIfNeeded方法我们知道,在获得每个SystemUI组件对象之后,都会调用该对象的start方法,作为SystemUI组件之一的StatusBar自然也不例外:

public class StatusBar extends SystemUI implements ActivityStarter, LifecycleOwner 
    @Override
    public void start() 
    	...代码省略...
    	createAndAddWindows(result);
    	...代码省略...
    

start方法会调用一个叫createAndAddWindows的关键方法,系统状态栏视图的创建和添加工作就是在该方法中完成的。

2、和createAndAddWindows方法相关的代码如下所示:

public class StatusBar extends SystemUI implements ActivityStarter, LifecycleOwner 

   private final StatusBarWindowController mStatusBarWindowController;//状态栏窗口控制器
   private final StatusBarComponent.Factory mStatusBarComponentFactory;//Dagger2状态栏组件工厂
   private StatusBarComponent mStatusBarComponent;//Dagger2状态栏子组件

   protected PhoneStatusBarView mStatusBarView;//状态栏视图
   private PhoneStatusBarViewController mPhoneStatusBarViewController;//状态栏视图控制器

    public StatusBar(
		...代码省略...
		StatusBarWindowController statusBarWindowController,//状态栏控制器
        StatusBarComponent.Factory statusBarComponentFactory,//状态栏Dagger2组件工厂
		...代码省略...
	)
		...代码省略...
		//为状态栏控制器mStatusBarWindowController赋值
        mStatusBarWindowController = statusBarWindowController;
      	//为状态栏Dagger2组件工厂mStatusBarComponentFactory赋值
        mStatusBarComponentFactory = statusBarComponentFactory;
        ...代码省略...
       

    @Override
    public void start() 
    	...代码省略...
    	createAndAddWindows(result);
    	...代码省略...
    

    public void createAndAddWindows(@Nullable RegisterStatusBarResult result) 
        makeStatusBarView(result);
        ...代码省略...
        mStatusBarWindowController.attach(

android 21 是啥版本

android每一个系统版本都对应一个编号的,21代表安卓5.0系统,23代表安卓6.0系统。

API等级15:Android 4.0.3 - 4.0.4 Ice Cream Sandwich

API等级16:Android 4.1 Jelly Bean

API等级17:Android 4.2 Jelly Bean

API等级18:Android 4.3 Jelly Bean

API等级19:Android 4.4 KitKat

API等级20:Android 4.4W

API等级21:Android 5.0 Lollipop

API等级22:Android 5.1 Lollipop

API等级23:Android 6.0 Marshmallow

扩展资料:

从2009年5月开始,Android操作系统改用甜点来作为版本代号,这些版本按照从C大写字母开始的顺序来进行命名:纸杯蛋糕(Cupcake)、甜甜圈(Donut)、闪电泡芙(Éclair)、冻酸奶(Froyo)、姜饼(Gingerbread)。

蜂巢(Honeycomb)﹑冰淇淋三明治(Ice Cream Sandwich)、果冻豆(Jelly Bean)、奇巧(KitKat)、棒棒糖(Lollipop)、棉花糖(Marshmallow)、牛轧糖(Nougat)、奥利奥(Oreo )、馅饼(Pie)。

参考资料来源:百度百科-安卓历史版本

参考技术A

android每一个系统版本都对应一个编号的


21代表安卓5.0系统,23代表安卓6.0系统,具体可以看下面的图


本回答被提问者和网友采纳
参考技术B android每一个系统版本都对应一个编号:21代表安卓5.0系统,23代表安卓6.0系统 参考技术C 一般是 20.1.0
Android 4.2 (也就是SDK 17)
参考技术D 安卓5.0

以上是关于Android 12系统源码_SystemUI系统状态栏StatusBar的创建流程的主要内容,如果未能解决你的问题,请参考以下文章

Android系统_SystemUI_android10_添加控制底部导航栏广播

Android4.2.2 动态显示隐藏屏幕底部的导航栏(对系统源码进行修改)

系统方向学习8--Android 10.0 SystemUI 状态栏屏蔽弹出的 提醒式通知

系统方向学习8--Android 10.0 SystemUI 状态栏屏蔽弹出的 提醒式通知

系统方向学习8--Android 10.0 SystemUI 状态栏屏蔽弹出的 提醒式通知

系统方向学习8--Android 10.0 SystemUI 状态栏屏蔽弹出的 提醒式通知