Android 10.0 状态栏系统图标显示分析

2024-08-27 02:44

本文主要是介绍Android 10.0 状态栏系统图标显示分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

SystemUI中StatusBar的图标控制器实现类为StatusBarIconControllerImpl,其继承了StatusBarIconController的接口,用于跟踪所有图标的状态,并将对应的状态发送给注册的图标管理器(IconManagers)。当我们在StatusBar中获取到它的实例后,还会将它传给PhoneStatusBarPolicy和StatusBarSignalPolicy对象。PhoneStatusBarPolicy控制启动时装载哪些图标(蓝牙,定位等),而StatusBarSignalPolicy控制网络信号图标(移动网络,WiFi,以太网)的变化。
一起来看 StatuBar 的 start() 方法:
frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarSignalPolicy.java

@Override
public void start() {// 省略部分代码......// 创建整个SystemUI视图并添加到WindowManager中createAndAddWindows();//这个重点方法,创建相关的视图// 省略部分代码......// Lastly, call to the icon policy to install/update all the icons.mIconPolicy.init();mSignalPolicy = new StatusBarSignalPolicy(mContext, mIconController);// 省略部分代码......
}

这里的 mIconPolicy 就是 PhoneStatusBarPolicy对象,mSignalPolicy 就是 StatusBarSignalPolicy 对象。我们这里以 StatusBarSignalPolicy 为例去研究。
StatusBarSignalPolicy实现了NetworkControllerImpl.SignalCallback接口,SignalCallback接口定义在NetworkControllerImpl实现的接口NetworkController中。
frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java

    @Injectpublic NetworkControllerImpl(Context context, @Background Looper bgLooper,DeviceProvisionedController deviceProvisionedController,BroadcastDispatcher broadcastDispatcher, ConnectivityManager connectivityManager,TelephonyManager telephonyManager, WifiManager wifiManager,NetworkScoreManager networkScoreManager) {this(context, connectivityManager,telephonyManager,wifiManager,networkScoreManager,SubscriptionManager.from(context), Config.readConfig(context), bgLooper,new CallbackHandler(),new AccessPointControllerImpl(context),new DataUsageController(context),new SubscriptionDefaults(),deviceProvisionedController,broadcastDispatcher);mReceiverHandler.post(mRegisterListeners);}private final Runnable mRegisterListeners = new Runnable() {@Overridepublic void run() {registerListeners();}};void registerListeners() {for (int i = 0; i < mMobileSignalControllers.size(); i++) {MobileSignalController mobileSignalController = mMobileSignalControllers.valueAt(i);mobileSignalController.registerListener();}if (mSubscriptionListener == null) {mSubscriptionListener = new SubListener();}mSubscriptionManager.addOnSubscriptionsChangedListener(mSubscriptionListener);mPhone.listen(mPhoneStateListener, LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE);// broadcastsIntentFilter filter = new IntentFilter();// wifi相关// wifi信号强度广播filter.addAction(WifiManager.RSSI_CHANGED_ACTION);// wifi状态变化广播filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);// wifi连接状态改变filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);// 移动网络相关// SIM卡状态改变filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);// 数据语音订阅修改filter.addAction(TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED);filter.addAction(TelephonyIntents.ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED);filter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);filter.addAction(TelephonyIntents.SPN_STRINGS_UPDATED_ACTION);// 连接状态相关// 网络连接状态发生变化filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);// 网络连接可能不好filter.addAction(ConnectivityManager.INET_CONDITION_ACTION);// 切换飞行模式时filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);filter.addAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);mContext.registerReceiver(this, filter, null, mReceiverHandler);mListening = true;// 省略部分代码......// 4.更新移动网络控制器updateMobileControllers();}

在NetworkControllerImpl 的构造方法里,最终会调用到:registerListeners() 方法进行广播的注册。
广播处理:
frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java

@Override
public void onReceive(Context context, Intent intent) {if (CHATTY) {Log.d(TAG, "onReceive: intent=" + intent);}final String action = intent.getAction();switch (action) {case ConnectivityManager.CONNECTIVITY_ACTION:case ConnectivityManager.INET_CONDITION_ACTION:// 省略部分代码......break;case Intent.ACTION_AIRPLANE_MODE_CHANGED:// 省略部分代码......break;case TelephonyManager.ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED:// We are using different subs now, we might be able to make calls.// 省略部分代码......break;case TelephonyManager.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED:// Notify every MobileSignalController so they can know whether they are the// data sim or not.// 省略部分代码......break;case Intent.ACTION_SIM_STATE_CHANGED:// Avoid rebroadcast because SysUI is direct boot aware.// 省略部分代码......break;case Intent.ACTION_SERVICE_STATE:// 省略部分代码......break;case CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED:// 省略部分代码......break;case ImsManager.ACTION_IMS_SERVICE_UP:case ImsManager.ACTION_IMS_SERVICE_DOWN:// 省略部分代码......break;case ACTION_HIGH_DEF_AUDIO_SUPPORT:// 省略部分代码......break;case ACTION_MODEM_CHANGE:// 省略部分代码......break;default:int subId = intent.getIntExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX,SubscriptionManager.INVALID_SUBSCRIPTION_ID);if (SubscriptionManager.isValidSubscriptionId(subId)) {if (mMobileSignalControllers.indexOfKey(subId) >= 0) {mMobileSignalControllers.get(subId).handleBroadcast(intent);} else {// Can't find this subscription...  We must be out of date.updateMobileControllers();}} else {// wifi状态图标处理// No sub id, must be for the wifi.mWifiSignalController.handleBroadcast(intent);}break;}
}

这里以 wifi状态图标处理 为例;接下来看WifiSignalController#handleBroadcast():
frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/policy/WifiSignalController.java

public void handleBroadcast(Intent intent) {mWifiTracker.handleBroadcast(intent);mCurrentState.enabled = mWifiTracker.enabled;mCurrentState.connected = mWifiTracker.connected;mCurrentState.ssid = mWifiTracker.ssid;mCurrentState.rssi = mWifiTracker.rssi;mCurrentState.level = mWifiTracker.level;mCurrentState.statusLabel = mWifiTracker.statusLabel;notifyListenersIfNecessary();
}

在WifiSignalController#handleBroadcast()方法中,就两个实现,一个是获取 WiFi 的状态,一个是通知更新状态。
我们直接看通知SignalController# notifyListenersIfNecessary() :
frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/policy/SignalController.java

public void notifyListenersIfNecessary() {if (isDirty()) {saveLastState();    // 保持此时的状态notifyListeners();    // 通知监听器}
}
public final void notifyListeners() {notifyListeners(mCallbackHandler);
}
public abstract void notifyListeners(SignalCallback callback);

notifyListener()方法的实现在WifiSignalController类中:
frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/policy/WifiSignalController.java

@Override
public void notifyListeners(SignalCallback callback) {// only show wifi in the cluster if connected or if wifi-onlyboolean visibleWhenEnabled = mContext.getResources().getBoolean(R.bool.config_showWifiIndicatorWhenEnabled);boolean wifiVisible = mCurrentState.enabled && ((mCurrentState.connected && mCurrentState.inetCondition == 1)|| !mHasMobileDataFeature || mWifiTracker.isDefaultNetwork|| visibleWhenEnabled);String wifiDesc = mCurrentState.connected ? mCurrentState.ssid : null;boolean ssidPresent = wifiVisible && mCurrentState.ssid != null;String contentDescription = getTextIfExists(getContentDescription()).toString();if (mCurrentState.inetCondition == 0) {contentDescription += ("," + mContext.getString(R.string.data_connection_no_internet));}IconState statusIcon = new IconState(wifiVisible, getCurrentIconId(), contentDescription);IconState qsIcon = new IconState(mCurrentState.connected,mWifiTracker.isCaptivePortal ? R.drawable.ic_qs_wifi_disconnected: getQsCurrentIconId(), contentDescription);// callback为 CallbackHandler对象callback.setWifiIndicators(mCurrentState.enabled, statusIcon, qsIcon,ssidPresent && mCurrentState.activityIn, ssidPresent && mCurrentState.activityOut,wifiDesc, mCurrentState.isTransient, mCurrentState.statusLabel);
}

可以看到,这里回调了StatusBarSignalPolicy#setWifiIndicators() 方法:
frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarSignalPolicy.java

@Override
public void setWifiIndicators(boolean enabled, IconState statusIcon, IconState qsIcon,boolean activityIn, boolean activityOut, String description, boolean isTransient,String statusLabel) {boolean visible = statusIcon.visible && !mBlockWifi;boolean in = activityIn && mActivityEnabled && visible;boolean out = activityOut && mActivityEnabled && visible;WifiIconState newState = mWifiIconState.copy();newState.visible = visible;newState.resId = statusIcon.icon;newState.activityIn = in;newState.activityOut = out;newState.slot = mSlotWifi;newState.airplaneSpacerVisible = mIsAirplaneMode;newState.contentDescription = statusIcon.contentDescription;MobileIconState first = getFirstMobileState();newState.signalSpacerVisible = first != null && first.typeId != 0;updateWifiIconWithState(newState);mWifiIconState = newState;
}
private void updateWifiIconWithState(WifiIconState state) {if (state.visible && state.resId > 0) {mIconController.setSignalIcon(mSlotWifi, state);mIconController.setIconVisibility(mSlotWifi, true);} else {mIconController.setIconVisibility(mSlotWifi, false);}
}

通过StatusBarIconController接口设置图标的套路都是一样的:

  • 获取图标名字
  • 监听事件
  • 通过StatusBarIconControllerImpl相应的方法设置图标。
    接下来再看StatusBarIconControllerImpl#setSignalIcon():
    frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconControllerImpl.java
/*** Signal icons need to be handled differently, because they can be* composite views*/
@Override
public void setSignalIcon(String slot, WifiIconState state) {int index = getSlotIndex(slot);if (state == null) {removeIcon(index, 0);return;}StatusBarIconHolder holder = getIcon(index, 0);if (holder == null) {holder = StatusBarIconHolder.fromWifiIconState(state);setIcon(index, holder);} else {holder.setWifiState(state);handleSet(index, holder);}
}

首先设置WiFi的状态信息,遍历mIconGroups分别执行StatusBarIconController接口中静态类IconManager中的onIconAdded()和onSetIconHolder()的回调。
IconManager用于将信息从StatusBarIconController转换为ViewGroup中的ImageViews(com.android.systemui.statusbar.AlphaOptimizedImageView)。
接着看IconManager中的onIconAdded()和onSetIconHolder()方法:这两个方法一个用于添加、一个用于更新。
frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarIconController.java

public interface StatusBarIconController {....public static class DarkIconManager extends IconManager {....public DarkIconManager(LinearLayout linearLayout) {// 将布局传入IconManagersuper(linearLayout);mIconHPadding = mContext.getResources().getDimensionPixelSize(R.dimen.status_bar_icon_padding);mDarkIconDispatcher = Dependency.get(DarkIconDispatcher.class);}....@Overrideprotected void onIconAdded(int index, String slot, boolean blocked,StatusBarIconHolder holder) {// 调用到父类的addHolder方法StatusIconDisplayable view = addHolder(index, slot, blocked, holder);....}}public static class IconManager implements DemoMode {....protected final ViewGroup mGroup;protected final Context mContext;public IconManager(ViewGroup group) {mGroup = group;mContext = group.getContext();mIconSize = mContext.getResources().getDimensionPixelSize(R.dimen.status_bar_height);....}....protected StatusIconDisplayable addHolder(int index, String slot, boolean blocked,StatusBarIconHolder holder) {switch (holder.getType()) {case TYPE_ICON:return addIcon(index, slot, blocked, holder.getIcon());case TYPE_WIFI:return addSignalIcon(index, slot, holder.getWifiState());case TYPE_MOBILE:return addMobileIcon(index, slot, holder.getMobileState());}return null;}@VisibleForTestingprotected StatusBarWifiView addSignalIcon(int index, String slot, WifiIconState state) {// 创建一个StatusBarWifiView StatusBarWifiView view = onCreateStatusBarWifiView(slot);view.applyWifiState(state);// 将view 添加进ViewGroupmGroup.addView(view, index, onCreateLayoutParams());if (mIsInDemoMode) {mDemoStatusIcons.addDemoWifiView(state);}return view;}private StatusBarWifiView onCreateStatusBarWifiView(String slot) {StatusBarWifiView view = StatusBarWifiView.fromContext(mContext, slot);return view;}....public void onSetIconHolder(int viewIndex, StatusBarIconHolder holder) {switch (holder.getType()) {case TYPE_ICON:onSetIcon(viewIndex, holder.getIcon());return;case TYPE_WIFI:onSetSignalIcon(viewIndex, holder.getWifiState());return;case TYPE_MOBILE:onSetMobileIcon(viewIndex, holder.getMobileState());default:break;}}public void onSetSignalIcon(int viewIndex, WifiIconState state) {StatusBarWifiView wifiView = (StatusBarWifiView) mGroup.getChildAt(viewIndex);if (wifiView != null) {wifiView.applyWifiState(state);}if (mIsInDemoMode) {mDemoStatusIcons.updateWifiState(state);}}....}}

这里根据不同的StatusBarIconHolder类型,设置不同的网络Icon,上面列出了 Wifi 图标相关的方法。
SystemUI状态栏图标根据源码可大体分为三种:

  1. StatusBarIconView
  2. StatusBarWifiView
  3. StatusBarMobileView

这里主要以Wifi 相关图标(StatusBarWifiView)进行分析,添加Icon时首先会创建一个
StatusBarWifiView,然后调用StatusBarWifiView的applyWifiState更新其显示状态,最后将其加入到CollapsedStatusBarFragment中放置Icon的ViewGroup中,这样就完成了添加过程;
再来看看 CollapsedStatusBarFragment:
SystemUI/src/com/android/systemui/statusbar/phone/CollapsedStatusBarFragment.java

public class CollapsedStatusBarFragment extends Fragment implements CommandQueue.Callbacks {....private DarkIconManager mDarkIconManager;....@Overridepublic View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.status_bar, container, false);}@Overridepublic void onViewCreated(View view, @Nullable Bundle savedInstanceState) {....// 这里可以看出status_bar布局中的statusIcons就是我们展示各种Icon的区域mDarkIconManager = new DarkIconManager(view.findViewById(R.id.statusIcons));mDarkIconManager.setShouldLog(true);Dependency.get(StatusBarIconController.class).addIconGroup(mDarkIconManager);....   }
}

补充:
notifyListenersIfNecessary()在其父类SignalController中定义,
frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/policy/SignalController.java

    private final CallbackHandler mCallbackHandler;public void notifyListenersIfNecessary() {if (isDirty()) {saveLastState();notifyListeners();}}// 在这里注意了,在这里的的参数是 CallbackHandler 的对象public final void notifyListeners() {notifyListeners(mCallbackHandler);}
// callback 则是 CallbackHandler 的对象。public abstract void notifyListeners(SignalCallback callback);

CallbackHandler维护了所有需要监听的SignalCallback接口对象,我们的StatusBarSignalPolicy就实现了该接口。
StatusBarSignalPolicy主要执行网络图标的刷新动作,其实现了NetworkControllerImpl.SignalCallback接口,然后注册到NetworkController,其具体实现类NetworkControllerImpl会根据WIFI,SIM等状态广播来进一步派发给具体的Controller,例如WifiSignalController,每个Controller只与CallbackHandler交互,然后CallbackHandler继续转交给维护的SignalCallback接口的具体实现类,例如StatusBarSignalPolicy

这篇关于Android 10.0 状态栏系统图标显示分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1110407

相关文章

Go标准库常见错误分析和解决办法

《Go标准库常见错误分析和解决办法》Go语言的标准库为开发者提供了丰富且高效的工具,涵盖了从网络编程到文件操作等各个方面,然而,标准库虽好,使用不当却可能适得其反,正所谓工欲善其事,必先利其器,本文将... 目录1. 使用了错误的time.Duration2. time.After导致的内存泄漏3. jsO

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

Linux系统中卸载与安装JDK的详细教程

《Linux系统中卸载与安装JDK的详细教程》本文详细介绍了如何在Linux系统中通过Xshell和Xftp工具连接与传输文件,然后进行JDK的安装与卸载,安装步骤包括连接Linux、传输JDK安装包... 目录1、卸载1.1 linux删除自带的JDK1.2 Linux上卸载自己安装的JDK2、安装2.1

Android中Dialog的使用详解

《Android中Dialog的使用详解》Dialog(对话框)是Android中常用的UI组件,用于临时显示重要信息或获取用户输入,本文给大家介绍Android中Dialog的使用,感兴趣的朋友一起... 目录android中Dialog的使用详解1. 基本Dialog类型1.1 AlertDialog(

macOS无效Launchpad图标轻松删除的4 种实用方法

《macOS无效Launchpad图标轻松删除的4种实用方法》mac中不在appstore上下载的应用经常在删除后它的图标还残留在launchpad中,并且长按图标也不会出现删除符号,下面解决这个问... 在 MACOS 上,Launchpad(也就是「启动台」)是一个便捷的 App 启动工具。但有时候,应

Spring事务中@Transactional注解不生效的原因分析与解决

《Spring事务中@Transactional注解不生效的原因分析与解决》在Spring框架中,@Transactional注解是管理数据库事务的核心方式,本文将深入分析事务自调用的底层原理,解释为... 目录1. 引言2. 事务自调用问题重现2.1 示例代码2.2 问题现象3. 为什么事务自调用会失效3

找不到Anaconda prompt终端的原因分析及解决方案

《找不到Anacondaprompt终端的原因分析及解决方案》因为anaconda还没有初始化,在安装anaconda的过程中,有一行是否要添加anaconda到菜单目录中,由于没有勾选,导致没有菜... 目录问题原因问http://www.chinasem.cn题解决安装了 Anaconda 却找不到 An

Spring定时任务只执行一次的原因分析与解决方案

《Spring定时任务只执行一次的原因分析与解决方案》在使用Spring的@Scheduled定时任务时,你是否遇到过任务只执行一次,后续不再触发的情况?这种情况可能由多种原因导致,如未启用调度、线程... 目录1. 问题背景2. Spring定时任务的基本用法3. 为什么定时任务只执行一次?3.1 未启用

Android Kotlin 高阶函数详解及其在协程中的应用小结

《AndroidKotlin高阶函数详解及其在协程中的应用小结》高阶函数是Kotlin中的一个重要特性,它能够将函数作为一等公民(First-ClassCitizen),使得代码更加简洁、灵活和可... 目录1. 引言2. 什么是高阶函数?3. 高阶函数的基础用法3.1 传递函数作为参数3.2 Lambda

Linux系统之主机网络配置方式

《Linux系统之主机网络配置方式》:本文主要介绍Linux系统之主机网络配置方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、查看主机的网络参数1、查看主机名2、查看IP地址3、查看网关4、查看DNS二、配置网卡1、修改网卡配置文件2、nmcli工具【通用