(一百三十五)Android O探索WLAN扫描(WIFI SCAN ALWAYS)

2023-12-19 07:38

本文主要是介绍(一百三十五)Android O探索WLAN扫描(WIFI SCAN ALWAYS),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.界面信息

小米mix2 WLAN扫描开关位于设置-更多设置-系统安全-位置信息-扫描,截图如下

 

2.流程梳理

搜索字符串

jiatai@jiatai:~/expand/aosp/aosp/packages/apps/Settings/res/values-zh-rCN$ grep "WLAN.*扫描" ./ -nr
./arrays.xml:250:    <item msgid="8281201165558093009">"WLAN扫描"</item>
./strings.xml:738:    <string name="wifi_scan_notify_text" msgid="5593805423071186757">"为了提高位置信息的精确度,系统应用和服务仍然会扫描 WLAN 网络。您可以在<xliff:g id="LINK_BEGIN_0">LINK_BEGIN</xliff:g>扫描设置<xliff:g id="LINK_END_1">LINK_END</xliff:g>中更改此设置。"</string>
./strings.xml:739:    <string name="wifi_scan_notify_text_scanning_off" msgid="3426075479272242098">"要提高位置信息的精确度,请在<xliff:g id="LINK_BEGIN_0">LINK_BEGIN</xliff:g>扫描设置<xliff:g id="LINK_END_1">LINK_END</xliff:g>中开启 WLAN 扫描功能。"</string>
./strings.xml:827:    <string name="wifi_scan_always_turnon_message" msgid="203123538572122989">"为了提高位置信息精确度以及其他目的,“<xliff:g id="APP_NAME">%1$s</xliff:g>”请求启用网络扫描功能(在关闭了WLAN时也可进行扫描)。\n\n是否对所有需要进行扫描的应用批准这项请求?"</string>
./strings.xml:1430:    <string name="location_scanning_wifi_always_scanning_title" msgid="6216705505621183645">"WLAN 扫描"</string>jiatai@jiatai:~/expand/aosp/aosp/packages/apps/Settings/res/xml$ grep "location_scanning_wifi_always_scanning_title" ./ -nr
./location_scanning.xml:22:            android:title="@string/location_scanning_wifi_always_scanning_title"
jiatai@jiatai:~/expand/aosp/aosp/packages/apps/Settings/res/xml$ vim ./location_scanning.xml
jiatai@jiatai:~/expand/aosp/aosp/packages/apps/Settings/res/xml$ cd ../../src/
jiatai@jiatai:~/expand/aosp/aosp/packages/apps/Settings/src$ grep "wifi_always_scanning" ./ -nr
./com/android/settings/location/ScanningSettings.java:32:    private static final String KEY_WIFI_SCAN_ALWAYS_AVAILABLE = "wifi_always_scanning";

之后定位到ScanningSettings这个类对应于开关的逻辑处理

2.1 ScanningSettings

 68     @Override69     public boolean onPreferenceTreeClick(Preference preference) {70         String key = preference.getKey();71         if (KEY_WIFI_SCAN_ALWAYS_AVAILABLE.equals(key)) {72             Global.putInt(getContentResolver(),73                     Global.WIFI_SCAN_ALWAYS_AVAILABLE,74                     ((SwitchPreference) preference).isChecked() ? 1 : 0);75         } else if (KEY_BLUETOOTH_SCAN_ALWAYS_AVAILABLE.equals(key)) {76             Global.putInt(getContentResolver(),77                     Global.BLE_SCAN_ALWAYS_AVAILABLE,78                     ((SwitchPreference) preference).isChecked() ? 1 : 0);79         } else {80             return super.onPreferenceTreeClick(preference);81         }82         return true;83     }

从如上代码可以看到该开关其实就是对应了一个数据库值(Global.WIFI_SCAN_ALWAYS_AVAILABLE)的变化

在framework搜索相关数据库监听

挨个看了下WifiServiceImpl中有对该数据库值(Global.WIFI_SCAN_ALWAYS_AVAILABLE)的监听

 

