AccessPoint.java revision d1e449267a68220e84c45065ed0d6eb8fe393ed0
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 258 // Do not evict old scan results on initial creation 259 updateRssi(); 260 updateSeen(); 261 mId = sLastId.incrementAndGet(); 262 } 263 264 public AccessPoint(Context context, WifiConfiguration config) { 265 mContext = context; 266 loadConfig(config); 267 mId = sLastId.incrementAndGet(); 268 } 269 270 /** 271 * Initialize an AccessPoint object for a {@link PasspointConfiguration}. This is mainly 272 * used by "Saved Networks" page for managing the saved {@link PasspointConfiguration}. 273 */ 274 public AccessPoint(Context context, PasspointConfiguration config) { 275 mContext = context; 276 mFqdn = config.getHomeSp().getFqdn(); 277 mProviderFriendlyName = config.getHomeSp().getFriendlyName(); 278 mId = sLastId.incrementAndGet(); 279 } 280 281 AccessPoint(Context context, AccessPoint other) { 282 mContext = context; 283 copyFrom(other); 284 } 285 286 AccessPoint(Context context, ScanResult result) { 287 mContext = context; 288 initWithScanResult(result); 289 mId = sLastId.incrementAndGet(); 290 } 291 292 /** 293 * Copy accesspoint information. NOTE: We do not copy tag information because that is never 294 * set on the internal copy. 295 * @param that 296 */ 297 void copyFrom(AccessPoint that) { 298 that.evictOldScanResults(); 299 this.ssid = that.ssid; 300 this.bssid = that.bssid; 301 this.security = that.security; 302 this.networkId = that.networkId; 303 this.pskType = that.pskType; 304 this.mConfig = that.mConfig; //TODO: Watch out, this object is mutated. 305 this.mRssi = that.mRssi; 306 this.mSeen = that.mSeen; 307 this.mInfo = that.mInfo; 308 this.mNetworkInfo = that.mNetworkInfo; 309 this.mScanResultCache.clear(); 310 this.mScanResultCache.putAll(that.mScanResultCache); 311 this.mScanResultScores.clear(); 312 this.mScanResultScores.putAll(that.mScanResultScores); 313 this.mId = that.mId; 314 this.mSpeed = that.mSpeed; 315 this.mIsScoredNetworkMetered = that.mIsScoredNetworkMetered; 316 this.mIsCarrierAp = that.mIsCarrierAp; 317 this.mCarrierApEapType = that.mCarrierApEapType; 318 this.mCarrierName = that.mCarrierName; 319 } 320 321 /** 322 * Returns a negative integer, zero, or a positive integer if this AccessPoint is less than, 323 * equal to, or greater than the other AccessPoint. 324 * 325 * Sort order rules for AccessPoints: 326 * 1. Active before inactive 327 * 2. Reachable before unreachable 328 * 3. Saved before unsaved 329 * 4. Network speed value 330 * 5. Stronger signal before weaker signal 331 * 6. SSID alphabetically 332 * 333 * Note that AccessPoints with a signal are usually also Reachable, 334 * and will thus appear before unreachable saved AccessPoints. 335 */ 336 @Override 337 public int compareTo(@NonNull AccessPoint other) { 338 // Active one goes first. 339 if (isActive() && !other.isActive()) return -1; 340 if (!isActive() && other.isActive()) return 1; 341 342 // Reachable one goes before unreachable one. 343 if (isReachable() && !other.isReachable()) return -1; 344 if (!isReachable() && other.isReachable()) return 1; 345 346 // Configured (saved) one goes before unconfigured one. 347 if (isSaved() && !other.isSaved()) return -1; 348 if (!isSaved() && other.isSaved()) return 1; 349 350 // Faster speeds go before slower speeds 351 if (getSpeed() != other.getSpeed()) { 352 return other.getSpeed() - getSpeed(); 353 } 354 355 // Sort by signal strength, bucketed by level 356 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS) 357 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS); 358 if (difference != 0) { 359 return difference; 360 } 361 362 // Sort by ssid. 363 difference = getSsidStr().compareToIgnoreCase(other.getSsidStr()); 364 if (difference != 0) { 365 return difference; 366 } 367 368 // Do a case sensitive comparison to distinguish SSIDs that differ in case only 369 return getSsidStr().compareTo(other.getSsidStr()); 370 } 371 372 @Override 373 public boolean equals(Object other) { 374 if (!(other instanceof AccessPoint)) return false; 375 return (this.compareTo((AccessPoint) other) == 0); 376 } 377 378 @Override 379 public int hashCode() { 380 int result = 0; 381 if (mInfo != null) result += 13 * mInfo.hashCode(); 382 result += 19 * mRssi; 383 result += 23 * networkId; 384 result += 29 * ssid.hashCode(); 385 return result; 386 } 387 388 @Override 389 public String toString() { 390 StringBuilder builder = new StringBuilder().append("AccessPoint(") 391 .append(ssid); 392 if (bssid != null) { 393 builder.append(":").append(bssid); 394 } 395 if (isSaved()) { 396 builder.append(',').append("saved"); 397 } 398 if (isActive()) { 399 builder.append(',').append("active"); 400 } 401 if (isEphemeral()) { 402 builder.append(',').append("ephemeral"); 403 } 404 if (isConnectable()) { 405 builder.append(',').append("connectable"); 406 } 407 if (security != SECURITY_NONE) { 408 builder.append(',').append(securityToString(security, pskType)); 409 } 410 builder.append(",level=").append(getLevel()); 411 if (mSpeed != Speed.NONE) { 412 builder.append(",speed=").append(mSpeed); 413 } 414 builder.append(",metered=").append(isMetered()); 415 416 return builder.append(')').toString(); 417 } 418 419 /** 420 * Updates the AccessPoint rankingScore, metering, and speed, returning true if the data has 421 * changed. 422 * 423 * @param scoreCache The score cache to use to retrieve scores. 424 * @param scoringUiEnabled Whether to show scoring and badging UI. 425 */ 426 boolean update(WifiNetworkScoreCache scoreCache, boolean scoringUiEnabled) { 427 boolean scoreChanged = false; 428 mScanResultScores.clear(); 429 if (scoringUiEnabled) { 430 scoreChanged = updateScores(scoreCache); 431 } 432 return updateMetered(scoreCache) || scoreChanged; 433 } 434 435 /** 436 * Updates the AccessPoint rankingScore and speed, returning true if the data has changed. 437 * 438 * @param scoreCache The score cache to use to retrieve scores. 439 */ 440 private boolean updateScores(WifiNetworkScoreCache scoreCache) { 441 int oldSpeed = mSpeed; 442 mSpeed = Speed.NONE; 443 444 for (ScanResult result : mScanResultCache.values()) { 445 ScoredNetwork score = scoreCache.getScoredNetwork(result); 446 if (score == null) { 447 continue; 448 } 449 450 int speed = score.calculateBadge(result.level); 451 mScanResultScores.put(result.BSSID, speed); 452 mSpeed = Math.max(mSpeed, speed); 453 } 454 455 // set mSpeed to the connected ScanResult if the AccessPoint is the active network 456 if (isActive() && mInfo != null) { 457 NetworkKey key = new NetworkKey(new WifiKey( 458 AccessPoint.convertToQuotedString(ssid), mInfo.getBSSID())); 459 ScoredNetwork score = scoreCache.getScoredNetwork(key); 460 if (score != null) { 461 mSpeed = score.calculateBadge(mInfo.getRssi()); 462 } 463 } 464 465 if(WifiTracker.sVerboseLogging) { 466 Log.i(TAG, String.format("%s: Set speed to %d", ssid, mSpeed)); 467 } 468 469 return oldSpeed != mSpeed; 470 } 471 472 /** 473 * Updates the AccessPoint's metering based on {@link ScoredNetwork#meteredHint}, returning 474 * true if the metering changed. 475 */ 476 private boolean updateMetered(WifiNetworkScoreCache scoreCache) { 477 boolean oldMetering = mIsScoredNetworkMetered; 478 mIsScoredNetworkMetered = false; 479 480 if (isActive() && mInfo != null) { 481 NetworkKey key = new NetworkKey(new WifiKey( 482 AccessPoint.convertToQuotedString(ssid), mInfo.getBSSID())); 483 ScoredNetwork score = scoreCache.getScoredNetwork(key); 484 if (score != null) { 485 mIsScoredNetworkMetered |= score.meteredHint; 486 } 487 } else { 488 for (ScanResult result : mScanResultCache.values()) { 489 ScoredNetwork score = scoreCache.getScoredNetwork(result); 490 if (score == null) { 491 continue; 492 } 493 mIsScoredNetworkMetered |= score.meteredHint; 494 } 495 } 496 return oldMetering == mIsScoredNetworkMetered; 497 } 498 499 private void evictOldScanResults() { 500 long nowMs = SystemClock.elapsedRealtime(); 501 for (Iterator<ScanResult> iter = mScanResultCache.values().iterator(); iter.hasNext(); ) { 502 ScanResult result = iter.next(); 503 // result timestamp is in microseconds 504 if (nowMs - result.timestamp / 1000 > MAX_SCAN_RESULT_AGE_MS) { 505 iter.remove(); 506 } 507 } 508 } 509 510 public boolean matches(ScanResult result) { 511 return ssid.equals(result.SSID) && security == getSecurity(result); 512 } 513 514 public boolean matches(WifiConfiguration config) { 515 if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) { 516 return ssid.equals(removeDoubleQuotes(config.SSID)) && config.FQDN.equals(mConfig.FQDN); 517 } else { 518 return ssid.equals(removeDoubleQuotes(config.SSID)) 519 && security == getSecurity(config) 520 && (mConfig == null || mConfig.shared == config.shared); 521 } 522 } 523 524 public WifiConfiguration getConfig() { 525 return mConfig; 526 } 527 528 public String getPasspointFqdn() { 529 return mFqdn; 530 } 531 532 public void clearConfig() { 533 mConfig = null; 534 networkId = WifiConfiguration.INVALID_NETWORK_ID; 535 } 536 537 public WifiInfo getInfo() { 538 return mInfo; 539 } 540 541 /** 542 * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1. 543 * 544 * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will 545 * always return at least 0. 546 */ 547 public int getLevel() { 548 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS); 549 } 550 551 public int getRssi() { 552 return mRssi; 553 } 554 555 /** 556 * Updates {@link #mRssi}. 557 * 558 * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned. 559 * If the given AccessPoint is not active, a value will be calculated from previous scan 560 * results, returning the best RSSI for all matching AccessPoints averaged with the previous 561 * value. If the access point is not connected and there are no scan results, the rssi will be 562 * set to {@link #UNREACHABLE_RSSI}. 563 */ 564 private void updateRssi() { 565 if (this.isActive()) { 566 return; 567 } 568 569 int rssi = UNREACHABLE_RSSI; 570 for (ScanResult result : mScanResultCache.values()) { 571 if (result.level > rssi) { 572 rssi = result.level; 573 } 574 } 575 576 if (rssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) { 577 mRssi = (mRssi + rssi) / 2; // half-life previous value 578 } else { 579 mRssi = rssi; 580 } 581 } 582 583 /** Updates {@link #mSeen} based on the scan result cache. */ 584 private void updateSeen() { 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 (isPasspoint() || isPasspointConfig()) { 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 = new StringBuilder(); 857 StringBuilder scans5GHz = new StringBuilder(); 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 maxRssi5 = WifiConfiguration.INVALID_RSSI; 880 int maxRssi24 = WifiConfiguration.INVALID_RSSI; 881 final int maxDisplayedScans = 4; 882 int num5 = 0; // number of scanned BSSID on 5GHz band 883 int num24 = 0; // number of scanned BSSID on 2.4Ghz band 884 int numBlackListed = 0; 885 evictOldScanResults(); 886 887 // TODO: sort list by RSSI or age 888 for (ScanResult result : mScanResultCache.values()) { 889 if (result.frequency >= LOWER_FREQ_5GHZ 890 && result.frequency <= HIGHER_FREQ_5GHZ) { 891 // Strictly speaking: [4915, 5825] 892 num5++; 893 894 if (result.level > maxRssi5) { 895 maxRssi5 = result.level; 896 } 897 if (num5 <= maxDisplayedScans) { 898 scans5GHz.append(verboseScanResultSummary(result, bssid)); 899 } 900 } else if (result.frequency >= LOWER_FREQ_24GHZ 901 && result.frequency <= HIGHER_FREQ_24GHZ) { 902 // Strictly speaking: [2412, 2482] 903 num24++; 904 905 if (result.level > maxRssi24) { 906 maxRssi24 = result.level; 907 } 908 if (num24 <= maxDisplayedScans) { 909 scans24GHz.append(verboseScanResultSummary(result, bssid)); 910 } 911 } 912 } 913 visibility.append(" ["); 914 if (num24 > 0) { 915 visibility.append("(").append(num24).append(")"); 916 if (num24 > maxDisplayedScans) { 917 visibility.append("max=").append(maxRssi24).append(","); 918 } 919 visibility.append(scans24GHz.toString()); 920 } 921 visibility.append(";"); 922 if (num5 > 0) { 923 visibility.append("(").append(num5).append(")"); 924 if (num5 > maxDisplayedScans) { 925 visibility.append("max=").append(maxRssi5).append(","); 926 } 927 visibility.append(scans5GHz.toString()); 928 } 929 if (numBlackListed > 0) 930 visibility.append("!").append(numBlackListed); 931 visibility.append("]"); 932 933 return visibility.toString(); 934 } 935 936 @VisibleForTesting 937 /* package */ String verboseScanResultSummary(ScanResult result, String bssid) { 938 StringBuilder stringBuilder = new StringBuilder(); 939 stringBuilder.append(" \n{").append(result.BSSID); 940 if (result.BSSID.equals(bssid)) { 941 stringBuilder.append("*"); 942 } 943 stringBuilder.append("=").append(result.frequency); 944 stringBuilder.append(",").append(result.level); 945 if (hasSpeed(result)) { 946 stringBuilder.append(",") 947 .append(getSpeedLabel(mScanResultScores.get(result.BSSID))); 948 } 949 stringBuilder.append("}"); 950 return stringBuilder.toString(); 951 } 952 953 private boolean hasSpeed(ScanResult result) { 954 return mScanResultScores.containsKey(result.BSSID) 955 && mScanResultScores.get(result.BSSID) != Speed.NONE; 956 } 957 958 /** 959 * Return whether this is the active connection. 960 * For ephemeral connections (networkId is invalid), this returns false if the network is 961 * disconnected. 962 */ 963 public boolean isActive() { 964 return mNetworkInfo != null && 965 (networkId != WifiConfiguration.INVALID_NETWORK_ID || 966 mNetworkInfo.getState() != State.DISCONNECTED); 967 } 968 969 public boolean isConnectable() { 970 return getLevel() != -1 && getDetailedState() == null; 971 } 972 973 public boolean isEphemeral() { 974 return mInfo != null && mInfo.isEphemeral() && 975 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED; 976 } 977 978 /** 979 * Return true if this AccessPoint represents a Passpoint AP. 980 */ 981 public boolean isPasspoint() { 982 return mConfig != null && mConfig.isPasspoint(); 983 } 984 985 /** 986 * Return true if this AccessPoint represents a Passpoint provider configuration. 987 */ 988 public boolean isPasspointConfig() { 989 return mFqdn != null; 990 } 991 992 /** 993 * Return whether the given {@link WifiInfo} is for this access point. 994 * If the current AP does not have a network Id then the config is used to 995 * match based on SSID and security. 996 */ 997 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) { 998 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) { 999 return networkId == info.getNetworkId(); 1000 } else if (config != null) { 1001 return matches(config); 1002 } 1003 else { 1004 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID. 1005 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID). 1006 // TODO: Handle hex string SSIDs. 1007 return ssid.equals(removeDoubleQuotes(info.getSSID())); 1008 } 1009 } 1010 1011 public boolean isSaved() { 1012 return networkId != WifiConfiguration.INVALID_NETWORK_ID; 1013 } 1014 1015 public Object getTag() { 1016 return mTag; 1017 } 1018 1019 public void setTag(Object tag) { 1020 mTag = tag; 1021 } 1022 1023 /** 1024 * Generate and save a default wifiConfiguration with common values. 1025 * Can only be called for unsecured networks. 1026 */ 1027 public void generateOpenNetworkConfig() { 1028 if (security != SECURITY_NONE) 1029 throw new IllegalStateException(); 1030 if (mConfig != null) 1031 return; 1032 mConfig = new WifiConfiguration(); 1033 mConfig.SSID = AccessPoint.convertToQuotedString(ssid); 1034 mConfig.allowedKeyManagement.set(KeyMgmt.NONE); 1035 } 1036 1037 void loadConfig(WifiConfiguration config) { 1038 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID)); 1039 bssid = config.BSSID; 1040 security = getSecurity(config); 1041 networkId = config.networkId; 1042 mConfig = config; 1043 } 1044 1045 private void initWithScanResult(ScanResult result) { 1046 ssid = result.SSID; 1047 bssid = result.BSSID; 1048 security = getSecurity(result); 1049 if (security == SECURITY_PSK) 1050 pskType = getPskType(result); 1051 1052 mScanResultCache.put(result.BSSID, result); 1053 updateRssi(); 1054 mSeen = result.timestamp; // even if the timestamp is old it is still valid 1055 mIsCarrierAp = result.isCarrierAp; 1056 mCarrierApEapType = result.carrierApEapType; 1057 mCarrierName = result.carrierName; 1058 } 1059 1060 public void saveWifiState(Bundle savedState) { 1061 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr()); 1062 savedState.putInt(KEY_SECURITY, security); 1063 savedState.putInt(KEY_SPEED, mSpeed); 1064 savedState.putInt(KEY_PSKTYPE, pskType); 1065 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig); 1066 savedState.putParcelable(KEY_WIFIINFO, mInfo); 1067 evictOldScanResults(); 1068 savedState.putParcelableArrayList(KEY_SCANRESULTCACHE, 1069 new ArrayList<ScanResult>(mScanResultCache.values())); 1070 if (mNetworkInfo != null) { 1071 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo); 1072 } 1073 if (mFqdn != null) { 1074 savedState.putString(KEY_FQDN, mFqdn); 1075 } 1076 if (mProviderFriendlyName != null) { 1077 savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName); 1078 } 1079 savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp); 1080 savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType); 1081 savedState.putString(KEY_CARRIER_NAME, mCarrierName); 1082 } 1083 1084 public void setListener(AccessPointListener listener) { 1085 mAccessPointListener = listener; 1086 } 1087 1088 /** 1089 * Update the AP with the given scan result. 1090 * 1091 * @param result the ScanResult to add to the AccessPoint scan cache 1092 * @param evictOldScanResults whether stale scan results should be removed 1093 * from the cache during this update process 1094 * @return true if the scan result update caused a change in state which would impact ranking 1095 * or AccessPoint rendering (e.g. wifi level, security) 1096 */ 1097 boolean update(ScanResult result, boolean evictOldScanResults) { 1098 if (matches(result)) { 1099 int oldLevel = getLevel(); 1100 1101 /* Add or update the scan result for the BSSID */ 1102 mScanResultCache.put(result.BSSID, result); 1103 if (evictOldScanResults) evictOldScanResults(); 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 return getSpeedLabel(mSpeed); 1191 } 1192 1193 @Nullable 1194 private String getSpeedLabel(int speed) { 1195 switch (speed) { 1196 case Speed.VERY_FAST: 1197 return mContext.getString(R.string.speed_label_very_fast); 1198 case Speed.FAST: 1199 return mContext.getString(R.string.speed_label_fast); 1200 case Speed.MODERATE: 1201 return mContext.getString(R.string.speed_label_okay); 1202 case Speed.SLOW: 1203 return mContext.getString(R.string.speed_label_slow); 1204 case Speed.NONE: 1205 default: 1206 return null; 1207 } 1208 } 1209 1210 /** Return true if the current RSSI is reachable, and false otherwise. */ 1211 public boolean isReachable() { 1212 return mRssi != UNREACHABLE_RSSI; 1213 } 1214 1215 public static String getSummary(Context context, String ssid, DetailedState state, 1216 boolean isEphemeral, String passpointProvider) { 1217 if (state == DetailedState.CONNECTED && ssid == null) { 1218 if (TextUtils.isEmpty(passpointProvider) == false) { 1219 // Special case for connected + passpoint networks. 1220 String format = context.getString(R.string.connected_via_passpoint); 1221 return String.format(format, passpointProvider); 1222 } else if (isEphemeral) { 1223 // Special case for connected + ephemeral networks. 1224 final NetworkScoreManager networkScoreManager = context.getSystemService( 1225 NetworkScoreManager.class); 1226 NetworkScorerAppData scorer = networkScoreManager.getActiveScorer(); 1227 if (scorer != null && scorer.getRecommendationServiceLabel() != null) { 1228 String format = context.getString(R.string.connected_via_network_scorer); 1229 return String.format(format, scorer.getRecommendationServiceLabel()); 1230 } else { 1231 return context.getString(R.string.connected_via_network_scorer_default); 1232 } 1233 } 1234 } 1235 1236 // Case when there is wifi connected without internet connectivity. 1237 final ConnectivityManager cm = (ConnectivityManager) 1238 context.getSystemService(Context.CONNECTIVITY_SERVICE); 1239 if (state == DetailedState.CONNECTED) { 1240 IWifiManager wifiManager = IWifiManager.Stub.asInterface( 1241 ServiceManager.getService(Context.WIFI_SERVICE)); 1242 NetworkCapabilities nc = null; 1243 1244 try { 1245 nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork()); 1246 } catch (RemoteException e) {} 1247 1248 if (nc != null) { 1249 if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) { 1250 int id = context.getResources() 1251 .getIdentifier("network_available_sign_in", "string", "android"); 1252 return context.getString(id); 1253 } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) { 1254 return context.getString(R.string.wifi_connected_no_internet); 1255 } 1256 } 1257 } 1258 if (state == null) { 1259 Log.w(TAG, "state is null, returning empty summary"); 1260 return ""; 1261 } 1262 String[] formats = context.getResources().getStringArray((ssid == null) 1263 ? R.array.wifi_status : R.array.wifi_status_with_ssid); 1264 int index = state.ordinal(); 1265 1266 if (index >= formats.length || formats[index].length() == 0) { 1267 return ""; 1268 } 1269 return String.format(formats[index], ssid); 1270 } 1271 1272 public static String getSummary(Context context, DetailedState state, boolean isEphemeral) { 1273 return getSummary(context, null, state, isEphemeral, null); 1274 } 1275 1276 public static String getSummary(Context context, DetailedState state, boolean isEphemeral, 1277 String passpointProvider) { 1278 return getSummary(context, null, state, isEphemeral, passpointProvider); 1279 } 1280 1281 public static String convertToQuotedString(String string) { 1282 return "\"" + string + "\""; 1283 } 1284 1285 private static int getPskType(ScanResult result) { 1286 boolean wpa = result.capabilities.contains("WPA-PSK"); 1287 boolean wpa2 = result.capabilities.contains("WPA2-PSK"); 1288 if (wpa2 && wpa) { 1289 return PSK_WPA_WPA2; 1290 } else if (wpa2) { 1291 return PSK_WPA2; 1292 } else if (wpa) { 1293 return PSK_WPA; 1294 } else { 1295 Log.w(TAG, "Received abnormal flag string: " + result.capabilities); 1296 return PSK_UNKNOWN; 1297 } 1298 } 1299 1300 private static int getSecurity(ScanResult result) { 1301 if (result.capabilities.contains("WEP")) { 1302 return SECURITY_WEP; 1303 } else if (result.capabilities.contains("PSK")) { 1304 return SECURITY_PSK; 1305 } else if (result.capabilities.contains("EAP")) { 1306 return SECURITY_EAP; 1307 } 1308 return SECURITY_NONE; 1309 } 1310 1311 static int getSecurity(WifiConfiguration config) { 1312 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { 1313 return SECURITY_PSK; 1314 } 1315 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || 1316 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { 1317 return SECURITY_EAP; 1318 } 1319 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE; 1320 } 1321 1322 public static String securityToString(int security, int pskType) { 1323 if (security == SECURITY_WEP) { 1324 return "WEP"; 1325 } else if (security == SECURITY_PSK) { 1326 if (pskType == PSK_WPA) { 1327 return "WPA"; 1328 } else if (pskType == PSK_WPA2) { 1329 return "WPA2"; 1330 } else if (pskType == PSK_WPA_WPA2) { 1331 return "WPA_WPA2"; 1332 } 1333 return "PSK"; 1334 } else if (security == SECURITY_EAP) { 1335 return "EAP"; 1336 } 1337 return "NONE"; 1338 } 1339 1340 static String removeDoubleQuotes(String string) { 1341 if (TextUtils.isEmpty(string)) { 1342 return ""; 1343 } 1344 int length = string.length(); 1345 if ((length > 1) && (string.charAt(0) == '"') 1346 && (string.charAt(length - 1) == '"')) { 1347 return string.substring(1, length - 1); 1348 } 1349 return string; 1350 } 1351 1352 public interface AccessPointListener { 1353 void onAccessPointChanged(AccessPoint accessPoint); 1354 void onLevelChanged(AccessPoint accessPoint); 1355 } 1356} 1357