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