2.2 WifiServiceImpl

    /*** Observes settings changes to scan always mode.*/private void registerForScanModeChange() {ContentObserver contentObserver = new ContentObserver(null) {@Overridepublic void onChange(boolean selfChange) {mSettingsStore.handleWifiScanAlwaysAvailableToggled();mWifiController.sendMessage(CMD_SCAN_ALWAYS_MODE_CHANGED);}};mFrameworkFacade.registerContentObserver(mContext,Settings.Global.getUriFor(Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE),false, contentObserver);}

数据库值(Global.WIFI_SCAN_ALWAYS_AVAILABLE)的变化会触发

                mSettingsStore.handleWifiScanAlwaysAvailableToggled();mWifiController.sendMessage(CMD_SCAN_ALWAYS_MODE_CHANGED);

依次看下

 

2.3 WifiSettingsStore

    synchronized void handleWifiScanAlwaysAvailableToggled() {mScanAlwaysAvailable = getPersistedScanAlwaysAvailable();}private boolean getPersistedScanAlwaysAvailable() {return Settings.Global.getInt(mContext.getContentResolver(),Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE,0) == 1;}

WifiSettingsStore就是更新一下自己保存的局部变量mScanAlwaysAvailable与当前开关保存一致。

 

2.4 WifiController

搜索代码看了下只有三个状态会对消息CMD_SCAN_ALWAYS_MODE_CHANGED进行处理,分别是

DefaultState(不作处理)

ApStaDisabledState(若开关打开,切换到StaDisabledWithScanState)

StaDisabledWithScanState(若开关关闭,切换到ApStaDisabledState)

 

