AccessPoint.java revision fca9a47ba86163defeb100a75fc856be6c1f3159
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.annotation.IntDef; 20import android.annotation.Nullable; 21import android.app.AppGlobals; 22import android.content.Context; 23import android.content.pm.ApplicationInfo; 24import android.content.pm.IPackageManager; 25import android.content.pm.PackageManager; 26import android.net.ConnectivityManager; 27import android.net.NetworkCapabilities; 28import android.net.NetworkInfo; 29import android.net.NetworkInfo.DetailedState; 30import android.net.NetworkInfo.State; 31import android.net.NetworkKey; 32import android.net.NetworkScoreManager; 33import android.net.NetworkScorerAppData; 34import android.net.ScoredNetwork; 35import android.net.WifiKey; 36import android.net.wifi.IWifiManager; 37import android.net.wifi.ScanResult; 38import android.net.wifi.WifiConfiguration; 39import android.net.wifi.WifiConfiguration.KeyMgmt; 40import android.net.wifi.WifiEnterpriseConfig; 41import android.net.wifi.WifiInfo; 42import android.net.wifi.WifiManager; 43import android.net.wifi.WifiNetworkScoreCache; 44import android.net.wifi.hotspot2.PasspointConfiguration; 45import android.os.Bundle; 46import android.os.RemoteException; 47import android.os.ServiceManager; 48import android.os.SystemClock; 49import android.os.UserHandle; 50import android.support.annotation.NonNull; 51import android.text.Spannable; 52import android.text.SpannableString; 53import android.text.TextUtils; 54import android.text.style.TtsSpan; 55import android.util.Log; 56 57import com.android.internal.annotations.VisibleForTesting; 58import com.android.settingslib.R; 59 60import java.lang.annotation.Retention; 61import java.lang.annotation.RetentionPolicy; 62import java.util.ArrayList; 63import java.util.HashMap; 64import java.util.Iterator; 65import java.util.Map; 66import java.util.concurrent.ConcurrentHashMap; 67import java.util.concurrent.atomic.AtomicInteger; 68 69 70public class AccessPoint implements Comparable<AccessPoint> { 71 static final String TAG = "SettingsLib.AccessPoint"; 72 73 /** 74 * Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels 75 */ 76 public static final int LOWER_FREQ_24GHZ = 2400; 77 78 /** 79 * Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels 80 */ 81 public static final int HIGHER_FREQ_24GHZ = 2500; 82 83 /** 84 * Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels 85 */ 86 public static final int LOWER_FREQ_5GHZ = 4900; 87 88 /** 89 * Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels 90 */ 91 public static final int HIGHER_FREQ_5GHZ = 5900; 92 93 @IntDef({Speed.NONE, Speed.SLOW, Speed.MODERATE, Speed.FAST, Speed.VERY_FAST}) 94 @Retention(RetentionPolicy.SOURCE) 95 public @interface Speed { 96 /** 97 * Constant value representing an unlabeled / unscored network. 98 */ 99 int NONE = 0; 100 /** 101 * Constant value representing a slow speed network connection. 102 */ 103 int SLOW = 5; 104 /** 105 * Constant value representing a medium speed network connection. 106 */ 107 int MODERATE = 10; 108 /** 109 * Constant value representing a fast speed network connection. 110 */ 111 int FAST = 20; 112 /** 113 * Constant value representing a very fast speed network connection. 114 */ 115 int VERY_FAST = 30; 116 } 117 118 /** 119 * Experimental: we should be able to show the user the list of BSSIDs and bands 120 * for that SSID. 121 * For now this data is used only with Verbose Logging so as to show the band and number 122 * of BSSIDs on which that network is seen. 123 */ 124 private final ConcurrentHashMap<String, ScanResult> mScanResultCache = 125 new ConcurrentHashMap<String, ScanResult>(32); 126 127 /** Map of BSSIDs to speed values for individual ScanResults. */ 128 private final Map<String, Integer> mScanResultScores = new HashMap<>(); 129 130 /** Maximum age of scan results to hold onto while actively scanning. **/ 131 private static final long MAX_SCAN_RESULT_AGE_MS = 15000; 132 133 static final String KEY_NETWORKINFO = "key_networkinfo"; 134 static final String KEY_WIFIINFO = "key_wifiinfo"; 135 static final String KEY_SCANRESULT = "key_scanresult"; 136 static final String KEY_SSID = "key_ssid"; 137 static final String KEY_SECURITY = "key_security"; 138 static final String KEY_SPEED = "key_speed"; 139 static final String KEY_PSKTYPE = "key_psktype"; 140 static final String KEY_SCANRESULTCACHE = "key_scanresultcache"; 141 static final String KEY_CONFIG = "key_config"; 142 static final String KEY_FQDN = "key_fqdn"; 143 static final String KEY_PROVIDER_FRIENDLY_NAME = "key_provider_friendly_name"; 144 static final String KEY_IS_CARRIER_AP = "key_is_carrier_ap"; 145 static final String KEY_CARRIER_AP_EAP_TYPE = "key_carrier_ap_eap_type"; 146 static final String KEY_CARRIER_NAME = "key_carrier_name"; 147 static final AtomicInteger sLastId = new AtomicInteger(0); 148 149 /** 150 * These values are matched in string arrays -- changes must be kept in sync 151 */ 152 public static final int SECURITY_NONE = 0; 153 public static final int SECURITY_WEP = 1; 154 public static final int SECURITY_PSK = 2; 155 public static final int SECURITY_EAP = 3; 156 157 private static final int PSK_UNKNOWN = 0; 158 private static final int PSK_WPA = 1; 159 private static final int PSK_WPA2 = 2; 160 private static final int PSK_WPA_WPA2 = 3; 161 162 /** 163 * The number of distinct wifi levels. 164 * 165 * <p>Must keep in sync with {@link R.array.wifi_signal} and {@link WifiManager#RSSI_LEVELS}. 166 */ 167 public static final int SIGNAL_LEVELS = 5; 168 169 public static final int UNREACHABLE_RSSI = Integer.MIN_VALUE; 170 171 private final Context mContext; 172 173 private String ssid; 174 private String bssid; 175 private int security; 176 private int networkId = WifiConfiguration.INVALID_NETWORK_ID; 177 178 private int pskType = PSK_UNKNOWN; 179 180 private WifiConfiguration mConfig; 181 182 private int mRssi = UNREACHABLE_RSSI; 183 private long mSeen = 0; 184 185 private WifiInfo mInfo; 186 private NetworkInfo mNetworkInfo; 187 AccessPointListener mAccessPointListener; 188 189 private Object mTag; 190 191 private int mSpeed = Speed.NONE; 192 private boolean mIsScoredNetworkMetered = false; 193 194 // used to co-relate internal vs returned accesspoint. 195 int mId; 196 197 /** 198 * Information associated with the {@link PasspointConfiguration}. Only maintaining 199 * the relevant info to preserve spaces. 200 */ 201 private String mFqdn; 202 private String mProviderFriendlyName; 203 204 private boolean mIsCarrierAp = false; 205 /** 206 * The EAP type {@link WifiEnterpriseConfig.Eap} associated with this AP if it is a carrier AP. 207 */ 208 private int mCarrierApEapType = WifiEnterpriseConfig.Eap.NONE; 209 private String mCarrierName = null; 210 211 public AccessPoint(Context context, Bundle savedState) { 212 mContext = context; 213 mConfig = savedState.getParcelable(KEY_CONFIG); 214 if (mConfig != null) { 215 loadConfig(mConfig); 216 } 217 if (savedState.containsKey(KEY_SSID)) { 218 ssid = savedState.getString(KEY_SSID); 219 } 220 if (savedState.containsKey(KEY_SECURITY)) { 221 security = savedState.getInt(KEY_SECURITY); 222 } 223 if (savedState.containsKey(KEY_SPEED)) { 224 mSpeed = savedState.getInt(KEY_SPEED); 225 } 226 if (savedState.containsKey(KEY_PSKTYPE)) { 227 pskType = savedState.getInt(KEY_PSKTYPE); 228 } 229 mInfo = savedState.getParcelable(KEY_WIFIINFO); 230 if (savedState.containsKey(KEY_NETWORKINFO)) { 231 mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO); 232 } 233 if (savedState.containsKey(KEY_SCANRESULTCACHE)) { 234 ArrayList<ScanResult> scanResultArrayList = 235 savedState.getParcelableArrayList(KEY_SCANRESULTCACHE); 236 mScanResultCache.clear(); 237 for (ScanResult result : scanResultArrayList) { 238 mScanResultCache.put(result.BSSID, result); 239 } 240 } 241 if (savedState.containsKey(KEY_FQDN)) { 242 mFqdn = savedState.getString(KEY_FQDN); 243 } 244 if (savedState.containsKey(KEY_PROVIDER_FRIENDLY_NAME)) { 245 mProviderFriendlyName = savedState.getString(KEY_PROVIDER_FRIENDLY_NAME); 246 } 247 if (savedState.containsKey(KEY_IS_CARRIER_AP)) { 248 mIsCarrierAp = savedState.getBoolean(KEY_IS_CARRIER_AP); 249 } 250 if (savedState.containsKey(KEY_CARRIER_AP_EAP_TYPE)) { 251 mCarrierApEapType = savedState.getInt(KEY_CARRIER_AP_EAP_TYPE); 252 } 253 if (savedState.containsKey(KEY_CARRIER_NAME)) { 254 mCarrierName = savedState.getString(KEY_CARRIER_NAME); 255 } 256 update(mConfig, mInfo, mNetworkInfo); 257 updateRssi(); 258 updateSeen(); 259 mId = sLastId.incrementAndGet(); 260 } 261 262 public AccessPoint(Context context, WifiConfiguration config) { 263 mContext = context; 264 loadConfig(config); 265 mId = sLastId.incrementAndGet(); 266 } 267 268 /** 269 * Initialize an AccessPoint object for a {@link PasspointConfiguration}. This is mainly 270 * used by "Saved Networks" page for managing the saved {@link PasspointConfiguration}. 271 */ 272 public AccessPoint(Context context, PasspointConfiguration config) { 273 mContext = context; 274 mFqdn = config.getHomeSp().getFqdn(); 275 mProviderFriendlyName = config.getHomeSp().getFriendlyName(); 276 mId = sLastId.incrementAndGet(); 277 } 278 279 AccessPoint(Context context, AccessPoint other) { 280 mContext = context; 281 copyFrom(other); 282 } 283 284 AccessPoint(Context context, ScanResult result) { 285 mContext = context; 286 initWithScanResult(result); 287 mId = sLastId.incrementAndGet(); 288 } 289 290 /** 291 * Copy accesspoint information. NOTE: We do not copy tag information because that is never 292 * set on the internal copy. 293 * @param that 294 */ 295 void copyFrom(AccessPoint that) { 296 that.evictOldScanResults(); 297 this.ssid = that.ssid; 298 this.bssid = that.bssid; 299 this.security = that.security; 300 this.networkId = that.networkId; 301 this.pskType = that.pskType; 302 this.mConfig = that.mConfig; //TODO: Watch out, this object is mutated. 303 this.mRssi = that.mRssi; 304 this.mSeen = that.mSeen; 305 this.mInfo = that.mInfo; 306 this.mNetworkInfo = that.mNetworkInfo; 307 this.mScanResultCache.clear(); 308 this.mScanResultCache.putAll(that.mScanResultCache); 309 this.mScanResultScores.clear(); 310 this.mScanResultScores.putAll(that.mScanResultScores); 311 this.mId = that.mId; 312 this.mSpeed = that.mSpeed; 313 this.mIsScoredNetworkMetered = that.mIsScoredNetworkMetered; 314 this.mIsCarrierAp = that.mIsCarrierAp; 315 this.mCarrierApEapType = that.mCarrierApEapType; 316 this.mCarrierName = that.mCarrierName; 317 } 318 319 /** 320 * Returns a negative integer, zero, or a positive integer if this AccessPoint is less than, 321 * equal to, or greater than the other AccessPoint. 322 * 323 * Sort order rules for AccessPoints: 324 * 1. Active before inactive 325 * 2. Reachable before unreachable 326 * 3. Saved before unsaved 327 * 4. Network speed value 328 * 5. Stronger signal before weaker signal 329 * 6. SSID alphabetically 330 * 331 * Note that AccessPoints with a signal are usually also Reachable, 332 * and will thus appear before unreachable saved AccessPoints. 333 */ 334 @Override 335 public int compareTo(@NonNull AccessPoint other) { 336 // Active one goes first. 337 if (isActive() && !other.isActive()) return -1; 338 if (!isActive() && other.isActive()) return 1; 339 340 // Reachable one goes before unreachable one. 341 if (isReachable() && !other.isReachable()) return -1; 342 if (!isReachable() && other.isReachable()) return 1; 343 344 // Configured (saved) one goes before unconfigured one. 345 if (isSaved() && !other.isSaved()) return -1; 346 if (!isSaved() && other.isSaved()) return 1; 347 348 // Faster speeds go before slower speeds 349 if (getSpeed() != other.getSpeed()) { 350 return other.getSpeed() - getSpeed(); 351 } 352 353 // Sort by signal strength, bucketed by level 354 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS) 355 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS); 356 if (difference != 0) { 357 return difference; 358 } 359 360 // Sort by ssid. 361 difference = getSsidStr().compareToIgnoreCase(other.getSsidStr()); 362 if (difference != 0) { 363 return difference; 364 } 365 366 // Do a case sensitive comparison to distinguish SSIDs that differ in case only 367 return getSsidStr().compareTo(other.getSsidStr()); 368 } 369 370 @Override 371 public boolean equals(Object other) { 372 if (!(other instanceof AccessPoint)) return false; 373 return (this.compareTo((AccessPoint) other) == 0); 374 } 375 376 @Override 377 public int hashCode() { 378 int result = 0; 379 if (mInfo != null) result += 13 * mInfo.hashCode(); 380 result += 19 * mRssi; 381 result += 23 * networkId; 382 result += 29 * ssid.hashCode(); 383 return result; 384 } 385 386 @Override 387 public String toString() { 388 StringBuilder builder = new StringBuilder().append("AccessPoint(") 389 .append(ssid); 390 if (bssid != null) { 391 builder.append(":").append(bssid); 392 } 393 if (isSaved()) { 394 builder.append(',').append("saved"); 395 } 396 if (isActive()) { 397 builder.append(',').append("active"); 398 } 399 if (isEphemeral()) { 400 builder.append(',').append("ephemeral"); 401 } 402 if (isConnectable()) { 403 builder.append(',').append("connectable"); 404 } 405 if (security != SECURITY_NONE) { 406 builder.append(',').append(securityToString(security, pskType)); 407 } 408 builder.append(",level=").append(getLevel()); 409 if (mSpeed != Speed.NONE) { 410 builder.append(",speed=").append(mSpeed); 411 } 412 builder.append(",metered=").append(isMetered()); 413 414 return builder.append(')').toString(); 415 } 416 417 /** 418 * Updates the AccessPoint rankingScore, metering, and speed, returning true if the data has 419 * changed. 420 * 421 * @param scoreCache The score cache to use to retrieve scores. 422 * @param scoringUiEnabled Whether to show scoring and badging UI. 423 */ 424 boolean update(WifiNetworkScoreCache scoreCache, boolean scoringUiEnabled) { 425 boolean scoreChanged = false; 426 mScanResultScores.clear(); 427 if (scoringUiEnabled) { 428 scoreChanged = updateScores(scoreCache); 429 } 430 return updateMetered(scoreCache) || scoreChanged; 431 } 432 433 /** 434 * Updates the AccessPoint rankingScore and speed, returning true if the data has changed. 435 * 436 * @param scoreCache The score cache to use to retrieve scores. 437 */ 438 private boolean updateScores(WifiNetworkScoreCache scoreCache) { 439 int oldSpeed = mSpeed; 440 mSpeed = Speed.NONE; 441 442 for (ScanResult result : mScanResultCache.values()) { 443 ScoredNetwork score = scoreCache.getScoredNetwork(result); 444 if (score == null) { 445 continue; 446 } 447 448 int speed = score.calculateBadge(result.level); 449 mScanResultScores.put(result.BSSID, speed); 450 mSpeed = Math.max(mSpeed, speed); 451 } 452 453 // set mSpeed to the connected ScanResult if the AccessPoint is the active network 454 if (isActive() && mInfo != null) { 455 NetworkKey key = new NetworkKey(new WifiKey( 456 AccessPoint.convertToQuotedString(ssid), mInfo.getBSSID())); 457 ScoredNetwork score = scoreCache.getScoredNetwork(key); 458 if (score != null) { 459 mSpeed = score.calculateBadge(mInfo.getRssi()); 460 } 461 } 462 463 if(WifiTracker.sVerboseLogging) { 464 Log.i(TAG, String.format("%s: Set speed to %d", ssid, mSpeed)); 465 } 466 467 return oldSpeed != mSpeed; 468 } 469 470 /** 471 * Updates the AccessPoint's metering based on {@link ScoredNetwork#meteredHint}, returning 472 * true if the metering changed. 473 */ 474 private boolean updateMetered(WifiNetworkScoreCache scoreCache) { 475 boolean oldMetering = mIsScoredNetworkMetered; 476 mIsScoredNetworkMetered = false; 477 478 if (isActive() && mInfo != null) { 479 NetworkKey key = new NetworkKey(new WifiKey( 480 AccessPoint.convertToQuotedString(ssid), mInfo.getBSSID())); 481 ScoredNetwork score = scoreCache.getScoredNetwork(key); 482 if (score != null) { 483 mIsScoredNetworkMetered |= score.meteredHint; 484 } 485 } else { 486 for (ScanResult result : mScanResultCache.values()) { 487 ScoredNetwork score = scoreCache.getScoredNetwork(result); 488 if (score == null) { 489 continue; 490 } 491 mIsScoredNetworkMetered |= score.meteredHint; 492 } 493 } 494 return oldMetering == mIsScoredNetworkMetered; 495 } 496 497 private void evictOldScanResults() { 498 if (WifiTracker.sStaleScanResults) { 499 // Do not evict old scan results unless we are scanning and have fresh results. 500 return; 501 } 502 long nowMs = SystemClock.elapsedRealtime(); 503 for (Iterator<ScanResult> iter = mScanResultCache.values().iterator(); iter.hasNext(); ) { 504 ScanResult result = iter.next(); 505 // result timestamp is in microseconds 506 if (nowMs - result.timestamp / 1000 > MAX_SCAN_RESULT_AGE_MS) { 507 iter.remove(); 508 } 509 } 510 } 511 512 public boolean matches(ScanResult result) { 513 return ssid.equals(result.SSID) && security == getSecurity(result); 514 } 515 516 public boolean matches(WifiConfiguration config) { 517 if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) { 518 return ssid.equals(removeDoubleQuotes(config.SSID)) && config.FQDN.equals(mConfig.FQDN); 519 } else { 520 return ssid.equals(removeDoubleQuotes(config.SSID)) 521 && security == getSecurity(config) 522 && (mConfig == null || mConfig.shared == config.shared); 523 } 524 } 525 526 public WifiConfiguration getConfig() { 527 return mConfig; 528 } 529 530 public String getPasspointFqdn() { 531 return mFqdn; 532 } 533 534 public void clearConfig() { 535 mConfig = null; 536 networkId = WifiConfiguration.INVALID_NETWORK_ID; 537 } 538 539 public WifiInfo getInfo() { 540 return mInfo; 541 } 542 543 /** 544 * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1. 545 * 546 * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will 547 * always return at least 0. 548 */ 549 public int getLevel() { 550 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS); 551 } 552 553 public int getRssi() { 554 return mRssi; 555 } 556 557 /** 558 * Updates {@link #mRssi}. 559 * 560 * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned. 561 * If the given AccessPoint is not active, a value will be calculated from previous scan 562 * results, returning the best RSSI for all matching AccessPoints averaged with the previous 563 * value. If the access point is not connected and there are no scan results, the rssi will be 564 * set to {@link #UNREACHABLE_RSSI}. 565 * 566 * <p>Old scan results will be evicted from the cache when this method is invoked. 567 */ 568 private void updateRssi() { 569 evictOldScanResults(); 570 571 if (this.isActive()) { 572 return; 573 } 574 575 int rssi = UNREACHABLE_RSSI; 576 for (ScanResult result : mScanResultCache.values()) { 577 if (result.level > rssi) { 578 rssi = result.level; 579 } 580 } 581 582 if (rssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) { 583 mRssi = (mRssi + rssi) / 2; // half-life previous value 584 } else { 585 mRssi = rssi; 586 } 587 } 588 589 /** 590 * Updates {@link #mSeen} based on the scan result cache. 591 * 592 * <p>Old scan results will be evicted from the cache when this method is invoked. 593 */ 594 private void updateSeen() { 595 evictOldScanResults(); 596 597 // TODO(sghuman): Set to now if connected 598 599 long seen = 0; 600 for (ScanResult result : mScanResultCache.values()) { 601 if (result.timestamp > seen) { 602 seen = result.timestamp; 603 } 604 } 605 606 // Only replace the previous value if we have a recent scan result to use 607 if (seen != 0) { 608 mSeen = seen; 609 } 610 } 611 612 /** 613 * Returns if the network should be considered metered. 614 */ 615 public boolean isMetered() { 616 return mIsScoredNetworkMetered 617 || WifiConfiguration.isMetered(mConfig, mInfo); 618 } 619 620 public NetworkInfo getNetworkInfo() { 621 return mNetworkInfo; 622 } 623 624 public int getSecurity() { 625 return security; 626 } 627 628 public String getSecurityString(boolean concise) { 629 Context context = mContext; 630 if (isPasspoint() || isPasspointConfig()) { 631 return concise ? context.getString(R.string.wifi_security_short_eap) : 632 context.getString(R.string.wifi_security_eap); 633 } 634 switch(security) { 635 case SECURITY_EAP: 636 return concise ? context.getString(R.string.wifi_security_short_eap) : 637 context.getString(R.string.wifi_security_eap); 638 case SECURITY_PSK: 639 switch (pskType) { 640 case PSK_WPA: 641 return concise ? context.getString(R.string.wifi_security_short_wpa) : 642 context.getString(R.string.wifi_security_wpa); 643 case PSK_WPA2: 644 return concise ? context.getString(R.string.wifi_security_short_wpa2) : 645 context.getString(R.string.wifi_security_wpa2); 646 case PSK_WPA_WPA2: 647 return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) : 648 context.getString(R.string.wifi_security_wpa_wpa2); 649 case PSK_UNKNOWN: 650 default: 651 return concise ? context.getString(R.string.wifi_security_short_psk_generic) 652 : context.getString(R.string.wifi_security_psk_generic); 653 } 654 case SECURITY_WEP: 655 return concise ? context.getString(R.string.wifi_security_short_wep) : 656 context.getString(R.string.wifi_security_wep); 657 case SECURITY_NONE: 658 default: 659 return concise ? "" : context.getString(R.string.wifi_security_none); 660 } 661 } 662 663 public String getSsidStr() { 664 return ssid; 665 } 666 667 public String getBssid() { 668 return bssid; 669 } 670 671 public CharSequence getSsid() { 672 final SpannableString str = new SpannableString(ssid); 673 str.setSpan(new TtsSpan.TelephoneBuilder(ssid).build(), 0, ssid.length(), 674 Spannable.SPAN_INCLUSIVE_INCLUSIVE); 675 return str; 676 } 677 678 public String getConfigName() { 679 if (mConfig != null && mConfig.isPasspoint()) { 680 return mConfig.providerFriendlyName; 681 } else if (mFqdn != null) { 682 return mProviderFriendlyName; 683 } else { 684 return ssid; 685 } 686 } 687 688 public DetailedState getDetailedState() { 689 if (mNetworkInfo != null) { 690 return mNetworkInfo.getDetailedState(); 691 } 692 Log.w(TAG, "NetworkInfo is null, cannot return detailed state"); 693 return null; 694 } 695 696 public boolean isCarrierAp() { 697 return mIsCarrierAp; 698 } 699 700 public int getCarrierApEapType() { 701 return mCarrierApEapType; 702 } 703 704 public String getCarrierName() { 705 return mCarrierName; 706 } 707 708 public String getSavedNetworkSummary() { 709 WifiConfiguration config = mConfig; 710 if (config != null) { 711 PackageManager pm = mContext.getPackageManager(); 712 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID); 713 int userId = UserHandle.getUserId(config.creatorUid); 714 ApplicationInfo appInfo = null; 715 if (config.creatorName != null && config.creatorName.equals(systemName)) { 716 appInfo = mContext.getApplicationInfo(); 717 } else { 718 try { 719 IPackageManager ipm = AppGlobals.getPackageManager(); 720 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId); 721 } catch (RemoteException rex) { 722 } 723 } 724 if (appInfo != null && 725 !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) && 726 !appInfo.packageName.equals( 727 mContext.getString(R.string.certinstaller_package))) { 728 return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm)); 729 } 730 } 731 return ""; 732 } 733 734 public String getSummary() { 735 return getSettingsSummary(mConfig); 736 } 737 738 public String getSettingsSummary() { 739 return getSettingsSummary(mConfig); 740 } 741 742 private String getSettingsSummary(WifiConfiguration config) { 743 // Update to new summary 744 StringBuilder summary = new StringBuilder(); 745 746 if (isActive() && config != null && config.isPasspoint()) { 747 // This is the active connection on passpoint 748 summary.append(getSummary(mContext, getDetailedState(), 749 false, config.providerFriendlyName)); 750 } else if (isActive() && config != null && getDetailedState() == DetailedState.CONNECTED 751 && mIsCarrierAp) { 752 summary.append(String.format(mContext.getString(R.string.connected_via_carrier), mCarrierName)); 753 } else if (isActive()) { 754 // This is the active connection on non-passpoint network 755 summary.append(getSummary(mContext, getDetailedState(), 756 mInfo != null && mInfo.isEphemeral())); 757 } else if (config != null && config.isPasspoint() 758 && config.getNetworkSelectionStatus().isNetworkEnabled()) { 759 String format = mContext.getString(R.string.available_via_passpoint); 760 summary.append(String.format(format, config.providerFriendlyName)); 761 } else if (config != null && config.hasNoInternetAccess()) { 762 int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled() 763 ? R.string.wifi_no_internet_no_reconnect 764 : R.string.wifi_no_internet; 765 summary.append(mContext.getString(messageID)); 766 } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) { 767 WifiConfiguration.NetworkSelectionStatus networkStatus = 768 config.getNetworkSelectionStatus(); 769 switch (networkStatus.getNetworkSelectionDisableReason()) { 770 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE: 771 summary.append(mContext.getString(R.string.wifi_disabled_password_failure)); 772 break; 773 case WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD: 774 summary.append(mContext.getString(R.string.wifi_check_password_try_again)); 775 break; 776 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE: 777 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE: 778 summary.append(mContext.getString(R.string.wifi_disabled_network_failure)); 779 break; 780 case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION: 781 summary.append(mContext.getString(R.string.wifi_disabled_generic)); 782 break; 783 } 784 } else if (config != null && config.getNetworkSelectionStatus().isNotRecommended()) { 785 summary.append(mContext.getString(R.string.wifi_disabled_by_recommendation_provider)); 786 } else if (mIsCarrierAp) { 787 summary.append(String.format(mContext.getString(R.string.available_via_carrier), mCarrierName)); 788 } else if (!isReachable()) { // Wifi out of range 789 summary.append(mContext.getString(R.string.wifi_not_in_range)); 790 } else { // In range, not disabled. 791 if (config != null) { // Is saved network 792 // Last attempt to connect to this failed. Show reason why 793 switch (config.recentFailure.getAssociationStatus()) { 794 case WifiConfiguration.RecentFailure.STATUS_AP_UNABLE_TO_HANDLE_NEW_STA: 795 summary.append(mContext.getString( 796 R.string.wifi_ap_unable_to_handle_new_sta)); 797 break; 798 default: 799 // "Saved" 800 summary.append(mContext.getString(R.string.wifi_remembered)); 801 break; 802 } 803 } 804 } 805 806 if (WifiTracker.sVerboseLogging) { 807 // Add RSSI/band information for this config, what was seen up to 6 seconds ago 808 // verbose WiFi Logging is only turned on thru developers settings 809 if (isActive() && mInfo != null) { 810 summary.append(" f=" + Integer.toString(mInfo.getFrequency())); 811 } 812 summary.append(" " + getVisibilityStatus()); 813 if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) { 814 summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString()); 815 if (config.getNetworkSelectionStatus().getDisableTime() > 0) { 816 long now = System.currentTimeMillis(); 817 long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000; 818 long sec = diff%60; //seconds 819 long min = (diff/60)%60; //minutes 820 long hour = (min/60)%60; //hours 821 summary.append(", "); 822 if (hour > 0) summary.append(Long.toString(hour) + "h "); 823 summary.append( Long.toString(min) + "m "); 824 summary.append( Long.toString(sec) + "s "); 825 } 826 summary.append(")"); 827 } 828 829 if (config != null) { 830 WifiConfiguration.NetworkSelectionStatus networkStatus = 831 config.getNetworkSelectionStatus(); 832 for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE; 833 index < WifiConfiguration.NetworkSelectionStatus 834 .NETWORK_SELECTION_DISABLED_MAX; index++) { 835 if (networkStatus.getDisableReasonCounter(index) != 0) { 836 summary.append(" " + WifiConfiguration.NetworkSelectionStatus 837 .getNetworkDisableReasonString(index) + "=" 838 + networkStatus.getDisableReasonCounter(index)); 839 } 840 } 841 } 842 } 843 844 // If Speed label and summary are both present, use the preference combination to combine 845 // the two, else return the non-null one. 846 if (getSpeedLabel() != null && summary.length() != 0) { 847 return mContext.getResources().getString( 848 R.string.preference_summary_default_combination, 849 getSpeedLabel(), 850 summary.toString()); 851 } else if (getSpeedLabel() != null) { 852 return getSpeedLabel(); 853 } else { 854 return summary.toString(); 855 } 856 } 857 858 /** 859 * Returns the visibility status of the WifiConfiguration. 860 * 861 * @return autojoin debugging information 862 * TODO: use a string formatter 863 * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"] 864 * For instance [-40,5/-30,2] 865 */ 866 private String getVisibilityStatus() { 867 StringBuilder visibility = new StringBuilder(); 868 StringBuilder scans24GHz = new StringBuilder(); 869 StringBuilder scans5GHz = new StringBuilder(); 870 String bssid = null; 871 872 long now = System.currentTimeMillis(); 873 874 if (isActive() && mInfo != null) { 875 bssid = mInfo.getBSSID(); 876 if (bssid != null) { 877 visibility.append(" ").append(bssid); 878 } 879 visibility.append(" rssi=").append(mInfo.getRssi()); 880 visibility.append(" "); 881 visibility.append(" score=").append(mInfo.score); 882 if (mSpeed != Speed.NONE) { 883 visibility.append(" speed=").append(getSpeedLabel()); 884 } 885 visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate)); 886 visibility.append(String.format("%.1f,", mInfo.txRetriesRate)); 887 visibility.append(String.format("%.1f ", mInfo.txBadRate)); 888 visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate)); 889 } 890 891 int maxRssi5 = WifiConfiguration.INVALID_RSSI; 892 int maxRssi24 = WifiConfiguration.INVALID_RSSI; 893 final int maxDisplayedScans = 4; 894 int num5 = 0; // number of scanned BSSID on 5GHz band 895 int num24 = 0; // number of scanned BSSID on 2.4Ghz band 896 int numBlackListed = 0; 897 evictOldScanResults(); 898 899 // TODO: sort list by RSSI or age 900 for (ScanResult result : mScanResultCache.values()) { 901 if (result.frequency >= LOWER_FREQ_5GHZ 902 && result.frequency <= HIGHER_FREQ_5GHZ) { 903 // Strictly speaking: [4915, 5825] 904 num5++; 905 906 if (result.level > maxRssi5) { 907 maxRssi5 = result.level; 908 } 909 if (num5 <= maxDisplayedScans) { 910 scans5GHz.append(verboseScanResultSummary(result, bssid)); 911 } 912 } else if (result.frequency >= LOWER_FREQ_24GHZ 913 && result.frequency <= HIGHER_FREQ_24GHZ) { 914 // Strictly speaking: [2412, 2482] 915 num24++; 916 917 if (result.level > maxRssi24) { 918 maxRssi24 = result.level; 919 } 920 if (num24 <= maxDisplayedScans) { 921 scans24GHz.append(verboseScanResultSummary(result, bssid)); 922 } 923 } 924 } 925 visibility.append(" ["); 926 if (num24 > 0) { 927 visibility.append("(").append(num24).append(")"); 928 if (num24 > maxDisplayedScans) { 929 visibility.append("max=").append(maxRssi24).append(","); 930 } 931 visibility.append(scans24GHz.toString()); 932 } 933 visibility.append(";"); 934 if (num5 > 0) { 935 visibility.append("(").append(num5).append(")"); 936 if (num5 > maxDisplayedScans) { 937 visibility.append("max=").append(maxRssi5).append(","); 938 } 939 visibility.append(scans5GHz.toString()); 940 } 941 if (numBlackListed > 0) 942 visibility.append("!").append(numBlackListed); 943 visibility.append("]"); 944 945 return visibility.toString(); 946 } 947 948 @VisibleForTesting 949 /* package */ String verboseScanResultSummary(ScanResult result, String bssid) { 950 StringBuilder stringBuilder = new StringBuilder(); 951 stringBuilder.append(" \n{").append(result.BSSID); 952 if (result.BSSID.equals(bssid)) { 953 stringBuilder.append("*"); 954 } 955 stringBuilder.append("=").append(result.frequency); 956 stringBuilder.append(",").append(result.level); 957 if (hasSpeed(result)) { 958 stringBuilder.append(",") 959 .append(getSpeedLabel(mScanResultScores.get(result.BSSID))); 960 } 961 stringBuilder.append("}"); 962 return stringBuilder.toString(); 963 } 964 965 private boolean hasSpeed(ScanResult result) { 966 return mScanResultScores.containsKey(result.BSSID) 967 && mScanResultScores.get(result.BSSID) != Speed.NONE; 968 } 969 970 /** 971 * Return whether this is the active connection. 972 * For ephemeral connections (networkId is invalid), this returns false if the network is 973 * disconnected. 974 */ 975 public boolean isActive() { 976 return mNetworkInfo != null && 977 (networkId != WifiConfiguration.INVALID_NETWORK_ID || 978 mNetworkInfo.getState() != State.DISCONNECTED); 979 } 980 981 public boolean isConnectable() { 982 return getLevel() != -1 && getDetailedState() == null; 983 } 984 985 public boolean isEphemeral() { 986 return mInfo != null && mInfo.isEphemeral() && 987 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED; 988 } 989 990 /** 991 * Return true if this AccessPoint represents a Passpoint AP. 992 */ 993 public boolean isPasspoint() { 994 return mConfig != null && mConfig.isPasspoint(); 995 } 996 997 /** 998 * Return true if this AccessPoint represents a Passpoint provider configuration. 999 */ 1000 public boolean isPasspointConfig() { 1001 return mFqdn != null; 1002 } 1003 1004 /** 1005 * Return whether the given {@link WifiInfo} is for this access point. 1006 * If the current AP does not have a network Id then the config is used to 1007 * match based on SSID and security. 1008 */ 1009 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) { 1010 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) { 1011 return networkId == info.getNetworkId(); 1012 } else if (config != null) { 1013 return matches(config); 1014 } 1015 else { 1016 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID. 1017 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID). 1018 // TODO: Handle hex string SSIDs. 1019 return ssid.equals(removeDoubleQuotes(info.getSSID())); 1020 } 1021 } 1022 1023 public boolean isSaved() { 1024 return networkId != WifiConfiguration.INVALID_NETWORK_ID; 1025 } 1026 1027 public Object getTag() { 1028 return mTag; 1029 } 1030 1031 public void setTag(Object tag) { 1032 mTag = tag; 1033 } 1034 1035 /** 1036 * Generate and save a default wifiConfiguration with common values. 1037 * Can only be called for unsecured networks. 1038 */ 1039 public void generateOpenNetworkConfig() { 1040 if (security != SECURITY_NONE) 1041 throw new IllegalStateException(); 1042 if (mConfig != null) 1043 return; 1044 mConfig = new WifiConfiguration(); 1045 mConfig.SSID = AccessPoint.convertToQuotedString(ssid); 1046 mConfig.allowedKeyManagement.set(KeyMgmt.NONE); 1047 } 1048 1049 void loadConfig(WifiConfiguration config) { 1050 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID)); 1051 bssid = config.BSSID; 1052 security = getSecurity(config); 1053 networkId = config.networkId; 1054 mConfig = config; 1055 } 1056 1057 private void initWithScanResult(ScanResult result) { 1058 ssid = result.SSID; 1059 bssid = result.BSSID; 1060 security = getSecurity(result); 1061 if (security == SECURITY_PSK) 1062 pskType = getPskType(result); 1063 1064 mScanResultCache.put(result.BSSID, result); 1065 updateRssi(); 1066 mSeen = result.timestamp; // even if the timestamp is old it is still valid 1067 mIsCarrierAp = result.isCarrierAp; 1068 mCarrierApEapType = result.carrierApEapType; 1069 mCarrierName = result.carrierName; 1070 } 1071 1072 public void saveWifiState(Bundle savedState) { 1073 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr()); 1074 savedState.putInt(KEY_SECURITY, security); 1075 savedState.putInt(KEY_SPEED, mSpeed); 1076 savedState.putInt(KEY_PSKTYPE, pskType); 1077 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig); 1078 savedState.putParcelable(KEY_WIFIINFO, mInfo); 1079 evictOldScanResults(); 1080 savedState.putParcelableArrayList(KEY_SCANRESULTCACHE, 1081 new ArrayList<ScanResult>(mScanResultCache.values())); 1082 if (mNetworkInfo != null) { 1083 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo); 1084 } 1085 if (mFqdn != null) { 1086 savedState.putString(KEY_FQDN, mFqdn); 1087 } 1088 if (mProviderFriendlyName != null) { 1089 savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName); 1090 } 1091 savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp); 1092 savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType); 1093 savedState.putString(KEY_CARRIER_NAME, mCarrierName); 1094 } 1095 1096 public void setListener(AccessPointListener listener) { 1097 mAccessPointListener = listener; 1098 } 1099 1100 boolean update(ScanResult result) { 1101 if (matches(result)) { 1102 int oldLevel = getLevel(); 1103 1104 /* Add or update the scan result for the BSSID */ 1105 mScanResultCache.put(result.BSSID, result); 1106 updateSeen(); 1107 updateRssi(); 1108 int newLevel = getLevel(); 1109 1110 if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) { 1111 mAccessPointListener.onLevelChanged(this); 1112 } 1113 // This flag only comes from scans, is not easily saved in config 1114 if (security == SECURITY_PSK) { 1115 pskType = getPskType(result); 1116 } 1117 1118 if (mAccessPointListener != null) { 1119 mAccessPointListener.onAccessPointChanged(this); 1120 } 1121 1122 // The carrier info in the ScanResult is set by the platform based on the SSID and will 1123 // always be the same for all matching scan results. 1124 mIsCarrierAp = result.isCarrierAp; 1125 mCarrierApEapType = result.carrierApEapType; 1126 mCarrierName = result.carrierName; 1127 1128 return true; 1129 } 1130 return false; 1131 } 1132 1133 /** Attempt to update the AccessPoint and return true if an update occurred. */ 1134 public boolean update( 1135 @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) { 1136 boolean updated = false; 1137 final int oldLevel = getLevel(); 1138 if (info != null && isInfoForThisAccessPoint(config, info)) { 1139 updated = (mInfo == null); 1140 if (mConfig != config) { 1141 // We do not set updated = true as we do not want to increase the amount of sorting 1142 // and copying performed in WifiTracker at this time. If issues involving refresh 1143 // are still seen, we will investigate further. 1144 update(config); // Notifies the AccessPointListener of the change 1145 } 1146 if (mRssi != info.getRssi() && info.getRssi() != WifiInfo.INVALID_RSSI) { 1147 mRssi = info.getRssi(); 1148 updated = true; 1149 } else if (mNetworkInfo != null && networkInfo != null 1150 && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) { 1151 updated = true; 1152 } 1153 mInfo = info; 1154 mNetworkInfo = networkInfo; 1155 } else if (mInfo != null) { 1156 updated = true; 1157 mInfo = null; 1158 mNetworkInfo = null; 1159 } 1160 if (updated && mAccessPointListener != null) { 1161 mAccessPointListener.onAccessPointChanged(this); 1162 1163 if (oldLevel != getLevel() /* current level */) { 1164 mAccessPointListener.onLevelChanged(this); 1165 } 1166 } 1167 return updated; 1168 } 1169 1170 void update(@Nullable WifiConfiguration config) { 1171 mConfig = config; 1172 networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID; 1173 if (mAccessPointListener != null) { 1174 mAccessPointListener.onAccessPointChanged(this); 1175 } 1176 } 1177 1178 @VisibleForTesting 1179 void setRssi(int rssi) { 1180 mRssi = rssi; 1181 } 1182 1183 /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */ 1184 void setUnreachable() { 1185 setRssi(AccessPoint.UNREACHABLE_RSSI); 1186 } 1187 1188 int getSpeed() { return mSpeed;} 1189 1190 @Nullable 1191 String getSpeedLabel() { 1192 return getSpeedLabel(mSpeed); 1193 } 1194 1195 @Nullable 1196 private String getSpeedLabel(int speed) { 1197 switch (speed) { 1198 case Speed.VERY_FAST: 1199 return mContext.getString(R.string.speed_label_very_fast); 1200 case Speed.FAST: 1201 return mContext.getString(R.string.speed_label_fast); 1202 case Speed.MODERATE: 1203 return mContext.getString(R.string.speed_label_okay); 1204 case Speed.SLOW: 1205 return mContext.getString(R.string.speed_label_slow); 1206 case Speed.NONE: 1207 default: 1208 return null; 1209 } 1210 } 1211 1212 /** Return true if the current RSSI is reachable, and false otherwise. */ 1213 public boolean isReachable() { 1214 return mRssi != UNREACHABLE_RSSI; 1215 } 1216 1217 public static String getSummary(Context context, String ssid, DetailedState state, 1218 boolean isEphemeral, String passpointProvider) { 1219 if (state == DetailedState.CONNECTED && ssid == null) { 1220 if (TextUtils.isEmpty(passpointProvider) == false) { 1221 // Special case for connected + passpoint networks. 1222 String format = context.getString(R.string.connected_via_passpoint); 1223 return String.format(format, passpointProvider); 1224 } else if (isEphemeral) { 1225 // Special case for connected + ephemeral networks. 1226 final NetworkScoreManager networkScoreManager = context.getSystemService( 1227 NetworkScoreManager.class); 1228 NetworkScorerAppData scorer = networkScoreManager.getActiveScorer(); 1229 if (scorer != null && scorer.getRecommendationServiceLabel() != null) { 1230 String format = context.getString(R.string.connected_via_network_scorer); 1231 return String.format(format, scorer.getRecommendationServiceLabel()); 1232 } else { 1233 return context.getString(R.string.connected_via_network_scorer_default); 1234 } 1235 } 1236 } 1237 1238 // Case when there is wifi connected without internet connectivity. 1239 final ConnectivityManager cm = (ConnectivityManager) 1240 context.getSystemService(Context.CONNECTIVITY_SERVICE); 1241 if (state == DetailedState.CONNECTED) { 1242 IWifiManager wifiManager = IWifiManager.Stub.asInterface( 1243 ServiceManager.getService(Context.WIFI_SERVICE)); 1244 NetworkCapabilities nc = null; 1245 1246 try { 1247 nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork()); 1248 } catch (RemoteException e) {} 1249 1250 if (nc != null) { 1251 if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) { 1252 int id = context.getResources() 1253 .getIdentifier("network_available_sign_in", "string", "android"); 1254 return context.getString(id); 1255 } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) { 1256 return context.getString(R.string.wifi_connected_no_internet); 1257 } 1258 } 1259 } 1260 if (state == null) { 1261 Log.w(TAG, "state is null, returning empty summary"); 1262 return ""; 1263 } 1264 String[] formats = context.getResources().getStringArray((ssid == null) 1265 ? R.array.wifi_status : R.array.wifi_status_with_ssid); 1266 int index = state.ordinal(); 1267 1268 if (index >= formats.length || formats[index].length() == 0) { 1269 return ""; 1270 } 1271 return String.format(formats[index], ssid); 1272 } 1273 1274 public static String getSummary(Context context, DetailedState state, boolean isEphemeral) { 1275 return getSummary(context, null, state, isEphemeral, null); 1276 } 1277 1278 public static String getSummary(Context context, DetailedState state, boolean isEphemeral, 1279 String passpointProvider) { 1280 return getSummary(context, null, state, isEphemeral, passpointProvider); 1281 } 1282 1283 public static String convertToQuotedString(String string) { 1284 return "\"" + string + "\""; 1285 } 1286 1287 private static int getPskType(ScanResult result) { 1288 boolean wpa = result.capabilities.contains("WPA-PSK"); 1289 boolean wpa2 = result.capabilities.contains("WPA2-PSK"); 1290 if (wpa2 && wpa) { 1291 return PSK_WPA_WPA2; 1292 } else if (wpa2) { 1293 return PSK_WPA2; 1294 } else if (wpa) { 1295 return PSK_WPA; 1296 } else { 1297 Log.w(TAG, "Received abnormal flag string: " + result.capabilities); 1298 return PSK_UNKNOWN; 1299 } 1300 } 1301 1302 private static int getSecurity(ScanResult result) { 1303 if (result.capabilities.contains("WEP")) { 1304 return SECURITY_WEP; 1305 } else if (result.capabilities.contains("PSK")) { 1306 return SECURITY_PSK; 1307 } else if (result.capabilities.contains("EAP")) { 1308 return SECURITY_EAP; 1309 } 1310 return SECURITY_NONE; 1311 } 1312 1313 static int getSecurity(WifiConfiguration config) { 1314 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { 1315 return SECURITY_PSK; 1316 } 1317 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || 1318 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { 1319 return SECURITY_EAP; 1320 } 1321 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE; 1322 } 1323 1324 public static String securityToString(int security, int pskType) { 1325 if (security == SECURITY_WEP) { 1326 return "WEP"; 1327 } else if (security == SECURITY_PSK) { 1328 if (pskType == PSK_WPA) { 1329 return "WPA"; 1330 } else if (pskType == PSK_WPA2) { 1331 return "WPA2"; 1332 } else if (pskType == PSK_WPA_WPA2) { 1333 return "WPA_WPA2"; 1334 } 1335 return "PSK"; 1336 } else if (security == SECURITY_EAP) { 1337 return "EAP"; 1338 } 1339 return "NONE"; 1340 } 1341 1342 static String removeDoubleQuotes(String string) { 1343 if (TextUtils.isEmpty(string)) { 1344 return ""; 1345 } 1346 int length = string.length(); 1347 if ((length > 1) && (string.charAt(0) == '"') 1348 && (string.charAt(length - 1) == '"')) { 1349 return string.substring(1, length - 1); 1350 } 1351 return string; 1352 } 1353 1354 public interface AccessPointListener { 1355 void onAccessPointChanged(AccessPoint accessPoint); 1356 void onLevelChanged(AccessPoint accessPoint); 1357 } 1358} 1359