Android N selectQualifiedNetwork分析
前言:
参考:Android N wifi auto connect流程分析
后续
分析
前面说了,handleScanResults会去调QualifiedNetworkSelector.selectQualifiedNetwork去筛选目标ssid,selectQualifiedNetwork是网络的选择算法,我们分析下它的原理
1、判断是否需要needQualifiedNetworkSelection,如果返回false,代表
- scanDetails=null or isLinkDebouncing
- or skipQualifiedNetworkSelectionForAutoConnect(auto connect disabled)
- or connecting/disconnecting or WifiConfiguration=null
- or not allowed to switch network
- or short time pass since last select
2、迭代所有扫描结果,找到得分最高的最佳候选人
- ssid=null, add to noValidSsid, ignore
- isBlackListed() ignore, addToBlacklist(bssid) will add to blackList
- too weak signal strength add to lowSignalScan, ignore 2.4G level<-85 5G level<-85
- 未保存的网络(添加到notSavedScan)或保存但短暂,忽略
- 计算每个关联网络不是短暂的扫描结果的得分。由于一个扫描结果可以关联多个网络,我们需要计算所有,并使用最高的一个作为扫描结果的分数。
3、现在我们需要遍历整个用户偏好来选择一个用户最喜欢的
public WifiConfiguration selectQualifiedNetwork(boolean forceSelectNetwork ,
boolean isUntrustedConnectionsAllowed, List<ScanDetail> scanDetails,
boolean isLinkDebouncing, boolean isConnected, boolean isDisconnected,
boolean isSupplicantTransient) {
localLog("==========start qualified Network Selection==========");
mScanDetails = scanDetails;
List<Pair<ScanDetail, WifiConfiguration>> filteredScanDetails = new ArrayList<>();
if (mCurrentConnectedNetwork == null) {
mCurrentConnectedNetwork =
mWifiConfigManager.getWifiConfiguration(mWifiInfo.getNetworkId());
}
// Always get the current BSSID from WifiInfo in case that firmware initiated roaming
// happened.
mCurrentBssid = mWifiInfo.getBSSID();
/*1.判断是否需要needQualifiedNetworkSelection,如果返回false,代表
* -scanDetails=null or isLinkDebouncing
* -or skipQualifiedNetworkSelectionForAutoConnect(auto connect disabled)
* -or connecting/disconnecting or WifiConfiguration=null
* -or not allowed to switch network
* -or short time pass since last select
*/
if (!forceSelectNetwork && !needQualifiedNetworkSelection(isLinkDebouncing, isConnected,
isDisconnected, isSupplicantTransient)) {
localLog("Quit qualified Network Selection since it is not forced and current network"
+ " is qualified already");
mFilteredScanDetails = filteredScanDetails;
return null;
}
int currentHighestScore = Integer.MIN_VALUE;
ScanResult scanResultCandidate = null;
WifiConfiguration networkCandidate = null;
final ExternalScoreEvaluator externalScoreEvaluator =
new ExternalScoreEvaluator(mLocalLog, mDbg);
String lastUserSelectedNetWorkKey = mWifiConfigManager.getLastSelectedConfiguration();
WifiConfiguration lastUserSelectedNetwork =
mWifiConfigManager.getWifiConfiguration(lastUserSelectedNetWorkKey);
if (lastUserSelectedNetwork != null) {
localLog("Last selection is " + lastUserSelectedNetwork.SSID + " Time to now: "
+ ((mClock.elapsedRealtime() - mWifiConfigManager.getLastSelectedTimeStamp())
/ 1000 / 60 + " minutes"));
}
updateSavedNetworkSelectionStatus();
updateBssidBlacklist();
StringBuffer lowSignalScan = new StringBuffer();
StringBuffer notSavedScan = new StringBuffer();
StringBuffer noValidSsid = new StringBuffer();
StringBuffer scoreHistory = new StringBuffer();
ArrayList<NetworkKey> unscoredNetworks = new ArrayList<NetworkKey>();
//iterate all scan results and find the best candidate with the highest score
//2.迭代所有扫描结果,找到得分最高的最佳候选人
for (ScanDetail scanDetail : mScanDetails) {
ScanResult scanResult = scanDetail.getScanResult();
//skip bad scan result
//2.1 ssid=null, add to noValidSsid, ignore
if (scanResult.SSID == null || TextUtils.isEmpty(scanResult.SSID)) {
if (mDbg) {
//We should not see this in ePNO
noValidSsid.append(scanResult.BSSID + " / ");
}
continue;
}
final String scanId = toScanId(scanResult);
//check whether this BSSID is blocked or not
//2.2 isBlackListed() ignore, addToBlacklist(bssid) will add to blackList
if (mWifiConfigManager.isBssidBlacklisted(scanResult.BSSID)
|| isBssidDisabled(scanResult.BSSID)) {
//We should not see this in ePNO
Log.e(TAG, scanId + " is in blacklist.");
continue;
}
//skip scan result with too weak signals
//2.3 too weak signal strength add to lowSignalScan, ignore 2.4G level<-85 5G level<-85
if ((scanResult.is24GHz() && scanResult.level
< mWifiConfigManager.mThresholdMinimumRssi24.get())
|| (scanResult.is5GHz() && scanResult.level
< mWifiConfigManager.mThresholdMinimumRssi5.get())) {
if (mDbg) {
lowSignalScan.append(scanId + "(" + (scanResult.is24GHz() ? "2.4GHz" : "5GHz")
+ ")" + scanResult.level + " / ");
}
continue;
}
//check if there is already a score for this network
if (mNetworkScoreCache != null && !mNetworkScoreCache.isScoredNetwork(scanResult)) {
//no score for this network yet.
WifiKey wifiKey;
try {
wifiKey = new WifiKey("\"" + scanResult.SSID + "\"", scanResult.BSSID);
NetworkKey ntwkKey = new NetworkKey(wifiKey);
//add to the unscoredNetworks list so we can request score later
unscoredNetworks.add(ntwkKey);
} catch (IllegalArgumentException e) {
Log.w(TAG, "Invalid SSID=" + scanResult.SSID + " BSSID=" + scanResult.BSSID
+ " for network score. Skip.");
}
}
//check whether this scan result belong to a saved network
//2.4 未保存的网络(添加到notSavedScan)或保存但短暂,忽略
boolean potentiallyEphemeral = false;
// Stores WifiConfiguration of potential connection candidates for scan result filtering
WifiConfiguration potentialEphemeralCandidate = null;
List<WifiConfiguration> associatedWifiConfigurations =
mWifiConfigManager.updateSavedNetworkWithNewScanDetail(scanDetail,
isSupplicantTransient || isConnected || isLinkDebouncing);
if (associatedWifiConfigurations == null) {
potentiallyEphemeral = true;
if (mDbg) {
notSavedScan.append(scanId + " / ");
}
} else if (associatedWifiConfigurations.size() == 1) {
//if there are more than 1 associated network, it must be a passpoint network
WifiConfiguration network = associatedWifiConfigurations.get(0);
if (network.ephemeral) {
potentialEphemeralCandidate = network;
potentiallyEphemeral = true;
}
}
// Evaluate the potentially ephemeral network as a possible candidate if untrusted
// connections are allowed and we have an external score for the scan result.
if (potentiallyEphemeral) {
if (isUntrustedConnectionsAllowed) {
Integer netScore = getNetworkScore(scanResult, false);
if (netScore != null
&& !mWifiConfigManager.wasEphemeralNetworkDeleted(scanResult.SSID)) {
externalScoreEvaluator.evalUntrustedCandidate(netScore, scanResult);
// scanDetail is for available ephemeral network
filteredScanDetails.add(Pair.create(scanDetail,
potentialEphemeralCandidate));
}
}
continue;
}
// 2.5 计算每个关联网络不是短暂的扫描结果的得分。由于一个扫描结果可以关联多个网络,
//我们需要计算所有,并使用最高的一个作为扫描结果的分数。
// calculate the score of each scanresult whose associated network is not ephemeral. Due
// to one scan result can associated with more than 1 network, we need calculate all
// the scores and use the highest one as the scanresults score.
int highestScore = Integer.MIN_VALUE;
int score;
WifiConfiguration configurationCandidateForThisScan = null;
WifiConfiguration potentialCandidate = null;
for (WifiConfiguration network : associatedWifiConfigurations) {
WifiConfiguration.NetworkSelectionStatus status =
network.getNetworkSelectionStatus();
status.setSeenInLastQualifiedNetworkSelection(true);
if (potentialCandidate == null) {
potentialCandidate = network;
}
if (!status.isNetworkEnabled()) {
continue;
} else if (network.BSSID != null && !network.BSSID.equals("any")
&& !network.BSSID.equals(scanResult.BSSID)) {
//in such scenario, user (APP) has specified the only BSSID to connect for this
// configuration. So only the matched scan result can be candidate
localLog("Network: " + getNetworkString(network) + " has specified" + "BSSID:"
+ network.BSSID + ". Skip " + scanResult.BSSID);
continue;
}
// If the network is marked to use external scores then attempt to fetch the score.
// These networks will not be considered alongside the other saved networks.
if (network.useExternalScores) {
Integer netScore = getNetworkScore(scanResult, false);
externalScoreEvaluator.evalSavedCandidate(netScore, network, scanResult);
continue;
}
score = calculateBssidScore(scanResult, network, mCurrentConnectedNetwork,
(mCurrentBssid == null ? false : mCurrentBssid.equals(scanResult.BSSID)),
(lastUserSelectedNetwork == null ? false : lastUserSelectedNetwork.networkId
== network.networkId), scoreHistory);
if (score > highestScore) {
highestScore = score;
configurationCandidateForThisScan = network;
potentialCandidate = network;
}
//update the cached candidate
if (score > status.getCandidateScore() || (score == status.getCandidateScore()
&& status.getCandidate() != null
&& scanResult.level > status.getCandidate().level)) {
status.setCandidate(scanResult);
status.setCandidateScore(score);
}
}
// Create potential filteredScanDetail entry
filteredScanDetails.add(Pair.create(scanDetail, potentialCandidate));
if (highestScore > currentHighestScore || (highestScore == currentHighestScore
&& scanResultCandidate != null
&& scanResult.level > scanResultCandidate.level)) {
currentHighestScore = highestScore;
scanResultCandidate = scanResult;
networkCandidate = configurationCandidateForThisScan;
networkCandidate.getNetworkSelectionStatus().setCandidate(scanResultCandidate);
}
}
mFilteredScanDetails = filteredScanDetails;
//kick the score manager if there is any unscored network
if (mScoreManager != null && unscoredNetworks.size() != 0) {
NetworkKey[] unscoredNetworkKeys =
unscoredNetworks.toArray(new NetworkKey[unscoredNetworks.size()]);
mScoreManager.requestScores(unscoredNetworkKeys);
}
if (mDbg) {
localLog(lowSignalScan + " skipped due to low signal\n");
localLog(notSavedScan + " skipped due to not saved\n ");
localLog(noValidSsid + " skipped due to not valid SSID\n");
localLog(scoreHistory.toString());
}
//we need traverse the whole user preference to choose the one user like most now
//2.6 现在我们需要遍历整个用户偏好来选择一个用户最喜欢的
if (scanResultCandidate != null) {
WifiConfiguration tempConfig = networkCandidate;
while (tempConfig.getNetworkSelectionStatus().getConnectChoice() != null) {
String key = tempConfig.getNetworkSelectionStatus().getConnectChoice();
tempConfig = mWifiConfigManager.getWifiConfiguration(key);
if (tempConfig != null) {
WifiConfiguration.NetworkSelectionStatus tempStatus =
tempConfig.getNetworkSelectionStatus();
if (tempStatus.getCandidate() != null && tempStatus.isNetworkEnabled()) {
scanResultCandidate = tempStatus.getCandidate();
networkCandidate = tempConfig;
}
} else {
//we should not come here in theory
localLoge("Connect choice: " + key + " has no corresponding saved config");
break;
}
}
localLog("After user choice adjust, the final candidate is:"
+ getNetworkString(networkCandidate) + " : " + scanResultCandidate.BSSID);
}
// At this point none of the saved networks were good candidates so we fall back to
// externally scored networks if any are available.
if (scanResultCandidate == null) {
localLog("Checking the externalScoreEvaluator for candidates...");
networkCandidate = getExternalScoreCandidate(externalScoreEvaluator);
if (networkCandidate != null) {
scanResultCandidate = networkCandidate.getNetworkSelectionStatus().getCandidate();
}
}
if (scanResultCandidate == null) {
localLog("Can not find any suitable candidates");
return null;
}
String currentAssociationId = mCurrentConnectedNetwork == null ? "Disconnected" :
getNetworkString(mCurrentConnectedNetwork);
String targetAssociationId = getNetworkString(networkCandidate);
//In passpoint, saved configuration has garbage SSID. We need update it with the SSID of
//the scan result.
if (networkCandidate.isPasspoint()) {
// This will update the passpoint configuration in WifiConfigManager
networkCandidate.SSID = "\"" + scanResultCandidate.SSID + "\"";
}
//For debug purpose only
if (scanResultCandidate.BSSID.equals(mCurrentBssid)) {
localLog(currentAssociationId + " is already the best choice!");
} else if (mCurrentConnectedNetwork != null
&& (mCurrentConnectedNetwork.networkId == networkCandidate.networkId
|| mCurrentConnectedNetwork.isLinked(networkCandidate))) {
localLog("Roaming from " + currentAssociationId + " to " + targetAssociationId);
} else {
localLog("reconnect from " + currentAssociationId + " to " + targetAssociationId);
}
mCurrentBssid = scanResultCandidate.BSSID;
mCurrentConnectedNetwork = networkCandidate;
mLastQualifiedNetworkSelectionTimeStamp = mClock.elapsedRealtime();
return networkCandidate;
}
Android N selectQualifiedNetwork分析的更多相关文章
- Android APP性能分析方法及工具
近期读到<Speed up your app>一文.这是一篇关于Android APP性能分析.优化的文章.在这篇文章中,作者介绍他的APP分析优化规则.使用的工具和方法.我觉得值得大家借 ...
- Android之mtklog分析
Android之mtklog分析 [海外场测反馈][xxx]动态测试时对比机xxxx拨打测试机xxxxx自动挂断电话 工作中遇到一个掉话的问题,需要分析log,log比较大,我也没法上传,就简答的讲讲 ...
- Android源码分析-全面理解Context
前言 Context在android中的作用不言而喻,当我们访问当前应用的资源,启动一个新的activity的时候都需要提供Context,而这个Context到底是什么呢,这个问题好像很好回答又好像 ...
- cocos2d-x for android:SimpleGame分析
cocos2d-x for android:SimpleGame分析 作为cocos2d-x的标配DEMO,SimpleGame可算是给入门学cocos2d-x的俺们这些新手门学习的对象了,那么来分析 ...
- Android内存机制分析1——了解Android堆和栈
//----------------------------------------------------------------------------------- Android内存机制分析1 ...
- Android 内存管理分析(四)
尊重原创作者,转载请注明出处: http://blog.csdn.net/gemmem/article/details/8920039 最近在网上看了不少Android内存管理方面的博文,但是文章大多 ...
- Qualcomm Android display架构分析
Android display架构分析(一) http://blog.csdn.net/BonderWu/archive/2010/08/12/5805961.aspx http://hi.baidu ...
- Android 消息处理源代码分析(1)
Android 消息处理源代码分析(1) 在Android中,通常被使用的消息队列的代码在文件夹\sources\android-22\android\os下,涉及到下面几个类文件 Handler.j ...
- Android平台APK分析工具包androguard的部署使用和原理分析
原创文章,转载请注明出处,谢谢. Android应用程序分析主要有静态分析和动态分析两种,常见的静态分析工具是Apktool.dex2jar以及jdgui.今天突然主要到Google code上有个叫 ...
随机推荐
- 部署docker镜像仓库及高可用
下载地址: https://github.com/goharbor/harbor/releases 安装harbor服务器: 安装harbor root@harbor-vm1:/usr/loc ...
- C#中的深度学习(三):理解神经网络结构
在这篇文章中,我们将回顾监督机器学习的基础知识,以及训练和验证阶段包括哪些内容. 在这里,我们将为不了解AI的读者介绍机器学习(ML)的基础知识,并且我们将描述在监督机器学习模型中的训练和验证步骤. ...
- linux目录和Windows目录对比
linux目录和Windows目录对比 我们应该知道 Windows 有一个默认的安装目录专门用来安装软件.Linux 的软件安装目录也应该是有讲究的,遵循这一点,对后期的管理和维护也是有帮助的. / ...
- ASP.NET Core 3.1使用 AutoMapper
多层架构中存在多种模型,如视图模型ViewModel,数据传输对你DTO,ORM对象等,这些数据在层与层之间进行传输必须涉及类型之间的转换. AutoMapper是一个对象-对象映射器,作用是通过设置 ...
- HTTP Error 405.0 - Method Not Allowed 无法显示您正在查找的页面,因为使用了无效方法(HTTP 谓词)。
将submit改成button即可 因为触发了form表单
- 【Azure Redis 缓存】Linux虚拟机中使用6380端口(SSL方式)连接Azure Redis (redis-cli & stunnel)
问题描述 在Azure Redis的官方文档中,介绍了在Windows下,如何通过redis-cli.exe连接Redis, 包含如何配置stunnel使得通过 6380,SSL方式连接到Redis ...
- 160个Crackerme破解
001: 第一个破解: 有两种登陆方式:序列号/名字和序列号,观察报错信息 两个报错信息,直接中文搜索字符: 第一种登陆方式报错为:sorry,xx 右键中文字符搜索,ctrl+f输入要搜索的字符,这 ...
- springMVC生成pdf文件
pom.xml文件配置=== <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf --> <dependenc ...
- 三目运算符(C++)
一.简介 固定格式 ?: 三目运算符:可用于赋值语句 三目运算表达式:<表达式1>?<表达式2>:<表达式3> 注:"?"运算符的含义是: 先求 ...
- SpringBoot 集成Elasticsearch进行简单增删改查
一.引入的pom文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns=" ...