2.4.1 wifi scan always打开

    class ApStaDisabledState extends State {
...case CMD_SCAN_ALWAYS_MODE_CHANGED:if (mSettingsStore.isScanAlwaysAvailable()) {transitionTo(mStaDisabledWithScanState);}break;

 

    class StaDisabledWithScanState extends State {private int mDeferredEnableSerialNumber = 0;private boolean mHaveDeferredEnable = false;private long mDisabledTimestamp;@Overridepublic void enter() {// need to set the mode before starting supplicant because WSM will assume we are going// in to client modemWifiStateMachine.setOperationalMode(WifiStateMachine.SCAN_ONLY_WITH_WIFI_OFF_MODE);mWifiStateMachine.setSupplicantRunning(true);// Supplicant can't restart right away, so not the time we switched offmDisabledTimestamp = SystemClock.elapsedRealtime();mDeferredEnableSerialNumber++;mHaveDeferredEnable = false;mWifiStateMachine.clearANQPCache();}

从如上代码及状态之间图示可以看出状态切换只走了StaDisabledWithScanState的enter方法

简单看了就是切换到了SCAN_ONLY_WITH_WIFI_OFF_MODE并且启动了supplicant

WSM

i 切换SCAN_ONLY_WITH_WIFI_OFF_MODE

    /*** TODO: doc*/public void setOperationalMode(int mode) {if (mVerboseLoggingEnabled) log("setting operational mode to " + String.valueOf(mode));sendMessage(CMD_SET_OPERATIONAL_MODE, mode, 0);}

InitialState

                case CMD_SET_OPERATIONAL_MODE:mOperationalMode = message.arg1;if (mOperationalMode != DISABLED_MODE) {sendMessage(CMD_START_SUPPLICANT);}break;

ii 启动supplicant

    /*** TODO: doc*/public void setSupplicantRunning(boolean enable) {if (enable) {sendMessage(CMD_START_SUPPLICANT);} else {sendMessage(CMD_STOP_SUPPLICANT);}}

可以看到两步其实都下发了启动supplicant的命令,简单看起来有冗余,之后WiFi启动流程是差不多的,加载驱动-启动supplicant,从InitialState-SupplicantStartingState-SupplicantStartedState

    class SupplicantStartedState extends State {@Overridepublic void enter() {if (mVerboseLoggingEnabled) {logd("SupplicantStartedState enter");}mWifiNative.setExternalSim(true);setRandomMacOui();mCountryCode.setReadyForChange(true);// We can't do this in the constructor because WifiStateMachine is created before the// wifi scanning service is initializedif (mWifiScanner == null) {mWifiScanner = mWifiInjector.getWifiScanner();synchronized (mWifiReqCountLock) {mWifiConnectivityManager =mWifiInjector.makeWifiConnectivityManager(mWifiInfo,hasConnectionRequests());mWifiConnectivityManager.setUntrustedConnectionAllowed(mUntrustedReqCount > 0);mWifiConnectivityManager.handleScreenStateChanged(mScreenOn);}}mWifiDiagnostics.startLogging(mVerboseLoggingEnabled);mIsRunning = true;updateBatteryWorkSource(null);/*** Enable bluetooth coexistence scan mode when bluetooth connection is active.* When this mode is on, some of the low-level scan parameters used by the* driver are changed to reduce interference with bluetooth*/mWifiNative.setBluetoothCoexistenceScanMode(mBluetoothConnectionActive);// Check if there is a voice call on-going and set/reset the tx power limit// appropriately.if (mEnableVoiceCallSarTxPowerLimit) {if (getTelephonyManager().isOffhook()) {sendMessage(CMD_SELECT_TX_POWER_SCENARIO,WifiNative.TX_POWER_SCENARIO_VOICE_CALL);} else {sendMessage(CMD_SELECT_TX_POWER_SCENARIO,WifiNative.TX_POWER_SCENARIO_NORMAL);}}// initialize network statesetNetworkDetailedState(DetailedState.DISCONNECTED);// Disable legacy multicast filtering, which on some chipsets defaults to enabled.// Legacy IPv6 multicast filtering blocks ICMPv6 router advertisements which breaks IPv6// provisioning. Legacy IPv4 multicast filtering may be re-enabled later via// IpClient.Callback.setFallbackMulticastFilter()mWifiNative.stopFilteringMulticastV4Packets();mWifiNative.stopFilteringMulticastV6Packets();if (mOperationalMode == SCAN_ONLY_MODE ||mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) {mWifiNative.disconnect();setWifiState(WIFI_STATE_DISABLED);transitionTo(mScanModeState);} else if (mOperationalMode == CONNECT_MODE) {setWifiState(WIFI_STATE_ENABLING);// Transitioning to Disconnected state will trigger a scan and subsequently AutoJointransitionTo(mDisconnectedState);} else if (mOperationalMode == DISABLED_MODE) {transitionTo(mSupplicantStoppingState);}
。。。

之前梳理WiFi启动流程的时候OperationalMode都是CONNECT_MODE,之后会切换到DisconnectedState

而这次wifi scan always的OperationalMode是SCAN_ONLY_WITH_WIFI_OFF_MODE,这时会切换到ScanModeState

    class ScanModeState extends State {private int mLastOperationMode;@Overridepublic void enter() {mLastOperationMode = mOperationalMode;mWifiStateTracker.updateState(WifiStateTracker.SCAN_MODE);}@Overridepublic boolean processMessage(Message message) {logStateAndMessage(message, this);switch(message.what) {case CMD_SET_OPERATIONAL_MODE:if (message.arg1 == CONNECT_MODE) {mOperationalMode = CONNECT_MODE;setWifiState(WIFI_STATE_ENABLING);transitionTo(mDisconnectedState);} else if (message.arg1 == DISABLED_MODE) {transitionTo(mSupplicantStoppingState);}// Nothing to dobreak;// Handle scan. All the connection related commands are// handled only in ConnectModeStatecase CMD_START_SCAN:handleScanRequest(message);break;default:return NOT_HANDLED;}return HANDLED;}}

这个状态很简单,就处理两个消息,CMD_SET_OPERATIONAL_MODE和CMD_START_SCAN,主要看下CMD_START_SCAN的处理

(对比ConnectModeState可以处理CMD_START_CONNECT CMD_START_ROAM CMD_SAVE_CONFIG等等连接相关的命令)

    private void handleScanRequest(Message message) {ScanSettings settings = null;WorkSource workSource = null;// unbundle parametersBundle bundle = (Bundle) message.obj;if (bundle != null) {settings = bundle.getParcelable(CUSTOMIZED_SCAN_SETTING);workSource = bundle.getParcelable(CUSTOMIZED_SCAN_WORKSOURCE);}Set<Integer> freqs = null;if (settings != null && settings.channelSet != null) {freqs = new HashSet<>();for (WifiChannel channel : settings.channelSet) {freqs.add(channel.freqMHz);}}// Retrieve the list of hidden network SSIDs to scan for.List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworks =mWifiConfigManager.retrieveHiddenNetworkList();// call wifi native to start the scanif (startScanNative(freqs, hiddenNetworks, workSource)) {// a full scan covers everything, clearing scan request bufferif (freqs == null)mBufferedScanMsg.clear();messageHandlingStatus = MESSAGE_HANDLING_STATUS_OK;return;}// if reach here, scan request is rejectedif (!mIsScanOngoing) {// if rejection is NOT due to ongoing scan (e.g. bad scan parameters),// discard this request and pop up the next oneif (mBufferedScanMsg.size() > 0) {sendMessage(mBufferedScanMsg.remove());}messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;} else if (!mIsFullScanOngoing) {// if rejection is due to an ongoing scan, and the ongoing one is NOT a full scan,// buffer the scan request to make sure specified channels will be scanned eventuallyif (freqs == null)mBufferedScanMsg.clear();if (mBufferedScanMsg.size() < SCAN_REQUEST_BUFFER_MAX_SIZE) {Message msg = obtainMessage(CMD_START_SCAN,message.arg1, message.arg2, bundle);mBufferedScanMsg.add(msg);} else {// if too many requests in buffer, combine them into a single full scanbundle = new Bundle();bundle.putParcelable(CUSTOMIZED_SCAN_SETTING, null);bundle.putParcelable(CUSTOMIZED_SCAN_WORKSOURCE, workSource);Message msg = obtainMessage(CMD_START_SCAN, message.arg1, message.arg2, bundle);mBufferedScanMsg.clear();mBufferedScanMsg.add(msg);}messageHandlingStatus = MESSAGE_HANDLING_STATUS_LOOPED;} else {// mIsScanOngoing and mIsFullScanOngoingmessageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;}}

这里还可以看到

        // Retrieve the list of hidden network SSIDs to scan for.List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworks =mWifiConfigManager.retrieveHiddenNetworkList();

这边应该是可以让扫描可以扫描到隐藏网络的相关代码,梳理待续

可以理解为ScanModeState主要就处理扫描请求,和其所处模式SCAN_ONLY_WITH_WIFI_OFF_MODE的描述很相符,WiFi关闭情况下只进行扫描。

 

2.4.1 wifi scan always关闭

WifiController

    class ApStaDisabledState extends State {private int mDeferredEnableSerialNumber = 0;private boolean mHaveDeferredEnable = false;private long mDisabledTimestamp;@Overridepublic void enter() {mWifiStateMachine.setSupplicantRunning(false);// Supplicant can't restart right away, so not the time we switched offmDisabledTimestamp = SystemClock.elapsedRealtime();mDeferredEnableSerialNumber++;mHaveDeferredEnable = false;mWifiStateMachine.clearANQPCache();}

这边看来就是将supplicant关闭即可

WSM ScanModeState的父状态为SupplicantStartedState,由于ScanModeState无法处理CMD_STOP_SUPPLICANT,由其父状态SupplicantStartedState处理。

    class SupplicantStartedState extends State {
...@Overridepublic boolean processMessage(Message message) {logStateAndMessage(message, this);switch(message.what) {case CMD_STOP_SUPPLICANT:   /* Supplicant stopped by user */if (mP2pSupported) {transitionTo(mWaitForP2pDisableState);} else {transitionTo(mSupplicantStoppingState);}break;
...@Overridepublic void exit() {mWifiDiagnostics.stopLogging();mIsRunning = false;updateBatteryWorkSource(null);mScanResults = new ArrayList<>();final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE);intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_DISABLED);mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);mBufferedScanMsg.clear();mNetworkInfo.setIsAvailable(false);if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo);mCountryCode.setReadyForChange(false);}}

切换到SupplicantStoppingState

    class SupplicantStoppingState extends State {@Overridepublic void enter() {/* Send any reset commands to supplicant before shutting it down */handleNetworkDisconnect();String suppState = System.getProperty("init.svc.wpa_supplicant");if (suppState == null) suppState = "unknown";setWifiState(WIFI_STATE_DISABLING);mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE);logd("SupplicantStoppingState: disableSupplicant "+ " init.svc.wpa_supplicant=" + suppState);if (mWifiNative.disableSupplicant()) {mWifiNative.closeSupplicantConnection();sendSupplicantConnectionChangedBroadcast(false);setWifiState(WIFI_STATE_DISABLED);} else {// Failed to disable supplicanthandleSupplicantConnectionLoss(true);}transitionTo(mInitialState);}}

关闭supplicant后切换到InitialState状态

    class InitialState extends State {private void cleanup() {// Tearing down the client interfaces below is going to stop our supplicant.mWifiMonitor.stopAllMonitoring();mDeathRecipient.unlinkToDeath();mWifiNative.tearDown();}@Overridepublic void enter() {mWifiStateTracker.updateState(WifiStateTracker.INVALID);cleanup();}

流程处理完毕。

 

3.总结

WIFI SCAN ALWAYS对应模式为SCAN_ONLY_WITH_WIFI_OFF_MODE,SCAN_ONLY_WITH_WIFI_OFF_MODE顾名思义WiFi关闭情况下只处理扫描请求。

这篇关于(一百三十五)Android O探索WLAN扫描(WIFI SCAN ALWAYS)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Android中Dialog的使用详解

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

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

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

Android自定义Scrollbar的两种实现方式

《Android自定义Scrollbar的两种实现方式》本文介绍两种实现自定义滚动条的方法,分别通过ItemDecoration方案和独立View方案实现滚动条定制化,文章通过代码示例讲解的非常详细,... 目录方案一:ItemDecoration实现(推荐用于RecyclerView)实现原理完整代码实现

Android App安装列表获取方法(实践方案)

《AndroidApp安装列表获取方法(实践方案)》文章介绍了Android11及以上版本获取应用列表的方案调整,包括权限配置、白名单配置和action配置三种方式,并提供了相应的Java和Kotl... 目录前言实现方案         方案概述一、 androidManifest 三种配置方式

Vue 调用摄像头扫描条码功能实现代码

《Vue调用摄像头扫描条码功能实现代码》本文介绍了如何使用Vue.js和jsQR库来实现调用摄像头并扫描条码的功能,通过安装依赖、获取摄像头视频流、解析条码等步骤,实现了从开始扫描到停止扫描的完整流... 目录实现步骤:代码实现1. 安装依赖2. vue 页面代码功能说明注意事项以下是一个基于 Vue.js

Android WebView无法加载H5页面的常见问题和解决方法

《AndroidWebView无法加载H5页面的常见问题和解决方法》AndroidWebView是一种视图组件,使得Android应用能够显示网页内容,它基于Chromium,具备现代浏览器的许多功... 目录1. WebView 简介2. 常见问题3. 网络权限设置4. 启用 JavaScript5. D

Android如何获取当前CPU频率和占用率

《Android如何获取当前CPU频率和占用率》最近在优化App的性能,需要获取当前CPU视频频率和占用率,所以本文小编就来和大家总结一下如何在Android中获取当前CPU频率和占用率吧... 最近在优化 App 的性能,需要获取当前 CPU视频频率和占用率,通过查询资料,大致思路如下:目前没有标准的

Android开发中gradle下载缓慢的问题级解决方法

《Android开发中gradle下载缓慢的问题级解决方法》本文介绍了解决Android开发中Gradle下载缓慢问题的几种方法,本文给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧... 目录一、网络环境优化二、Gradle版本与配置优化三、其他优化措施针对android开发中Gradle下载缓慢的问

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

pip install jupyterlab失败的原因问题及探索

《pipinstalljupyterlab失败的原因问题及探索》在学习Yolo模型时,尝试安装JupyterLab但遇到错误,错误提示缺少Rust和Cargo编译环境,因为pywinpty包需要它... 目录背景问题解决方案总结背景最近在学习Yolo模型,然后其中要下载jupyter(有点LSVmu像一个