AccessPoint.java revision 6d0f85a24fe3348c3b01950ce688797870641176
1/* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.settingslib.wifi; 18 19import android.app.AppGlobals; 20import android.content.Context; 21import android.content.pm.ApplicationInfo; 22import android.content.pm.IPackageManager; 23import android.content.pm.PackageManager; 24import android.net.ConnectivityManager; 25import android.net.Network; 26import android.net.NetworkCapabilities; 27import android.net.NetworkInfo; 28import android.net.NetworkInfo.DetailedState; 29import android.net.NetworkInfo.State; 30import android.net.wifi.IWifiManager; 31import android.net.wifi.ScanResult; 32import android.net.wifi.WifiConfiguration; 33import android.net.wifi.WifiConfiguration.KeyMgmt; 34import android.net.wifi.WifiInfo; 35import android.net.wifi.WifiManager; 36import android.os.Bundle; 37import android.os.RemoteException; 38import android.os.ServiceManager; 39import android.os.SystemClock; 40import android.os.UserHandle; 41import android.support.annotation.NonNull; 42import android.text.Spannable; 43import android.text.SpannableString; 44import android.text.TextUtils; 45import android.text.style.TtsSpan; 46import android.util.Log; 47 48import com.android.settingslib.R; 49 50import java.util.ArrayList; 51import java.util.Iterator; 52import java.util.Map; 53import java.util.concurrent.ConcurrentHashMap; 54 55 56public class AccessPoint implements Comparable<AccessPoint> { 57 static final String TAG = "SettingsLib.AccessPoint"; 58 59 /** 60 * Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels 61 */ 62 public static final int LOWER_FREQ_24GHZ = 2400; 63 64 /** 65 * Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels 66 */ 67 public static final int HIGHER_FREQ_24GHZ = 2500; 68 69 /** 70 * Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels 71 */ 72 public static final int LOWER_FREQ_5GHZ = 4900; 73 74 /** 75 * Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels 76 */ 77 public static final int HIGHER_FREQ_5GHZ = 5900; 78 79 80 /** 81 * Experimental: we should be able to show the user the list of BSSIDs and bands 82 * for that SSID. 83 * For now this data is used only with Verbose Logging so as to show the band and number 84 * of BSSIDs on which that network is seen. 85 */ 86 private final ConcurrentHashMap<String, ScanResult> mScanResultCache = 87 new ConcurrentHashMap<String, ScanResult>(32); 88 private static final long MAX_SCAN_RESULT_AGE_MS = 15000; 89 90 private static final String KEY_NETWORKINFO = "key_networkinfo"; 91 private static final String KEY_WIFIINFO = "key_wifiinfo"; 92 private static final String KEY_SCANRESULT = "key_scanresult"; 93 private static final String KEY_SSID = "key_ssid"; 94 private static final String KEY_SECURITY = "key_security"; 95 private static final String KEY_PSKTYPE = "key_psktype"; 96 private static final String KEY_SCANRESULTCACHE = "key_scanresultcache"; 97 private static final String KEY_CONFIG = "key_config"; 98 99 /** 100 * These values are matched in string arrays -- changes must be kept in sync 101 */ 102 public static final int SECURITY_NONE = 0; 103 public static final int SECURITY_WEP = 1; 104 public static final int SECURITY_PSK = 2; 105 public static final int SECURITY_EAP = 3; 106 107 private static final int PSK_UNKNOWN = 0; 108 private static final int PSK_WPA = 1; 109 private static final int PSK_WPA2 = 2; 110 private static final int PSK_WPA_WPA2 = 3; 111 112 public static final int SIGNAL_LEVELS = 4; 113 114 private final Context mContext; 115 116 private String ssid; 117 private String bssid; 118 private int security; 119 private int networkId = WifiConfiguration.INVALID_NETWORK_ID; 120 121 private int pskType = PSK_UNKNOWN; 122 123 private WifiConfiguration mConfig; 124 125 private int mRssi = Integer.MAX_VALUE; 126 private long mSeen = 0; 127 128 private WifiInfo mInfo; 129 private NetworkInfo mNetworkInfo; 130 private AccessPointListener mAccessPointListener; 131 132 private Object mTag; 133 134 public AccessPoint(Context context, Bundle savedState) { 135 mContext = context; 136 mConfig = savedState.getParcelable(KEY_CONFIG); 137 if (mConfig != null) { 138 loadConfig(mConfig); 139 } 140 if (savedState.containsKey(KEY_SSID)) { 141 ssid = savedState.getString(KEY_SSID); 142 } 143 if (savedState.containsKey(KEY_SECURITY)) { 144 security = savedState.getInt(KEY_SECURITY); 145 } 146 if (savedState.containsKey(KEY_PSKTYPE)) { 147 pskType = savedState.getInt(KEY_PSKTYPE); 148 } 149 mInfo = (WifiInfo) savedState.getParcelable(KEY_WIFIINFO); 150 if (savedState.containsKey(KEY_NETWORKINFO)) { 151 mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO); 152 } 153 if (savedState.containsKey(KEY_SCANRESULTCACHE)) { 154 ArrayList<ScanResult> scanResultArrayList = 155 savedState.getParcelableArrayList(KEY_SCANRESULTCACHE); 156 mScanResultCache.clear(); 157 for (ScanResult result : scanResultArrayList) { 158 mScanResultCache.put(result.BSSID, result); 159 } 160 } 161 update(mConfig, mInfo, mNetworkInfo); 162 mRssi = getRssi(); 163 mSeen = getSeen(); 164 } 165 166 AccessPoint(Context context, ScanResult result) { 167 mContext = context; 168 initWithScanResult(result); 169 } 170 171 AccessPoint(Context context, WifiConfiguration config) { 172 mContext = context; 173 loadConfig(config); 174 } 175 176 @Override 177 public int compareTo(@NonNull AccessPoint other) { 178 // Active one goes first. 179 if (isActive() && !other.isActive()) return -1; 180 if (!isActive() && other.isActive()) return 1; 181 182 // Reachable one goes before unreachable one. 183 if (mRssi != Integer.MAX_VALUE && other.mRssi == Integer.MAX_VALUE) return -1; 184 if (mRssi == Integer.MAX_VALUE && other.mRssi != Integer.MAX_VALUE) return 1; 185 186 // Configured one goes before unconfigured one. 187 if (networkId != WifiConfiguration.INVALID_NETWORK_ID 188 && other.networkId == WifiConfiguration.INVALID_NETWORK_ID) return -1; 189 if (networkId == WifiConfiguration.INVALID_NETWORK_ID 190 && other.networkId != WifiConfiguration.INVALID_NETWORK_ID) return 1; 191 192 // Sort by signal strength, bucketed by level 193 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS) 194 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS); 195 if (difference != 0) { 196 return difference; 197 } 198 // Sort by ssid. 199 return ssid.compareToIgnoreCase(other.ssid); 200 } 201 202 @Override 203 public boolean equals(Object other) { 204 if (!(other instanceof AccessPoint)) return false; 205 return (this.compareTo((AccessPoint) other) == 0); 206 } 207 208 @Override 209 public int hashCode() { 210 int result = 0; 211 if (mInfo != null) result += 13 * mInfo.hashCode(); 212 result += 19 * mRssi; 213 result += 23 * networkId; 214 result += 29 * ssid.hashCode(); 215 return result; 216 } 217 218 @Override 219 public String toString() { 220 StringBuilder builder = new StringBuilder().append("AccessPoint(") 221 .append(ssid); 222 if (isSaved()) { 223 builder.append(',').append("saved"); 224 } 225 if (isActive()) { 226 builder.append(',').append("active"); 227 } 228 if (isEphemeral()) { 229 builder.append(',').append("ephemeral"); 230 } 231 if (isConnectable()) { 232 builder.append(',').append("connectable"); 233 } 234 if (security != SECURITY_NONE) { 235 builder.append(',').append(securityToString(security, pskType)); 236 } 237 return builder.append(')').toString(); 238 } 239 240 private void evictOldScanResults() { 241 long nowMs = SystemClock.elapsedRealtime(); 242 for (Iterator<ScanResult> iter = mScanResultCache.values().iterator(); iter.hasNext(); ) { 243 ScanResult result = iter.next(); 244 // result timestamp is in microseconds 245 if (nowMs - result.timestamp / 1000 > MAX_SCAN_RESULT_AGE_MS) { 246 iter.remove(); 247 } 248 } 249 } 250 251 public boolean matches(ScanResult result) { 252 return ssid.equals(result.SSID) && security == getSecurity(result); 253 } 254 255 public boolean matches(WifiConfiguration config) { 256 if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) { 257 return config.FQDN.equals(mConfig.providerFriendlyName); 258 } else { 259 return ssid.equals(removeDoubleQuotes(config.SSID)) 260 && security == getSecurity(config) 261 && (mConfig == null || mConfig.shared == config.shared); 262 } 263 } 264 265 public WifiConfiguration getConfig() { 266 return mConfig; 267 } 268 269 public void clearConfig() { 270 mConfig = null; 271 networkId = WifiConfiguration.INVALID_NETWORK_ID; 272 } 273 274 public WifiInfo getInfo() { 275 return mInfo; 276 } 277 278 public int getLevel() { 279 if (mRssi == Integer.MAX_VALUE) { 280 return -1; 281 } 282 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS); 283 } 284 285 public int getRssi() { 286 evictOldScanResults(); 287 int rssi = Integer.MIN_VALUE; 288 for (ScanResult result : mScanResultCache.values()) { 289 if (result.level > rssi) { 290 rssi = result.level; 291 } 292 } 293 294 return rssi; 295 } 296 297 public long getSeen() { 298 evictOldScanResults(); 299 long seen = 0; 300 for (ScanResult result : mScanResultCache.values()) { 301 if (result.timestamp > seen) { 302 seen = result.timestamp; 303 } 304 } 305 306 return seen; 307 } 308 309 public NetworkInfo getNetworkInfo() { 310 return mNetworkInfo; 311 } 312 313 public int getSecurity() { 314 return security; 315 } 316 317 public String getSecurityString(boolean concise) { 318 Context context = mContext; 319 if (mConfig != null && mConfig.isPasspoint()) { 320 return concise ? context.getString(R.string.wifi_security_short_eap) : 321 context.getString(R.string.wifi_security_eap); 322 } 323 switch(security) { 324 case SECURITY_EAP: 325 return concise ? context.getString(R.string.wifi_security_short_eap) : 326 context.getString(R.string.wifi_security_eap); 327 case SECURITY_PSK: 328 switch (pskType) { 329 case PSK_WPA: 330 return concise ? context.getString(R.string.wifi_security_short_wpa) : 331 context.getString(R.string.wifi_security_wpa); 332 case PSK_WPA2: 333 return concise ? context.getString(R.string.wifi_security_short_wpa2) : 334 context.getString(R.string.wifi_security_wpa2); 335 case PSK_WPA_WPA2: 336 return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) : 337 context.getString(R.string.wifi_security_wpa_wpa2); 338 case PSK_UNKNOWN: 339 default: 340 return concise ? context.getString(R.string.wifi_security_short_psk_generic) 341 : context.getString(R.string.wifi_security_psk_generic); 342 } 343 case SECURITY_WEP: 344 return concise ? context.getString(R.string.wifi_security_short_wep) : 345 context.getString(R.string.wifi_security_wep); 346 case SECURITY_NONE: 347 default: 348 return concise ? "" : context.getString(R.string.wifi_security_none); 349 } 350 } 351 352 public String getSsidStr() { 353 return ssid; 354 } 355 356 public String getBssid() { 357 return bssid; 358 } 359 360 public CharSequence getSsid() { 361 SpannableString str = new SpannableString(ssid); 362 str.setSpan(new TtsSpan.VerbatimBuilder(ssid).build(), 0, ssid.length(), 363 Spannable.SPAN_INCLUSIVE_INCLUSIVE); 364 return str; 365 } 366 367 public String getConfigName() { 368 if (mConfig != null && mConfig.isPasspoint()) { 369 return mConfig.providerFriendlyName; 370 } else { 371 return ssid; 372 } 373 } 374 375 public DetailedState getDetailedState() { 376 return mNetworkInfo != null ? mNetworkInfo.getDetailedState() : null; 377 } 378 379 public String getSavedNetworkSummary() { 380 WifiConfiguration config = mConfig; 381 if (config != null) { 382 PackageManager pm = mContext.getPackageManager(); 383 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID); 384 int userId = UserHandle.getUserId(config.creatorUid); 385 ApplicationInfo appInfo = null; 386 if (config.creatorName != null && config.creatorName.equals(systemName)) { 387 appInfo = mContext.getApplicationInfo(); 388 } else { 389 try { 390 IPackageManager ipm = AppGlobals.getPackageManager(); 391 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId); 392 } catch (RemoteException rex) { 393 } 394 } 395 if (appInfo != null && 396 !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) && 397 !appInfo.packageName.equals( 398 mContext.getString(R.string.certinstaller_package))) { 399 return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm)); 400 } 401 } 402 return ""; 403 } 404 405 public String getSummary() { 406 return getSettingsSummary(mConfig); 407 } 408 409 public String getSettingsSummary() { 410 return getSettingsSummary(mConfig); 411 } 412 413 private String getSettingsSummary(WifiConfiguration config) { 414 // Update to new summary 415 StringBuilder summary = new StringBuilder(); 416 417 if (isActive() && config != null && config.isPasspoint()) { 418 // This is the active connection on passpoint 419 summary.append(getSummary(mContext, getDetailedState(), 420 false, config.providerFriendlyName)); 421 } else if (isActive()) { 422 // This is the active connection on non-passpoint network 423 summary.append(getSummary(mContext, getDetailedState(), 424 mInfo != null && mInfo.isEphemeral())); 425 } else if (config != null && config.isPasspoint()) { 426 String format = mContext.getString(R.string.available_via_passpoint); 427 summary.append(String.format(format, config.providerFriendlyName)); 428 } else if (config != null && config.hasNoInternetAccess()) { 429 int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled() 430 ? R.string.wifi_no_internet_no_reconnect 431 : R.string.wifi_no_internet; 432 summary.append(mContext.getString(messageID)); 433 } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) { 434 WifiConfiguration.NetworkSelectionStatus networkStatus = 435 config.getNetworkSelectionStatus(); 436 switch (networkStatus.getNetworkSelectionDisableReason()) { 437 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE: 438 summary.append(mContext.getString(R.string.wifi_disabled_password_failure)); 439 break; 440 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE: 441 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE: 442 summary.append(mContext.getString(R.string.wifi_disabled_network_failure)); 443 break; 444 case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION: 445 summary.append(mContext.getString(R.string.wifi_disabled_generic)); 446 break; 447 } 448 } else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range 449 summary.append(mContext.getString(R.string.wifi_not_in_range)); 450 } else { // In range, not disabled. 451 if (config != null) { // Is saved network 452 summary.append(mContext.getString(R.string.wifi_remembered)); 453 } 454 } 455 456 if (WifiTracker.sVerboseLogging > 0) { 457 // Add RSSI/band information for this config, what was seen up to 6 seconds ago 458 // verbose WiFi Logging is only turned on thru developers settings 459 if (mInfo != null && mNetworkInfo != null) { // This is the active connection 460 summary.append(" f=" + Integer.toString(mInfo.getFrequency())); 461 } 462 summary.append(" " + getVisibilityStatus()); 463 if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) { 464 summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString()); 465 if (config.getNetworkSelectionStatus().getDisableTime() > 0) { 466 long now = System.currentTimeMillis(); 467 long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000; 468 long sec = diff%60; //seconds 469 long min = (diff/60)%60; //minutes 470 long hour = (min/60)%60; //hours 471 summary.append(", "); 472 if (hour > 0) summary.append(Long.toString(hour) + "h "); 473 summary.append( Long.toString(min) + "m "); 474 summary.append( Long.toString(sec) + "s "); 475 } 476 summary.append(")"); 477 } 478 479 if (config != null) { 480 WifiConfiguration.NetworkSelectionStatus networkStatus = 481 config.getNetworkSelectionStatus(); 482 for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE; 483 index < WifiConfiguration.NetworkSelectionStatus 484 .NETWORK_SELECTION_DISABLED_MAX; index++) { 485 if (networkStatus.getDisableReasonCounter(index) != 0) { 486 summary.append(" " + WifiConfiguration.NetworkSelectionStatus 487 .getNetworkDisableReasonString(index) + "=" 488 + networkStatus.getDisableReasonCounter(index)); 489 } 490 } 491 } 492 } 493 return summary.toString(); 494 } 495 496 /** 497 * Returns the visibility status of the WifiConfiguration. 498 * 499 * @return autojoin debugging information 500 * TODO: use a string formatter 501 * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"] 502 * For instance [-40,5/-30,2] 503 */ 504 private String getVisibilityStatus() { 505 StringBuilder visibility = new StringBuilder(); 506 StringBuilder scans24GHz = null; 507 StringBuilder scans5GHz = null; 508 String bssid = null; 509 510 long now = System.currentTimeMillis(); 511 512 if (mInfo != null) { 513 bssid = mInfo.getBSSID(); 514 if (bssid != null) { 515 visibility.append(" ").append(bssid); 516 } 517 visibility.append(" rssi=").append(mInfo.getRssi()); 518 visibility.append(" "); 519 visibility.append(" score=").append(mInfo.score); 520 visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate)); 521 visibility.append(String.format("%.1f,", mInfo.txRetriesRate)); 522 visibility.append(String.format("%.1f ", mInfo.txBadRate)); 523 visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate)); 524 } 525 526 int rssi5 = WifiConfiguration.INVALID_RSSI; 527 int rssi24 = WifiConfiguration.INVALID_RSSI; 528 int num5 = 0; 529 int num24 = 0; 530 int numBlackListed = 0; 531 int n24 = 0; // Number scan results we included in the string 532 int n5 = 0; // Number scan results we included in the string 533 evictOldScanResults(); 534 // TODO: sort list by RSSI or age 535 for (ScanResult result : mScanResultCache.values()) { 536 537 if (result.frequency >= LOWER_FREQ_5GHZ 538 && result.frequency <= HIGHER_FREQ_5GHZ) { 539 // Strictly speaking: [4915, 5825] 540 // number of known BSSID on 5GHz band 541 num5 = num5 + 1; 542 } else if (result.frequency >= LOWER_FREQ_24GHZ 543 && result.frequency <= HIGHER_FREQ_24GHZ) { 544 // Strictly speaking: [2412, 2482] 545 // number of known BSSID on 2.4Ghz band 546 num24 = num24 + 1; 547 } 548 549 550 if (result.frequency >= LOWER_FREQ_5GHZ 551 && result.frequency <= HIGHER_FREQ_5GHZ) { 552 if (result.level > rssi5) { 553 rssi5 = result.level; 554 } 555 if (n5 < 4) { 556 if (scans5GHz == null) scans5GHz = new StringBuilder(); 557 scans5GHz.append(" \n{").append(result.BSSID); 558 if (bssid != null && result.BSSID.equals(bssid)) scans5GHz.append("*"); 559 scans5GHz.append("=").append(result.frequency); 560 scans5GHz.append(",").append(result.level); 561 scans5GHz.append("}"); 562 n5++; 563 } 564 } else if (result.frequency >= LOWER_FREQ_24GHZ 565 && result.frequency <= HIGHER_FREQ_24GHZ) { 566 if (result.level > rssi24) { 567 rssi24 = result.level; 568 } 569 if (n24 < 4) { 570 if (scans24GHz == null) scans24GHz = new StringBuilder(); 571 scans24GHz.append(" \n{").append(result.BSSID); 572 if (bssid != null && result.BSSID.equals(bssid)) scans24GHz.append("*"); 573 scans24GHz.append("=").append(result.frequency); 574 scans24GHz.append(",").append(result.level); 575 scans24GHz.append("}"); 576 n24++; 577 } 578 } 579 } 580 visibility.append(" ["); 581 if (num24 > 0) { 582 visibility.append("(").append(num24).append(")"); 583 if (n24 <= 4) { 584 if (scans24GHz != null) { 585 visibility.append(scans24GHz.toString()); 586 } 587 } else { 588 visibility.append("max=").append(rssi24); 589 if (scans24GHz != null) { 590 visibility.append(",").append(scans24GHz.toString()); 591 } 592 } 593 } 594 visibility.append(";"); 595 if (num5 > 0) { 596 visibility.append("(").append(num5).append(")"); 597 if (n5 <= 4) { 598 if (scans5GHz != null) { 599 visibility.append(scans5GHz.toString()); 600 } 601 } else { 602 visibility.append("max=").append(rssi5); 603 if (scans5GHz != null) { 604 visibility.append(",").append(scans5GHz.toString()); 605 } 606 } 607 } 608 if (numBlackListed > 0) 609 visibility.append("!").append(numBlackListed); 610 visibility.append("]"); 611 612 return visibility.toString(); 613 } 614 615 /** 616 * Return whether this is the active connection. 617 * For ephemeral connections (networkId is invalid), this returns false if the network is 618 * disconnected. 619 */ 620 public boolean isActive() { 621 return mNetworkInfo != null && 622 (networkId != WifiConfiguration.INVALID_NETWORK_ID || 623 mNetworkInfo.getState() != State.DISCONNECTED); 624 } 625 626 public boolean isConnectable() { 627 return getLevel() != -1 && getDetailedState() == null; 628 } 629 630 public boolean isEphemeral() { 631 return mInfo != null && mInfo.isEphemeral() && 632 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED; 633 } 634 635 public boolean isPasspoint() { 636 return mConfig != null && mConfig.isPasspoint(); 637 } 638 639 /** 640 * Return whether the given {@link WifiInfo} is for this access point. 641 * If the current AP does not have a network Id then the config is used to 642 * match based on SSID and security. 643 */ 644 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) { 645 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) { 646 return networkId == info.getNetworkId(); 647 } else if (config != null) { 648 return matches(config); 649 } 650 else { 651 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID. 652 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID). 653 // TODO: Handle hex string SSIDs. 654 return ssid.equals(removeDoubleQuotes(info.getSSID())); 655 } 656 } 657 658 public boolean isSaved() { 659 return networkId != WifiConfiguration.INVALID_NETWORK_ID; 660 } 661 662 public Object getTag() { 663 return mTag; 664 } 665 666 public void setTag(Object tag) { 667 mTag = tag; 668 } 669 670 /** 671 * Generate and save a default wifiConfiguration with common values. 672 * Can only be called for unsecured networks. 673 */ 674 public void generateOpenNetworkConfig() { 675 if (security != SECURITY_NONE) 676 throw new IllegalStateException(); 677 if (mConfig != null) 678 return; 679 mConfig = new WifiConfiguration(); 680 mConfig.SSID = AccessPoint.convertToQuotedString(ssid); 681 mConfig.allowedKeyManagement.set(KeyMgmt.NONE); 682 } 683 684 void loadConfig(WifiConfiguration config) { 685 if (config.isPasspoint()) 686 ssid = config.providerFriendlyName; 687 else 688 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID)); 689 690 bssid = config.BSSID; 691 security = getSecurity(config); 692 networkId = config.networkId; 693 mConfig = config; 694 } 695 696 private void initWithScanResult(ScanResult result) { 697 ssid = result.SSID; 698 bssid = result.BSSID; 699 security = getSecurity(result); 700 if (security == SECURITY_PSK) 701 pskType = getPskType(result); 702 mRssi = result.level; 703 mSeen = result.timestamp; 704 } 705 706 public void saveWifiState(Bundle savedState) { 707 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr()); 708 savedState.putInt(KEY_SECURITY, security); 709 savedState.putInt(KEY_PSKTYPE, pskType); 710 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig); 711 savedState.putParcelable(KEY_WIFIINFO, mInfo); 712 evictOldScanResults(); 713 savedState.putParcelableArrayList(KEY_SCANRESULTCACHE, 714 new ArrayList<ScanResult>(mScanResultCache.values())); 715 if (mNetworkInfo != null) { 716 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo); 717 } 718 } 719 720 public void setListener(AccessPointListener listener) { 721 mAccessPointListener = listener; 722 } 723 724 boolean update(ScanResult result) { 725 if (matches(result)) { 726 /* Add or update the scan result for the BSSID */ 727 mScanResultCache.put(result.BSSID, result); 728 729 int oldLevel = getLevel(); 730 int oldRssi = getRssi(); 731 mSeen = getSeen(); 732 mRssi = (getRssi() + oldRssi)/2; 733 int newLevel = getLevel(); 734 735 if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) { 736 mAccessPointListener.onLevelChanged(this); 737 } 738 // This flag only comes from scans, is not easily saved in config 739 if (security == SECURITY_PSK) { 740 pskType = getPskType(result); 741 } 742 743 if (mAccessPointListener != null) { 744 mAccessPointListener.onAccessPointChanged(this); 745 } 746 747 return true; 748 } 749 return false; 750 } 751 752 boolean update(WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) { 753 boolean reorder = false; 754 if (info != null && isInfoForThisAccessPoint(config, info)) { 755 reorder = (mInfo == null); 756 mRssi = info.getRssi(); 757 mInfo = info; 758 mNetworkInfo = networkInfo; 759 if (mAccessPointListener != null) { 760 mAccessPointListener.onAccessPointChanged(this); 761 } 762 } else if (mInfo != null) { 763 reorder = true; 764 mInfo = null; 765 mNetworkInfo = null; 766 if (mAccessPointListener != null) { 767 mAccessPointListener.onAccessPointChanged(this); 768 } 769 } 770 return reorder; 771 } 772 773 void update(WifiConfiguration config) { 774 mConfig = config; 775 networkId = config.networkId; 776 if (mAccessPointListener != null) { 777 mAccessPointListener.onAccessPointChanged(this); 778 } 779 } 780 781 void setRssi(int rssi) { 782 mRssi = rssi; 783 } 784 785 public static String getSummary(Context context, String ssid, DetailedState state, 786 boolean isEphemeral, String passpointProvider) { 787 if (state == DetailedState.CONNECTED && ssid == null) { 788 if (TextUtils.isEmpty(passpointProvider) == false) { 789 // Special case for connected + passpoint networks. 790 String format = context.getString(R.string.connected_via_passpoint); 791 return String.format(format, passpointProvider); 792 } else if (isEphemeral) { 793 // Special case for connected + ephemeral networks. 794 return context.getString(R.string.connected_via_wfa); 795 } 796 } 797 798 // Case when there is wifi connected without internet connectivity. 799 final ConnectivityManager cm = (ConnectivityManager) 800 context.getSystemService(Context.CONNECTIVITY_SERVICE); 801 if (state == DetailedState.CONNECTED) { 802 IWifiManager wifiManager = IWifiManager.Stub.asInterface( 803 ServiceManager.getService(Context.WIFI_SERVICE)); 804 Network nw; 805 806 try { 807 nw = wifiManager.getCurrentNetwork(); 808 } catch (RemoteException e) { 809 nw = null; 810 } 811 NetworkCapabilities nc = cm.getNetworkCapabilities(nw); 812 if (nc != null && !nc.hasCapability(nc.NET_CAPABILITY_VALIDATED)) { 813 return context.getString(R.string.wifi_connected_no_internet); 814 } 815 } 816 817 String[] formats = context.getResources().getStringArray((ssid == null) 818 ? R.array.wifi_status : R.array.wifi_status_with_ssid); 819 int index = state.ordinal(); 820 821 if (index >= formats.length || formats[index].length() == 0) { 822 return ""; 823 } 824 return String.format(formats[index], ssid); 825 } 826 827 public static String getSummary(Context context, DetailedState state, boolean isEphemeral) { 828 return getSummary(context, null, state, isEphemeral, null); 829 } 830 831 public static String getSummary(Context context, DetailedState state, boolean isEphemeral, 832 String passpointProvider) { 833 return getSummary(context, null, state, isEphemeral, passpointProvider); 834 } 835 836 public static String convertToQuotedString(String string) { 837 return "\"" + string + "\""; 838 } 839 840 private static int getPskType(ScanResult result) { 841 boolean wpa = result.capabilities.contains("WPA-PSK"); 842 boolean wpa2 = result.capabilities.contains("WPA2-PSK"); 843 if (wpa2 && wpa) { 844 return PSK_WPA_WPA2; 845 } else if (wpa2) { 846 return PSK_WPA2; 847 } else if (wpa) { 848 return PSK_WPA; 849 } else { 850 Log.w(TAG, "Received abnormal flag string: " + result.capabilities); 851 return PSK_UNKNOWN; 852 } 853 } 854 855 private static int getSecurity(ScanResult result) { 856 if (result.capabilities.contains("WEP")) { 857 return SECURITY_WEP; 858 } else if (result.capabilities.contains("PSK")) { 859 return SECURITY_PSK; 860 } else if (result.capabilities.contains("EAP")) { 861 return SECURITY_EAP; 862 } 863 return SECURITY_NONE; 864 } 865 866 static int getSecurity(WifiConfiguration config) { 867 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { 868 return SECURITY_PSK; 869 } 870 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || 871 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { 872 return SECURITY_EAP; 873 } 874 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE; 875 } 876 877 public static String securityToString(int security, int pskType) { 878 if (security == SECURITY_WEP) { 879 return "WEP"; 880 } else if (security == SECURITY_PSK) { 881 if (pskType == PSK_WPA) { 882 return "WPA"; 883 } else if (pskType == PSK_WPA2) { 884 return "WPA2"; 885 } else if (pskType == PSK_WPA_WPA2) { 886 return "WPA_WPA2"; 887 } 888 return "PSK"; 889 } else if (security == SECURITY_EAP) { 890 return "EAP"; 891 } 892 return "NONE"; 893 } 894 895 static String removeDoubleQuotes(String string) { 896 if (TextUtils.isEmpty(string)) { 897 return ""; 898 } 899 int length = string.length(); 900 if ((length > 1) && (string.charAt(0) == '"') 901 && (string.charAt(length - 1) == '"')) { 902 return string.substring(1, length - 1); 903 } 904 return string; 905 } 906 907 public interface AccessPointListener { 908 void onAccessPointChanged(AccessPoint accessPoint); 909 void onLevelChanged(AccessPoint accessPoint); 910 } 911} 912