Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

深入解析 Android 無線網路配置管理者 WifiConfigStore

編輯:關於 Android 程式設計

在 Android 的無線網路體系中,WifiConfigStore 扮演著「配置管家」的角色,專責處理網路配置資訊的保存與讀取。無論我們是在設定 (Settings) 中新增一個網路、發起連線,還是觸發 auto_connect 自動重連流程,最終都會走到 WifiConfigStore 的相關方法裡。

 public class WifiConfigStore extends IpConfigStore

從類別繼承關係可以看到,WifiConfigStore 派生自 IpConfigStore,並在其基礎上提供了一整套管理「使用者曾經配置過的網路」的 API。以下挑選 framework 中幾個高頻使用的介面來說明。

一、saveNetwork() 與 selectNetwork()

在 WifiStateMachine 的建構子中,WifiConfigStore 物件被建立起來:

 mWifiConfigStore = new WifiConfigStore(context,this, mWifiNative);

這裡傳入了 Context、當前的 WifiStateMachine 參照,以及一個 WifiNative 物件。透過 mWifiNative,我們得以向底層的 wpa_supplicant 下發連線、選擇網路等各類指令。

當我們要連接一個網路時,通常會先把它的配置資訊保存下來,也就是呼叫 saveNetwork():

 /** * Add/update the specified configuration and save config * * @param config WifiConfiguration to be saved * @return network update result */ NetworkUpdateResult saveNetwork(WifiConfiguration config, int uid) { WifiConfiguration conf; // A new network cannot have null SSID if (config == null || (config.networkId == INVALID_NETWORK_ID && config.SSID == null)) { return new NetworkUpdateResult(INVALID_NETWORK_ID); } if (VDBG) localLog("WifiConfigStore: saveNetwork netId", config.networkId); if (VDBG) { loge("WifiConfigStore saveNetwork, size=" + mConfiguredNetworks.size() + " SSID=" + config.SSID + " Uid=" + Integer.toString(config.creatorUid) + "/" + Integer.toString(config.lastUpdateUid)); } if (mDeletedEphemeralSSIDs.remove(config.SSID)) { if (VDBG) { loge("WifiConfigStore: removed from ephemeral blacklist: " + config.SSID); } // NOTE: This will be flushed to disk as part of the addOrUpdateNetworkNative call // below, since we're creating/modifying a config. } boolean newNetwork = (config.networkId == INVALID_NETWORK_ID); NetworkUpdateResult result = addOrUpdateNetworkNative(config, uid); int netId = result.getNetworkId(); if (VDBG) localLog("WifiConfigStore: saveNetwork got it back netId=", netId); /* enable a new network */ if (newNetwork && netId != INVALID_NETWORK_ID) { if (VDBG) localLog("WifiConfigStore: will enable netId=", netId); mWifiNative.enableNetwork(netId, false); conf = mConfiguredNetworks.get(netId); if (conf != null) conf.status = Status.ENABLED; } conf = mConfiguredNetworks.get(netId); if (conf != null) { if (conf.autoJoinStatus != WifiConfiguration.AUTO_JOIN_ENABLED) { if (VDBG) localLog("WifiConfigStore: re-enabling: " + conf.SSID); // reenable autojoin, since new information has been provided conf.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED); enableNetworkWithoutBroadcast(conf.networkId, false); } if (VDBG) { loge("WifiConfigStore: saveNetwork got config back netId=" + Integer.toString(netId) + " uid=" + Integer.toString(config.creatorUid)); } } mWifiNative.saveConfig(); sendConfiguredNetworksChangedBroadcast(conf, result.isNewNetwork() ? WifiManager.CHANGE_REASON_ADDED : WifiManager.CHANGE_REASON_CONFIG_CHANGE); return result; }

saveNetwork() 的核心職責,是依據傳入的 WifiConfiguration 物件去更新並保存各項網路配置。WifiConfiguration 代表一個已配置的網路,主要承載加密方式、SSID、密鑰等資訊。其中關鍵的一步,是呼叫 addOrUpdateNetworkNative() 把配置寫入並持久化到本地。這個函式看似龐雜,實際邏輯並不複雜:

首先,它會依傳入的 config,從 mConfiguredNetworks 中取出同一 netId 的舊物件 savedConfig。mConfiguredNetworks 是一個 HashMap 結構,以 netId 為鍵、對應的 WifiConfiguration 為值,也就是以鍵值對的形式保存了目前所有已配置的網路。後續步驟都在比對 config 與 savedConfig 的差異,把變更同步進 wpa_supplicant 的設定檔並完成更新,最後再將更新後的 WifiConfiguration 放回 mConfiguredNetworks。此外還會呼叫 writeIpAndProxyConfigurationsOnChange(),把新的資訊寫入本機檔案 /misc/wifi/ipconfig.txt。稍後會提到,當我們重新開啟 Wifi 時,系統正是從這個檔案讀回曾經配置過的網路並執行重連。

 /* Compare current and new configuration and write to file on change */ private NetworkUpdateResult writeIpAndProxyConfigurationsOnChange( WifiConfiguration currentConfig, WifiConfiguration newConfig) { boolean ipChanged = false; boolean proxyChanged = false; if (VDBG) { loge("writeIpAndProxyConfigurationsOnChange: " + currentConfig.SSID + " -> " + newConfig.SSID + " path: " + ipConfigFile); } switch (newConfig.getIpAssignment()) { case STATIC: if (currentConfig.getIpAssignment() != newConfig.getIpAssignment()) { ipChanged = true; } else { ipChanged = !Objects.equals( currentConfig.getStaticIpConfiguration(), newConfig.getStaticIpConfiguration()); } break; case DHCP: if (currentConfig.getIpAssignment() != newConfig.getIpAssignment()) { ipChanged = true; } break; case UNASSIGNED: /* Ignore */ break; default: loge("Ignore invalid ip assignment during write"); break; } switch (newConfig.getProxySettings()) { case STATIC: case PAC: ProxyInfo newHttpProxy = newConfig.getHttpProxy(); ProxyInfo currentHttpProxy = currentConfig.getHttpProxy(); if (newHttpProxy != null) { proxyChanged = !newHttpProxy.equals(currentHttpProxy); } else { proxyChanged = (currentHttpProxy != null); } break; case NONE: if (currentConfig.getProxySettings() != newConfig.getProxySettings()) { proxyChanged = true; } break; case UNASSIGNED: /* Ignore */ break; default: loge("Ignore invalid proxy configuration during write"); break; } if (ipChanged) { currentConfig.setIpAssignment(newConfig.getIpAssignment()); currentConfig.setStaticIpConfiguration(newConfig.getStaticIpConfiguration()); log("IP config changed SSID = " + currentConfig.SSID); if (currentConfig.getStaticIpConfiguration() != null) { log(" static configuration: " + currentConfig.getStaticIpConfiguration().toString()); } } if (proxyChanged) { currentConfig.setProxySettings(newConfig.getProxySettings()); currentConfig.setHttpProxy(newConfig.getHttpProxy()); log("proxy changed SSID = " + currentConfig.SSID); if (currentConfig.getHttpProxy() != null) { log(" proxyProperties: " + currentConfig.getHttpProxy().toString()); } } if (ipChanged || proxyChanged) { writeIpAndProxyConfigurations(); sendConfiguredNetworksChangedBroadcast(currentConfig, WifiManager.CHANGE_REASON_CONFIG_CHANGE); } return new NetworkUpdateResult(ipChanged, proxyChanged); }

這段程式碼牽涉到 IpAssignment 與 ProxySettings 兩個列舉型別:

 public enum IpAssignment { /* Use statically configured IP settings. Configuration can be accessed * with staticIpConfiguration */ STATIC, /* Use dynamically configured IP settigns */ DHCP, /* no IP details are assigned, this is used to indicate * that any existing IP settings should be retained */ UNASSIGNED } public enum ProxySettings { /* No proxy is to be used. Any existing proxy settings * should be cleared. */ NONE, /* Use statically configured proxy. Configuration can be accessed * with httpProxy. */ STATIC, /* no proxy details are assigned, this is used to indicate * that any existing proxy settings should be retained */ UNASSIGNED, /* Use a Pac based proxy. */ PAC }

IpAssignment 表示目前取得 IP 的方式,我們可以依需求在裡頭擴充自訂型別,例如 PPPoE;相對地,ProxySettings 則描述目前網路採用的代理模式。IpAssignment 的值一般由設定介面依使用者選擇的 IP 模式賦值,再傳遞給 framework,讓底層知道該用哪種方式去拿 IP。舉例來說,若使用者選擇靜態 IP (Static IP),在 WifiStateMachine::ObtainingIpState 中就會出現類似以下的判斷:

 if (!mWifiConfigStore.isUsingStaticIp(mLastNetworkId)) { if (isRoaming()) { renewDhcp(); } else { // Remove any IP address on the interface in case we're switching from static // IP configuration to DHCP. This is safe because if we get here when not // roaming, we don't have a usable address. clearIPv4Address(mInterfaceName); startDhcp(); } obtainingIpWatchdogCount++; logd("Start Dhcp Watchdog " + obtainingIpWatchdogCount); // Get Link layer stats so as we get fresh tx packet counters getWifiLinkLayerStats(true); sendMessageDelayed(obtainMessage(CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER, obtainingIpWatchdogCount, 0), OBTAINING_IP_ADDRESS_GUARD_TIMER_MSEC); } else { // stop any running dhcp before assigning static IP stopDhcp(); StaticIpConfiguration config = mWifiConfigStore.getStaticIpConfiguration( mLastNetworkId); if (config.ipAddress == null) { logd("Static IP lacks address"); sendMessage(CMD_STATIC_IP_FAILURE); } else { InterfaceConfiguration ifcg = new InterfaceConfiguration(); ifcg.setLinkAddress(config.ipAddress); ifcg.setInterfaceUp(); try { mNwService.setInterfaceConfig(mInterfaceName, ifcg); if (DBG) log("Static IP configuration succeeded"); DhcpResults dhcpResults = new DhcpResults(config); sendMessage(CMD_STATIC_IP_SUCCESS, dhcpResults); } catch (RemoteException re) { loge("Static IP configuration failed: " + re); sendMessage(CMD_STATIC_IP_FAILURE); } catch (IllegalStateException e) { loge("Static IP configuration failed: " + e); sendMessage(CMD_STATIC_IP_FAILURE); } } }

其中透過 WifiConfigStore.isUsingStaticIp(mLastNetworkId) 就能得知目前使用者到底是用哪種方式取得 IP,方法定義如下:

 /** * Return if the specified network is using static IP * @param netId id * @return {@code true} if using static ip for netId */ boolean isUsingStaticIp(int netId) { WifiConfiguration config = mConfiguredNetworks.get(netId); if (config != null && config.getIpAssignment() == IpAssignment.STATIC) { return true; } return false; }

它會依傳入的 netId,從 mConfiguredNetworks 取出對應的 WifiConfiguration,再讀取其中的 IpAssignment 值,藉此區分不同網路並讓流程走向不同分支。若我們擴充了新的方式,也可以仿照這個原生範例,寫出自己的判斷邏輯。

回到 writeIpAndProxyConfigurationsOnChange(),它會依 IpAssignment 與 ProxySettings 是否改變來更新 currentConfig,再由 writeIpAndProxyConfigurations() 把結果落盤到本機檔案:

 private void writeIpAndProxyConfigurations() { final SparseArray networks = new SparseArray(); for(WifiConfiguration config : mConfiguredNetworks.values()) { if (!config.ephemeral && config.autoJoinStatus != WifiConfiguration.AUTO_JOIN_DELETED) { networks.put(configKey(config), config.getIpConfiguration()); } } super.writeIpAndProxyConfigurations(ipConfigFile, networks);//in IpConfigStore }
 public void IpConfigStore::writeIpAndProxyConfigurations(String filePath, final SparseArray networks) { mWriter.write(filePath, new DelayedDiskWrite.Writer() { public void onWriteCalled(DataOutputStream out) throws IOException{ out.writeInt(IPCONFIG_FILE_VERSION); for(int i = 0; i < networks.size(); i++) { writeConfig(out, networks.keyAt(i), networks.valueAt(i)); } } }); }
 private boolean writeConfig(DataOutputStream out, int configKey, IpConfiguration config) throws IOException { boolean written = false; try { switch (config.ipAssignment) { case STATIC: out.writeUTF(IP_ASSIGNMENT_KEY); out.writeUTF(config.ipAssignment.toString()); StaticIpConfiguration staticIpConfiguration = config.staticIpConfiguration; if (staticIpConfiguration != null) { if (staticIpConfiguration.ipAddress != null) { LinkAddress ipAddress = staticIpConfiguration.ipAddress; out.writeUTF(LINK_ADDRESS_KEY); out.writeUTF(ipAddress.getAddress().getHostAddress()); out.writeInt(ipAddress.getPrefixLength()); } if (staticIpConfiguration.gateway != null) { out.writeUTF(GATEWAY_KEY); out.writeInt(0); // Default route. out.writeInt(1); // Have a gateway. out.writeUTF(staticIpConfiguration.gateway.getHostAddress()); } for (InetAddress inetAddr : staticIpConfiguration.dnsServers) { out.writeUTF(DNS_KEY); out.writeUTF(inetAddr.getHostAddress()); } } written = true; break; case DHCP: out.writeUTF(IP_ASSIGNMENT_KEY); out.writeUTF(config.ipAssignment.toString()); written = true; break; case UNASSIGNED: /* Ignore */ break; default: loge("Ignore invalid ip assignment while writing"); break; } switch (config.proxySettings) { case STATIC: ProxyInfo proxyProperties = config.httpProxy; String exclusionList = proxyProperties.getExclusionListAsString(); out.writeUTF(PROXY_SETTINGS_KEY); out.writeUTF(config.proxySettings.toString()); out.writeUTF(PROXY_HOST_KEY); out.writeUTF(proxyProperties.getHost()); out.writeUTF(PROXY_PORT_KEY); out.writeInt(proxyProperties.getPort()); if (exclusionList != null) { out.writeUTF(EXCLUSION_LIST_KEY); out.writeUTF(exclusionList); } written = true; break; case PAC: ProxyInfo proxyPacProperties = config.httpProxy; out.writeUTF(PROXY_SETTINGS_KEY); out.writeUTF(config.proxySettings.toString()); out.writeUTF(PROXY_PAC_FILE); out.writeUTF(proxyPacProperties.getPacFileUrl().toString()); written = true; break; case NONE: out.writeUTF(PROXY_SETTINGS_KEY); out.writeUTF(config.proxySettings.toString()); written = true; break; case UNASSIGNED: /* Ignore */ break; default: loge("Ignore invalid proxy settings while writing"); break; } if (written) { out.writeUTF(ID_KEY); out.writeInt(configKey); } } catch (NullPointerException e) { loge("Failure in writing " + config + e); } out.writeUTF(EOS); return written; }

真正落盤的動作,是由父類別 IpConfigStore::writeConfig() 完成的。在 WifiConfigStore::writeIpAndProxyConfigurations() 中,我們會把 mConfiguredNetworks 裡所有已保存的網路配置取出,重新以「唯一 int 值搭配 IpConfiguration」的形式裝進 SparseArray<IpConfiguration> networks 這個集合物件裡;而 ipConfigFile 的值,正是路徑 "/misc/wifi/ipconfig.txt"。

在 IpConfigStore::writeIpAndProxyConfigurations 與 IpConfigStore::writeConfig() 中,會遍歷 networks 集合,並依下列分類把資訊寫進 ipconfig.txt:

 switch (config.ipAssignment) switch (config.proxySettings)

寫入時有固定規則:每個標籤後面緊跟著該標籤對應的值,如此安排正是為了方便後續的讀取。系統預先定義的標籤值如下:

 /* IP and proxy configuration keys */ protected static final String ID_KEY = "id"; protected static final String IP_ASSIGNMENT_KEY = "ipAssignment"; protected static final String LINK_ADDRESS_KEY = "linkAddress"; protected static final String GATEWAY_KEY = "gateway"; protected static final String DNS_KEY = "dns"; protected static final String PROXY_SETTINGS_KEY = "proxySettings"; protected static final String PROXY_HOST_KEY = "proxyHost"; protected static final String PROXY_PORT_KEY = "proxyPort"; protected static final String PROXY_PAC_FILE = "proxyPac"; protected static final String EXCLUSION_LIST_KEY = "exclusionList"; protected static final String EOS = "eos"; protected static final int IPCONFIG_FILE_VERSION = 2;

從這裡我們不難看出可以客製化的切入點。目前部分 Android 手機的 Wifi 功能支援無線 PPPoE,而使用 PPPoE 必須搭配帳號資訊。此時我們大可以在 WifiConfiguration 或 IpConfiguration 中新增帳號屬性欄位,在保存網路時一併把帳號密碼寫入;並在從 ipconfig.txt 讀回時,將這些資訊重新封裝進 WifiConfiguration 或 IpConfiguration 物件,供無線 PPPoE 取得 IP 時使用。

最後還會牽涉到 writeKnownNetworkHistory() 的呼叫,它會把每個 WifiConfiguration 的部分欄位(如優先級、SSID 等)寫入 /misc/wifi/networkHistory.txt,寫入方式與前面相同。至此,saveNetwork() 的處理流程便告一段落。

至於 selectNetwork(),它的作用是挑選一個特定網路並準備連線,過程中會牽涉到網路優先級的更新與 enable 網路的操作。

 /** * Selects the specified network for connection. This involves * updating the priority of all the networks and enabling the given * network while disabling others. * * Selecting a network will leave the other networks disabled and * a call to enableAllNetworks() needs to be issued upon a connection * or a failure event from supplicant * * @param config network to select for connection * @param updatePriorities makes config highest priority network * @return false if the network id is invalid */ boolean selectNetwork(WifiConfiguration config, boolean updatePriorities, int uid) { if (VDBG) localLog("selectNetwork", config.networkId); if (config.networkId == INVALID_NETWORK_ID) return false; // Reset the priority of each network at start or if it goes too high. if (mLastPriority == -1 || mLastPriority > 1000000) { for(WifiConfiguration config2 : mConfiguredNetworks.values()) { if (updatePriorities) { if (config2.networkId != INVALID_NETWORK_ID) { config2.priority = 0; setNetworkPriorityNative(config2.networkId, config.priority); } } } mLastPriority = 0; } // Set to the highest priority and save the configuration. if (updatePriorities) { config.priority = ++mLastPriority; setNetworkPriorityNative(config.networkId, config.priority); buildPnoList(); } if (config.isPasspoint()) { /* need to slap on the SSID of selected bssid to work */ if (getScanDetailCache(config).size() != 0) { ScanDetail result = getScanDetailCache(config).getFirst(); if (result == null) { loge("Could not find scan result for " + config.BSSID); } else { log("Setting SSID for " + config.networkId + " to" + result.getSSID()); setSSIDNative(config.networkId, result.getSSID()); config.SSID = result.getSSID(); } } else { loge("Could not find bssid for " + config); } } if (updatePriorities) mWifiNative.saveConfig(); else mWifiNative.selectNetwork(config.networkId); updateLastConnectUid(config, uid); writeKnownNetworkHistory(false); /* Enable the given network while disabling all other networks */ enableNetworkWithoutBroadcast(config.networkId, true); /* Avoid saving the config & sending a broadcast to prevent settings * from displaying a disabled list of networks */ return true; }

mLastPriority 是一個 int 型別的整數,代表目前網路中優先級的最大值。愈是最近連線過的網路,其 priority 值就愈大。updatePriorities 則用來標示是否需要更新優先級。當目前最大優先級為 -1 或超過 1000000 時,都會重設 mLastPriority;若 updatePriorities 為 true,也會把變更同步寫入 wpa_supplicant.conf。

 // Set to the highest priority and save the configuration. if (updatePriorities) { config.priority = ++mLastPriority; setNetworkPriorityNative(config.networkId, config.priority); buildPnoList(); }

由此可見,每個正在連線的網路都會被賦予最高優先級。而最後的 enableNetworkWithoutBroadcast(),會在 mConfiguredNetworks 中把選中網路的 status 設為 Status.ENABLED,其餘則設為 Status.DISABLED:

 /* Mark all networks except specified netId as disabled */ private void markAllNetworksDisabledExcept(int netId) { for(WifiConfiguration config : mConfiguredNetworks.values()) { if(config != null && config.networkId != netId) { if (config.status != Status.DISABLED) { config.status = Status.DISABLED; config.disableReason = WifiConfiguration.DISABLED_UNKNOWN_REASON; } } }

}

二、重新開啟 Wifi 時對 ipconfig.txt 的讀取

當我們重新開啟 Wifi,系統通常都會執行網路自動重連。此時在 WifiStateMachine 中:

 mWifiConfigStore.loadAndEnableAllNetworks();
 /** * Fetch the list of configured networks * and enable all stored networks in supplicant. */ void loadAndEnableAllNetworks() { if (DBG) log("Loading config and enabling all networks "); loadConfiguredNetworks(); enableAllNetworks(); }

接著看 loadConfiguredNetworks():

 void loadConfiguredNetworks() { mLastPriority = 0; mConfiguredNetworks.clear(); int last_id = -1; boolean done = false; while (!done) { String listStr = mWifiNative.listNetworks(last_id); if (listStr == null) return; String[] lines = listStr.split("\n"); if (showNetworks) { localLog("WifiConfigStore: loadConfiguredNetworks: "); for (String net : lines) { localLog(net); } } // Skip the first line, which is a header for (int i = 1; i < lines.length; i++) { String[] result = lines[i].split("\t"); // network-id | ssid | bssid | flags WifiConfiguration config = new WifiConfiguration(); try { config.networkId = Integer.parseInt(result[0]); last_id = config.networkId; } catch(NumberFormatException e) { loge("Failed to read network-id '" + result[0] + "'"); continue; } if (result.length > 3) { if (result[3].indexOf("[CURRENT]") != -1) config.status = WifiConfiguration.Status.CURRENT; else if (result[3].indexOf("[DISABLED]") != -1) config.status = WifiConfiguration.Status.DISABLED; else config.status = WifiConfiguration.Status.ENABLED; } else { config.status = WifiConfiguration.Status.ENABLED; } readNetworkVariables(config); Checksum csum = new CRC32(); if (config.SSID != null) { csum.update(config.SSID.getBytes(), 0, config.SSID.getBytes().length); long d = csum.getValue(); if (mDeletedSSIDs.contains(d)) { loge(" got CRC for SSID " + config.SSID + " -> " + d + ", was deleted"); } } if (config.priority > mLastPriority) { mLastPriority = config.priority; } config.setIpAssignment(IpAssignment.DHCP);//默認設置DHCP config.setProxySettings(ProxySettings.NONE);//默認設置NONE if (mConfiguredNetworks.getByConfigKey(config.configKey()) != null) { // That SSID is already known, just ignore this duplicate entry if (showNetworks) localLog("discarded duplicate network ", config.networkId); } else if(WifiServiceImpl.isValid(config)){ mConfiguredNetworks.put(config.networkId, config); if (showNetworks) localLog("loaded configured network", config.networkId); } else { if (showNetworks) log("Ignoring loaded configured for network " + config.networkId + " because config are not valid"); } } done = (lines.length == 1); } readPasspointConfig(); readIpAndProxyConfigurations();//讀取ipconfig.txt readNetworkHistory();//讀取networkHistory.txt readAutoJoinConfig(); buildPnoList(); sendConfiguredNetworksChangedBroadcast(); if (showNetworks) localLog("loadConfiguredNetworks loaded " + mConfiguredNetworks.size() + " networks"); if (mConfiguredNetworks.isEmpty()) { // no networks? Lets log if the file contents logKernelTime(); logContents(SUPPLICANT_CONFIG_FILE); logContents(SUPPLICANT_CONFIG_FILE_BACKUP); logContents(networkHistoryConfigFile); } }

函式一開始便會清空 mConfiguredNetworks 集合。

整體流程可以這樣理解:先從 wpa_supplicant 讀取已保存的網路列表並填入 mConfiguredNetworks;接著呼叫 readIpAndProxyConfigurations(),從 ipconfig.txt 讀回 IpConfiguration 並更新到集合中對應的 WifiConfiguration;最後再呼叫 mConfiguredNetworks(),從 /misc/wifi/networkHistory.txt 讀取資訊,同樣更新到各個 WifiConfiguration 物件裡。

讀取的方式與前面介紹的寫入方式大同小異。經過這兩次讀取,我們手上的 WifiConfiguration 資訊就相對完整了。

若碰上前面提到的無線 PPPoE 情境,readIpAndProxyConfigurations() 便會把我們事先寫入的帳號密碼一併讀出並存進 mConfiguredNetworks。當 auto_connect 流程執行時,會取得最近一次連線網路的 netId,從 mConfiguredNetworks 取出的對應 WifiConfiguration 裡就保存著 PPPoE 的帳號密碼,如此一來,PPPoE 取得 IP 時便有可用的帳戶資訊了。

補充:

WifiConfigStore 中定義了一個頗具意義的預設常數:

 /** * The maximum number of times we will retry a connection to an access point * for which we have failed in acquiring an IP address from DHCP. A value of * N means that we will make N+1 connection attempts in all. * * See {@link Settings.Secure#WIFI_MAX_DHCP_RETRY_COUNT}. This is the default * value if a Settings value is not present. */ private static final int DEFAULT_MAX_DHCP_RETRIES = 9;

從原生註解可以得知,這個變數控制的是當某個網路取得 IP 失敗後,後續還要重試幾次;若值定為 9,實際重連次數會是 9+1,也就是 10 次。

如果我們想客製這個值,重連次數便會以自訂設定為準:

 int WifiConfigStore::getMaxDhcpRetries() { return Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.WIFI_MAX_DHCP_RETRY_COUNT, DEFAULT_MAX_DHCP_RETRIES); }

我們可以透過設定 Settings.Global.WIFI_MAX_DHCP_RETRY_COUNT 這個欄位來客製這部分:

 /** * The maximum number of times we will retry a connection to an access * point for which we have failed in acquiring an IP address from DHCP. * A value of N means that we will make N+1 connection attempts in all. */ public static final String WIFI_MAX_DHCP_RETRY_COUNT = "wifi_max_dhcp_retry_count";

getMaxDhcpRetries() 在 WifiConfigStore 中僅被 handleSSIDStateChange() 使用:

 void handleSSIDStateChange(int netId, boolean enabled, String message, String BSSID) { WifiConfiguration config = mConfiguredNetworks.get(netId); if (config != null) { if (enabled) { loge("Ignoring SSID re-enabled from supplicant: " + config.configKey() + " had autoJoinStatus=" + Integer.toString(config.autoJoinStatus) + " self added " + config.selfAdded + " ephemeral " + config.ephemeral); //We should not re-enable the BSSID based on Supplicant reanable. // Framework will re-enable it after its own blacklist timer expires } else { loge("SSID temp disabled for " + config.configKey() + " had autoJoinStatus=" + Integer.toString(config.autoJoinStatus) + " self added " + config.selfAdded + " ephemeral " + config.ephemeral); if (message != null) { loge(" message=" + message); } if (config.selfAdded && config.lastConnected == 0) { // This is a network we self added, and we never succeeded, // the user did not create this network and never entered its credentials, // so we want to be very aggressive in disabling it completely. removeConfigAndSendBroadcastIfNeeded(config.networkId); } else { if (message != null) { if (message.contains("no identity")) { config.setAutoJoinStatus( WifiConfiguration.AUTO_JOIN_DISABLED_NO_CREDENTIALS); if (DBG) { loge("no identity blacklisted " + config.configKey() + " to " + Integer.toString(config.autoJoinStatus)); } } else if (message.contains("WRONG_KEY") || message.contains("AUTH_FAILED")) { // This configuration has received an auth failure, so disable it // temporarily because we don't want auto-join to try it out. // this network may be re-enabled by the "usual" // enableAllNetwork function config.numAuthFailures++; if (config.numAuthFailures > maxAuthErrorsToBlacklist) { config.setAutoJoinStatus (WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE); disableNetwork(netId, WifiConfiguration.DISABLED_AUTH_FAILURE); loge("Authentication failure, blacklist " + config.configKey() + " " + Integer.toString(config.networkId) + " num failures " + config.numAuthFailures); } } else if (message.contains("DHCP FAILURE")) { config.numIpConfigFailures++; config.lastConnectionFailure = System.currentTimeMillis(); int maxRetries = getMaxDhcpRetries(); // maxRetries == 0 means keep trying forever if (maxRetries > 0 && config.numIpConfigFailures > maxRetries) { /** * If we've exceeded the maximum number of retries for DHCP * to a given network, disable the network */ config.setAutoJoinStatus (WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE); disableNetwork(netId, WifiConfiguration.DISABLED_DHCP_FAILURE); loge("DHCP failure, blacklist " + config.configKey() + " " + Integer.toString(config.networkId) + " num failures " + config.numIpConfigFailures); } // Also blacklist the BSSId if we find it ScanResult result = null; String bssidDbg = ""; if (getScanDetailCache(config) != null && BSSID != null) { result = getScanDetailCache(config).get(BSSID); } if (result != null) { result.numIpConfigFailures ++; bssidDbg = BSSID + " ipfail=" + result.numIpConfigFailures; if (result.numIpConfigFailures > 3) { // Tell supplicant to stop trying this BSSID mWifiNative.addToBlacklist(BSSID); result.setAutoJoinStatus(ScanResult.AUTO_JOIN_DISABLED); } } if (DBG) { loge("blacklisted " + config.configKey() + " to " + config.autoJoinStatus + " due to IP config failures, count=" + config.numIpConfigFailures + " disableReason=" + config.disableReason + " " + bssidDbg); } } else if (message.contains("CONN_FAILED")) { config.numConnectionFailures++; if (config.numConnectionFailures > maxConnectionErrorsToBlacklist) { config.setAutoJoinStatus (WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE); disableNetwork(netId, WifiConfiguration.DISABLED_ASSOCIATION_REJECT); loge("Connection failure, blacklist " + config.configKey() + " " + config.networkId + " num failures " + config.numConnectionFailures); } } message.replace("\n", ""); message.replace("\r", ""); config.lastFailure = message; } } } } }

在 WifiStateMachine 中,若一個網路 DHCP 取得 IP 失敗、靜態 IP 配置失敗,或網路配置資訊遺失,都會間接呼叫到 handleSSIDStateChange(),在設定次數內嘗試重連。舉個例子:

 private void WifiStateMachine::handleIpConfigurationLost() { mWifiInfo.setInetAddress(null); mWifiInfo.setMeteredHint(false); mWifiConfigStore.handleSSIDStateChange(mLastNetworkId, false, "DHCP FAILURE", mWifiInfo.getBSSID());//函數調用 /* DHCP times out after about 30 seconds, we do a * disconnect thru supplicant, we will let autojoin retry connecting to the network */ mWifiNative.disconnect(); }

這裡呼叫時,netId 為目前使用網路的 netId,用來在 WifiConfigStore 取得對應的 WifiConfiguration;enabled 為 false;message 為 DHCP FAILURE。對照 handleSSIDStateChange() 的實作可以分析出:

依傳入的 message,實作會根據其內容判斷目前網路發生的是哪一種錯誤,並記錄對應的錯誤次數,例如是 WRONG_KEY、AUTH_FAILED,還是 DHCP FAILURE;接著更新 WifiConfiguration 中對應各錯誤的欄位值。以 WRONG_KEY 與 AUTH_FAILED 為例,對應欄位是 numAuthFailures,記錄授權失敗次數;一旦授權失敗次數超過門檻,便會把該網路的 autoJoinStatus 設為 AUTO_JOIN_DISABLED_ON_AUTH_FAILURE 並停用網路。如此一來,後續 auto_connect 流程判斷 autoJoinStatus 不合法時,就不會再嘗試重連。

 if (config.numAuthFailures > maxAuthErrorsToBlacklist) { config.setAutoJoinStatus (WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE);//設置autostatus disableNetwork(netId, WifiConfiguration.DISABLED_AUTH_FAILURE);//disable網絡 loge("Authentication failure, blacklist " + config.configKey() + " " + Integer.toString(config.networkId) + " num failures " + config.numAuthFailures); }

而在我們的例子中傳入的 message 是 DHCP FAILURE:

 else if (message.contains("DHCP FAILURE")) { config.numIpConfigFailures++; config.lastConnectionFailure = System.currentTimeMillis(); int maxRetries = getMaxDhcpRetries(); // maxRetries == 0 means keep trying forever if (maxRetries > 0 && config.numIpConfigFailures > maxRetries) { /** * If we've exceeded the maximum number of retries for DHCP * to a given network, disable the network */ config.setAutoJoinStatus (WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE);//設置autostatus disableNetwork(netId, WifiConfiguration.DISABLED_DHCP_FAILURE);//disable網絡 loge("DHCP failure, blacklist " + config.configKey() + " " + Integer.toString(config.networkId) + " num failures " + config.numIpConfigFailures); } // Also blacklist the BSSId if we find it ScanResult result = null; String bssidDbg = ""; if (getScanDetailCache(config) != null && BSSID != null) { result = getScanDetailCache(config).get(BSSID); } if (result != null) { result.numIpConfigFailures ++; bssidDbg = BSSID + " ipfail=" + result.numIpConfigFailures; if (result.numIpConfigFailures > 3) { // Tell supplicant to stop trying this BSSID mWifiNative.addToBlacklist(BSSID);//也有可能將當前網絡加入到blacklist中 result.setAutoJoinStatus(ScanResult.AUTO_JOIN_DISABLED);//設置autostatus } } if (DBG) { loge("blacklisted " + config.configKey() + " to " + config.autoJoinStatus + " due to IP config failures, count=" + config.numIpConfigFailures + " disableReason=" + config.disableReason + " " + bssidDbg); } }

首先 numIpConfigFailures 自增 1,這個欄位代表目前網路 DHCP 失敗的次數。若目前網路的 DHCP 失敗次數 numIpConfigFailures 大於設定的 DHCP 最大重連次數,就會把 config 的 autoJoinStatus 設為 WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE,並停用目前網路。此時,除非手動觸發連線,否則都不會再自動重連了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved