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