AccessPoint.java revision 64d02323df8a3effa5099743f3ea4ff1c9737058
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 = NetworkKey.createFromWifiInfo(mInfo); 458 ScoredNetwork score = scoreCache.getScoredNetwork(key); 459 if (score != null) { 460 mSpeed = score.calculateBadge(mInfo.getRssi()); 461 } 462 } 463 464 if(WifiTracker.sVerboseLogging) { 465 Log.i(TAG, String.format("%s: Set speed to %d", ssid, mSpeed)); 466 } 467 468 return oldSpeed != mSpeed; 469 } 470 471 /** 472 * Updates the AccessPoint's metering based on {@link ScoredNetwork#meteredHint}, returning 473 * true if the metering changed. 474 */ 475 private boolean updateMetered(WifiNetworkScoreCache scoreCache) { 476 boolean oldMetering = mIsScoredNetworkMetered; 477 mIsScoredNetworkMetered = false; 478 479 if (isActive() && mInfo != null) { 480 NetworkKey key = NetworkKey.createFromWifiInfo(mInfo); 481 ScoredNetwork score = scoreCache.getScoredNetwork(key); 482 if (score != null) { 483 mIsScoredNetworkMetered |= score.meteredHint; 484 } 485 } else { 486 for (ScanResult result : mScanResultCache.values()) { 487 ScoredNetwork score = scoreCache.getScoredNetwork(result); 488 if (score == null) { 489 continue; 490 } 491 mIsScoredNetworkMetered |= score.meteredHint; 492 } 493 } 494 return oldMetering == mIsScoredNetworkMetered; 495 } 496 497 private void evictOldScanResults() { 498 long nowMs = SystemClock.elapsedRealtime(); 499 for (Iterator<ScanResult> iter = mScanResultCache.values().iterator(); iter.hasNext(); ) { 500 ScanResult result = iter.next(); 501 // result timestamp is in microseconds 502 if (nowMs - result.timestamp / 1000 > MAX_SCAN_RESULT_AGE_MS) { 503 iter.remove(); 504 } 505 } 506 } 507 508 public boolean matches(ScanResult result) { 509 return ssid.equals(result.SSID) && security == getSecurity(result); 510 } 511 512 public boolean matches(WifiConfiguration config) { 513 if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) { 514 return ssid.equals(removeDoubleQuotes(config.SSID)) && config.FQDN.equals(mConfig.FQDN); 515 } else { 516 return ssid.equals(removeDoubleQuotes(config.SSID)) 517 && security == getSecurity(config) 518 && (mConfig == null || mConfig.shared == config.shared); 519 } 520 } 521 522 public WifiConfiguration getConfig() { 523 return mConfig; 524 } 525 526 public String getPasspointFqdn() { 527 return mFqdn; 528 } 529 530 public void clearConfig() { 531 mConfig = null; 532 networkId = WifiConfiguration.INVALID_NETWORK_ID; 533 } 534 535 public WifiInfo getInfo() { 536 return mInfo; 537 } 538 539 /** 540 * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1. 541 * 542 * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will 543 * always return at least 0. 544 */ 545 public int getLevel() { 546 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS); 547 } 548 549 public int getRssi() { 550 return mRssi; 551 } 552 553 /** 554 * Updates {@link #mRssi}. 555 * 556 * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned. 557 * If the given AccessPoint is not active, a value will be calculated from previous scan 558 * results, returning the best RSSI for all matching AccessPoints averaged with the previous 559 * value. If the access point is not connected and there are no scan results, the rssi will be 560 * set to {@link #UNREACHABLE_RSSI}. 561 */ 562 private void updateRssi() { 563 if (this.isActive()) { 564 return; 565 } 566 567 int rssi = UNREACHABLE_RSSI; 568 for (ScanResult result : mScanResultCache.values()) { 569 if (result.level > rssi) { 570 rssi = result.level; 571 } 572 } 573 574 if (rssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) { 575 mRssi = (mRssi + rssi) / 2; // half-life previous value 576 } else { 577 mRssi = rssi; 578 } 579 } 580 581 /** Updates {@link #mSeen} based on the scan result cache. */ 582 private void updateSeen() { 583 // TODO(sghuman): Set to now if connected 584 585 long seen = 0; 586 for (ScanResult result : mScanResultCache.values()) { 587 if (result.timestamp > seen) { 588 seen = result.timestamp; 589 } 590 } 591 592 // Only replace the previous value if we have a recent scan result to use 593 if (seen != 0) { 594 mSeen = seen; 595 } 596 } 597 598 /** 599 * Returns if the network should be considered metered. 600 */ 601 public boolean isMetered() { 602 return mIsScoredNetworkMetered 603 || WifiConfiguration.isMetered(mConfig, mInfo); 604 } 605 606 public NetworkInfo getNetworkInfo() { 607 return mNetworkInfo; 608 } 609 610 public int getSecurity() { 611 return security; 612 } 613 614 public String getSecurityString(boolean concise) { 615 Context context = mContext; 616 if (isPasspoint() || isPasspointConfig()) { 617 return concise ? context.getString(R.string.wifi_security_short_eap) : 618 context.getString(R.string.wifi_security_eap); 619 } 620 switch(security) { 621 case SECURITY_EAP: 622 return concise ? context.getString(R.string.wifi_security_short_eap) : 623 context.getString(R.string.wifi_security_eap); 624 case SECURITY_PSK: 625 switch (pskType) { 626 case PSK_WPA: 627 return concise ? context.getString(R.string.wifi_security_short_wpa) : 628 context.getString(R.string.wifi_security_wpa); 629 case PSK_WPA2: 630 return concise ? context.getString(R.string.wifi_security_short_wpa2) : 631 context.getString(R.string.wifi_security_wpa2); 632 case PSK_WPA_WPA2: 633 return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) : 634 context.getString(R.string.wifi_security_wpa_wpa2); 635 case PSK_UNKNOWN: 636 default: 637 return concise ? context.getString(R.string.wifi_security_short_psk_generic) 638 : context.getString(R.string.wifi_security_psk_generic); 639 } 640 case SECURITY_WEP: 641 return concise ? context.getString(R.string.wifi_security_short_wep) : 642 context.getString(R.string.wifi_security_wep); 643 case SECURITY_NONE: 644 default: 645 return concise ? "" : context.getString(R.string.wifi_security_none); 646 } 647 } 648 649 public String getSsidStr() { 650 return ssid; 651 } 652 653 public String getBssid() { 654 return bssid; 655 } 656 657 public CharSequence getSsid() { 658 final SpannableString str = new SpannableString(ssid); 659 str.setSpan(new TtsSpan.TelephoneBuilder(ssid).build(), 0, ssid.length(), 660 Spannable.SPAN_INCLUSIVE_INCLUSIVE); 661 return str; 662 } 663 664 public String getConfigName() { 665 if (mConfig != null && mConfig.isPasspoint()) { 666 return mConfig.providerFriendlyName; 667 } else if (mFqdn != null) { 668 return mProviderFriendlyName; 669 } else { 670 return ssid; 671 } 672 } 673 674 public DetailedState getDetailedState() { 675 if (mNetworkInfo != null) { 676 return mNetworkInfo.getDetailedState(); 677 } 678 Log.w(TAG, "NetworkInfo is null, cannot return detailed state"); 679 return null; 680 } 681 682 public boolean isCarrierAp() { 683 return mIsCarrierAp; 684 } 685 686 public int getCarrierApEapType() { 687 return mCarrierApEapType; 688 } 689 690 public String getCarrierName() { 691 return mCarrierName; 692 } 693 694 public String getSavedNetworkSummary() { 695 WifiConfiguration config = mConfig; 696 if (config != null) { 697 PackageManager pm = mContext.getPackageManager(); 698 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID); 699 int userId = UserHandle.getUserId(config.creatorUid); 700 ApplicationInfo appInfo = null; 701 if (config.creatorName != null && config.creatorName.equals(systemName)) { 702 appInfo = mContext.getApplicationInfo(); 703 } else { 704 try { 705 IPackageManager ipm = AppGlobals.getPackageManager(); 706 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId); 707 } catch (RemoteException rex) { 708 } 709 } 710 if (appInfo != null && 711 !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) && 712 !appInfo.packageName.equals( 713 mContext.getString(R.string.certinstaller_package))) { 714 return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm)); 715 } 716 } 717 return ""; 718 } 719 720 public String getSummary() { 721 return getSettingsSummary(mConfig); 722 } 723 724 public String getSettingsSummary() { 725 return getSettingsSummary(mConfig); 726 } 727 728 private String getSettingsSummary(WifiConfiguration config) { 729 // Update to new summary 730 StringBuilder summary = new StringBuilder(); 731 732 if (isActive() && config != null && config.isPasspoint()) { 733 // This is the active connection on passpoint 734 summary.append(getSummary(mContext, getDetailedState(), 735 false, config.providerFriendlyName)); 736 } else if (isActive() && config != null && getDetailedState() == DetailedState.CONNECTED 737 && mIsCarrierAp) { 738 summary.append(String.format(mContext.getString(R.string.connected_via_carrier), mCarrierName)); 739 } else if (isActive()) { 740 // This is the active connection on non-passpoint network 741 summary.append(getSummary(mContext, getDetailedState(), 742 mInfo != null && mInfo.isEphemeral())); 743 } else if (config != null && config.isPasspoint() 744 && config.getNetworkSelectionStatus().isNetworkEnabled()) { 745 String format = mContext.getString(R.string.available_via_passpoint); 746 summary.append(String.format(format, config.providerFriendlyName)); 747 } else if (config != null && config.hasNoInternetAccess()) { 748 int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled() 749 ? R.string.wifi_no_internet_no_reconnect 750 : R.string.wifi_no_internet; 751 summary.append(mContext.getString(messageID)); 752 } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) { 753 WifiConfiguration.NetworkSelectionStatus networkStatus = 754 config.getNetworkSelectionStatus(); 755 switch (networkStatus.getNetworkSelectionDisableReason()) { 756 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE: 757 summary.append(mContext.getString(R.string.wifi_disabled_password_failure)); 758 break; 759 case WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD: 760 summary.append(mContext.getString(R.string.wifi_check_password_try_again)); 761 break; 762 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE: 763 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE: 764 summary.append(mContext.getString(R.string.wifi_disabled_network_failure)); 765 break; 766 case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION: 767 summary.append(mContext.getString(R.string.wifi_disabled_generic)); 768 break; 769 } 770 } else if (config != null && config.getNetworkSelectionStatus().isNotRecommended()) { 771 summary.append(mContext.getString(R.string.wifi_disabled_by_recommendation_provider)); 772 } else if (mIsCarrierAp) { 773 summary.append(String.format(mContext.getString(R.string.available_via_carrier), mCarrierName)); 774 } else if (!isReachable()) { // Wifi out of range 775 summary.append(mContext.getString(R.string.wifi_not_in_range)); 776 } else { // In range, not disabled. 777 if (config != null) { // Is saved network 778 // Last attempt to connect to this failed. Show reason why 779 switch (config.recentFailure.getAssociationStatus()) { 780 case WifiConfiguration.RecentFailure.STATUS_AP_UNABLE_TO_HANDLE_NEW_STA: 781 summary.append(mContext.getString( 782 R.string.wifi_ap_unable_to_handle_new_sta)); 783 break; 784 default: 785 // "Saved" 786 summary.append(mContext.getString(R.string.wifi_remembered)); 787 break; 788 } 789 } 790 } 791 792 if (WifiTracker.sVerboseLogging) { 793 // Add RSSI/band information for this config, what was seen up to 6 seconds ago 794 // verbose WiFi Logging is only turned on thru developers settings 795 if (isActive() && mInfo != null) { 796 summary.append(" f=" + Integer.toString(mInfo.getFrequency())); 797 } 798 summary.append(" " + getVisibilityStatus()); 799 if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) { 800 summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString()); 801 if (config.getNetworkSelectionStatus().getDisableTime() > 0) { 802 long now = System.currentTimeMillis(); 803 long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000; 804 long sec = diff%60; //seconds 805 long min = (diff/60)%60; //minutes 806 long hour = (min/60)%60; //hours 807 summary.append(", "); 808 if (hour > 0) summary.append(Long.toString(hour) + "h "); 809 summary.append( Long.toString(min) + "m "); 810 summary.append( Long.toString(sec) + "s "); 811 } 812 summary.append(")"); 813 } 814 815 if (config != null) { 816 WifiConfiguration.NetworkSelectionStatus networkStatus = 817 config.getNetworkSelectionStatus(); 818 for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE; 819 index < WifiConfiguration.NetworkSelectionStatus 820 .NETWORK_SELECTION_DISABLED_MAX; index++) { 821 if (networkStatus.getDisableReasonCounter(index) != 0) { 822 summary.append(" " + WifiConfiguration.NetworkSelectionStatus 823 .getNetworkDisableReasonString(index) + "=" 824 + networkStatus.getDisableReasonCounter(index)); 825 } 826 } 827 } 828 } 829 830 // If Speed label and summary are both present, use the preference combination to combine 831 // the two, else return the non-null one. 832 if (getSpeedLabel() != null && summary.length() != 0) { 833 return mContext.getResources().getString( 834 R.string.preference_summary_default_combination, 835 getSpeedLabel(), 836 summary.toString()); 837 } else if (getSpeedLabel() != null) { 838 return getSpeedLabel(); 839 } else { 840 return summary.toString(); 841 } 842 } 843 844 /** 845 * Returns the visibility status of the WifiConfiguration. 846 * 847 * @return autojoin debugging information 848 * TODO: use a string formatter 849 * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"] 850 * For instance [-40,5/-30,2] 851 */ 852 private String getVisibilityStatus() { 853 StringBuilder visibility = new StringBuilder(); 854 StringBuilder scans24GHz = new StringBuilder(); 855 StringBuilder scans5GHz = new StringBuilder(); 856 String bssid = null; 857 858 long now = System.currentTimeMillis(); 859 860 if (isActive() && mInfo != null) { 861 bssid = mInfo.getBSSID(); 862 if (bssid != null) { 863 visibility.append(" ").append(bssid); 864 } 865 visibility.append(" rssi=").append(mInfo.getRssi()); 866 visibility.append(" "); 867 visibility.append(" score=").append(mInfo.score); 868 if (mSpeed != Speed.NONE) { 869 visibility.append(" speed=").append(getSpeedLabel()); 870 } 871 visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate)); 872 visibility.append(String.format("%.1f,", mInfo.txRetriesRate)); 873 visibility.append(String.format("%.1f ", mInfo.txBadRate)); 874 visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate)); 875 } 876 877 int maxRssi5 = WifiConfiguration.INVALID_RSSI; 878 int maxRssi24 = WifiConfiguration.INVALID_RSSI; 879 final int maxDisplayedScans = 4; 880 int num5 = 0; // number of scanned BSSID on 5GHz band 881 int num24 = 0; // number of scanned BSSID on 2.4Ghz band 882 int numBlackListed = 0; 883 evictOldScanResults(); 884 885 // TODO: sort list by RSSI or age 886 for (ScanResult result : mScanResultCache.values()) { 887 if (result.frequency >= LOWER_FREQ_5GHZ 888 && result.frequency <= HIGHER_FREQ_5GHZ) { 889 // Strictly speaking: [4915, 5825] 890 num5++; 891 892 if (result.level > maxRssi5) { 893 maxRssi5 = result.level; 894 } 895 if (num5 <= maxDisplayedScans) { 896 scans5GHz.append(verboseScanResultSummary(result, bssid)); 897 } 898 } else if (result.frequency >= LOWER_FREQ_24GHZ 899 && result.frequency <= HIGHER_FREQ_24GHZ) { 900 // Strictly speaking: [2412, 2482] 901 num24++; 902 903 if (result.level > maxRssi24) { 904 maxRssi24 = result.level; 905 } 906 if (num24 <= maxDisplayedScans) { 907 scans24GHz.append(verboseScanResultSummary(result, bssid)); 908 } 909 } 910 } 911 visibility.append(" ["); 912 if (num24 > 0) { 913 visibility.append("(").append(num24).append(")"); 914 if (num24 > maxDisplayedScans) { 915 visibility.append("max=").append(maxRssi24).append(","); 916 } 917 visibility.append(scans24GHz.toString()); 918 } 919 visibility.append(";"); 920 if (num5 > 0) { 921 visibility.append("(").append(num5).append(")"); 922 if (num5 > maxDisplayedScans) { 923 visibility.append("max=").append(maxRssi5).append(","); 924 } 925 visibility.append(scans5GHz.toString()); 926 } 927 if (numBlackListed > 0) 928 visibility.append("!").append(numBlackListed); 929 visibility.append("]"); 930 931 return visibility.toString(); 932 } 933 934 @VisibleForTesting 935 /* package */ String verboseScanResultSummary(ScanResult result, String bssid) { 936 StringBuilder stringBuilder = new StringBuilder(); 937 stringBuilder.append(" \n{").append(result.BSSID); 938 if (result.BSSID.equals(bssid)) { 939 stringBuilder.append("*"); 940 } 941 stringBuilder.append("=").append(result.frequency); 942 stringBuilder.append(",").append(result.level); 943 if (hasSpeed(result)) { 944 stringBuilder.append(",") 945 .append(getSpeedLabel(mScanResultScores.get(result.BSSID))); 946 } 947 stringBuilder.append("}"); 948 return stringBuilder.toString(); 949 } 950 951 private boolean hasSpeed(ScanResult result) { 952 return mScanResultScores.containsKey(result.BSSID) 953 && mScanResultScores.get(result.BSSID) != Speed.NONE; 954 } 955 956 /** 957 * Return whether this is the active connection. 958 * For ephemeral connections (networkId is invalid), this returns false if the network is 959 * disconnected. 960 */ 961 public boolean isActive() { 962 return mNetworkInfo != null && 963 (networkId != WifiConfiguration.INVALID_NETWORK_ID || 964 mNetworkInfo.getState() != State.DISCONNECTED); 965 } 966 967 public boolean isConnectable() { 968 return getLevel() != -1 && getDetailedState() == null; 969 } 970 971 public boolean isEphemeral() { 972 return mInfo != null && mInfo.isEphemeral() && 973 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED; 974 } 975 976 /** 977 * Return true if this AccessPoint represents a Passpoint AP. 978 */ 979 public boolean isPasspoint() { 980 return mConfig != null && mConfig.isPasspoint(); 981 } 982 983 /** 984 * Return true if this AccessPoint represents a Passpoint provider configuration. 985 */ 986 public boolean isPasspointConfig() { 987 return mFqdn != null; 988 } 989 990 /** 991 * Return whether the given {@link WifiInfo} is for this access point. 992 * If the current AP does not have a network Id then the config is used to 993 * match based on SSID and security. 994 */ 995 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) { 996 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) { 997 return networkId == info.getNetworkId(); 998 } else if (config != null) { 999 return matches(config); 1000 } 1001 else { 1002 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID. 1003 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID). 1004 // TODO: Handle hex string SSIDs. 1005 return ssid.equals(removeDoubleQuotes(info.getSSID())); 1006 } 1007 } 1008 1009 public boolean isSaved() { 1010 return networkId != WifiConfiguration.INVALID_NETWORK_ID; 1011 } 1012 1013 public Object getTag() { 1014 return mTag; 1015 } 1016 1017 public void setTag(Object tag) { 1018 mTag = tag; 1019 } 1020 1021 /** 1022 * Generate and save a default wifiConfiguration with common values. 1023 * Can only be called for unsecured networks. 1024 */ 1025 public void generateOpenNetworkConfig() { 1026 if (security != SECURITY_NONE) 1027 throw new IllegalStateException(); 1028 if (mConfig != null) 1029 return; 1030 mConfig = new WifiConfiguration(); 1031 mConfig.SSID = AccessPoint.convertToQuotedString(ssid); 1032 mConfig.allowedKeyManagement.set(KeyMgmt.NONE); 1033 } 1034 1035 void loadConfig(WifiConfiguration config) { 1036 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID)); 1037 bssid = config.BSSID; 1038 security = getSecurity(config); 1039 networkId = config.networkId; 1040 mConfig = config; 1041 } 1042 1043 private void initWithScanResult(ScanResult result) { 1044 ssid = result.SSID; 1045 bssid = result.BSSID; 1046 security = getSecurity(result); 1047 if (security == SECURITY_PSK) 1048 pskType = getPskType(result); 1049 1050 mScanResultCache.put(result.BSSID, result); 1051 updateRssi(); 1052 mSeen = result.timestamp; // even if the timestamp is old it is still valid 1053 mIsCarrierAp = result.isCarrierAp; 1054 mCarrierApEapType = result.carrierApEapType; 1055 mCarrierName = result.carrierName; 1056 } 1057 1058 public void saveWifiState(Bundle savedState) { 1059 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr()); 1060 savedState.putInt(KEY_SECURITY, security); 1061 savedState.putInt(KEY_SPEED, mSpeed); 1062 savedState.putInt(KEY_PSKTYPE, pskType); 1063 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig); 1064 savedState.putParcelable(KEY_WIFIINFO, mInfo); 1065 evictOldScanResults(); 1066 savedState.putParcelableArrayList(KEY_SCANRESULTCACHE, 1067 new ArrayList<ScanResult>(mScanResultCache.values())); 1068 if (mNetworkInfo != null) { 1069 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo); 1070 } 1071 if (mFqdn != null) { 1072 savedState.putString(KEY_FQDN, mFqdn); 1073 } 1074 if (mProviderFriendlyName != null) { 1075 savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName); 1076 } 1077 savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp); 1078 savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType); 1079 savedState.putString(KEY_CARRIER_NAME, mCarrierName); 1080 } 1081 1082 public void setListener(AccessPointListener listener) { 1083 mAccessPointListener = listener; 1084 } 1085 1086 /** 1087 * Update the AP with the given scan result. 1088 * 1089 * @param result the ScanResult to add to the AccessPoint scan cache 1090 * @param evictOldScanResults whether stale scan results should be removed 1091 * from the cache during this update process 1092 * @return true if the scan result update caused a change in state which would impact ranking 1093 * or AccessPoint rendering (e.g. wifi level, security) 1094 */ 1095 boolean update(ScanResult result, boolean evictOldScanResults) { 1096 if (matches(result)) { 1097 int oldLevel = getLevel(); 1098 1099 /* Add or update the scan result for the BSSID */ 1100 mScanResultCache.put(result.BSSID, result); 1101 if (evictOldScanResults) evictOldScanResults(); 1102 updateSeen(); 1103 updateRssi(); 1104 int newLevel = getLevel(); 1105 1106 if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) { 1107 mAccessPointListener.onLevelChanged(this); 1108 } 1109 // This flag only comes from scans, is not easily saved in config 1110 if (security == SECURITY_PSK) { 1111 pskType = getPskType(result); 1112 } 1113 1114 if (mAccessPointListener != null) { 1115 mAccessPointListener.onAccessPointChanged(this); 1116 } 1117 1118 // The carrier info in the ScanResult is set by the platform based on the SSID and will 1119 // always be the same for all matching scan results. 1120 mIsCarrierAp = result.isCarrierAp; 1121 mCarrierApEapType = result.carrierApEapType; 1122 mCarrierName = result.carrierName; 1123 1124 return true; 1125 } 1126 return false; 1127 } 1128 1129 /** Attempt to update the AccessPoint and return true if an update occurred. */ 1130 public boolean update( 1131 @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) { 1132 boolean updated = false; 1133 final int oldLevel = getLevel(); 1134 if (info != null && isInfoForThisAccessPoint(config, info)) { 1135 updated = (mInfo == null); 1136 if (mConfig != config) { 1137 // We do not set updated = true as we do not want to increase the amount of sorting 1138 // and copying performed in WifiTracker at this time. If issues involving refresh 1139 // are still seen, we will investigate further. 1140 update(config); // Notifies the AccessPointListener of the change 1141 } 1142 if (mRssi != info.getRssi() && info.getRssi() != WifiInfo.INVALID_RSSI) { 1143 mRssi = info.getRssi(); 1144 updated = true; 1145 } else if (mNetworkInfo != null && networkInfo != null 1146 && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) { 1147 updated = true; 1148 } 1149 mInfo = info; 1150 mNetworkInfo = networkInfo; 1151 } else if (mInfo != null) { 1152 updated = true; 1153 mInfo = null; 1154 mNetworkInfo = null; 1155 } 1156 if (updated && mAccessPointListener != null) { 1157 mAccessPointListener.onAccessPointChanged(this); 1158 1159 if (oldLevel != getLevel() /* current level */) { 1160 mAccessPointListener.onLevelChanged(this); 1161 } 1162 } 1163 return updated; 1164 } 1165 1166 void update(@Nullable WifiConfiguration config) { 1167 mConfig = config; 1168 networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID; 1169 if (mAccessPointListener != null) { 1170 mAccessPointListener.onAccessPointChanged(this); 1171 } 1172 } 1173 1174 @VisibleForTesting 1175 void setRssi(int rssi) { 1176 mRssi = rssi; 1177 } 1178 1179 /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */ 1180 void setUnreachable() { 1181 setRssi(AccessPoint.UNREACHABLE_RSSI); 1182 } 1183 1184 int getSpeed() { return mSpeed;} 1185 1186 @Nullable 1187 String getSpeedLabel() { 1188 return getSpeedLabel(mSpeed); 1189 } 1190 1191 @Nullable 1192 private String getSpeedLabel(int speed) { 1193 switch (speed) { 1194 case Speed.VERY_FAST: 1195 return mContext.getString(R.string.speed_label_very_fast); 1196 case Speed.FAST: 1197 return mContext.getString(R.string.speed_label_fast); 1198 case Speed.MODERATE: 1199 return mContext.getString(R.string.speed_label_okay); 1200 case Speed.SLOW: 1201 return mContext.getString(R.string.speed_label_slow); 1202 case Speed.NONE: 1203 default: 1204 return null; 1205 } 1206 } 1207 1208 /** Return true if the current RSSI is reachable, and false otherwise. */ 1209 public boolean isReachable() { 1210 return mRssi != UNREACHABLE_RSSI; 1211 } 1212 1213 public static String getSummary(Context context, String ssid, DetailedState state, 1214 boolean isEphemeral, String passpointProvider) { 1215 if (state == DetailedState.CONNECTED && ssid == null) { 1216 if (TextUtils.isEmpty(passpointProvider) == false) { 1217 // Special case for connected + passpoint networks. 1218 String format = context.getString(R.string.connected_via_passpoint); 1219 return String.format(format, passpointProvider); 1220 } else if (isEphemeral) { 1221 // Special case for connected + ephemeral networks. 1222 final NetworkScoreManager networkScoreManager = context.getSystemService( 1223 NetworkScoreManager.class); 1224 NetworkScorerAppData scorer = networkScoreManager.getActiveScorer(); 1225 if (scorer != null && scorer.getRecommendationServiceLabel() != null) { 1226 String format = context.getString(R.string.connected_via_network_scorer); 1227 return String.format(format, scorer.getRecommendationServiceLabel()); 1228 } else { 1229 return context.getString(R.string.connected_via_network_scorer_default); 1230 } 1231 } 1232 } 1233 1234 // Case when there is wifi connected without internet connectivity. 1235 final ConnectivityManager cm = (ConnectivityManager) 1236 context.getSystemService(Context.CONNECTIVITY_SERVICE); 1237 if (state == DetailedState.CONNECTED) { 1238 IWifiManager wifiManager = IWifiManager.Stub.asInterface( 1239 ServiceManager.getService(Context.WIFI_SERVICE)); 1240 NetworkCapabilities nc = null; 1241 1242 try { 1243 nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork()); 1244 } catch (RemoteException e) {} 1245 1246 if (nc != null) { 1247 if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) { 1248 int id = context.getResources() 1249 .getIdentifier("network_available_sign_in", "string", "android"); 1250 return context.getString(id); 1251 } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) { 1252 return context.getString(R.string.wifi_connected_no_internet); 1253 } 1254 } 1255 } 1256 if (state == null) { 1257 Log.w(TAG, "state is null, returning empty summary"); 1258 return ""; 1259 } 1260 String[] formats = context.getResources().getStringArray((ssid == null) 1261 ? R.array.wifi_status : R.array.wifi_status_with_ssid); 1262 int index = state.ordinal(); 1263 1264 if (index >= formats.length || formats[index].length() == 0) { 1265 return ""; 1266 } 1267 return String.format(formats[index], ssid); 1268 } 1269 1270 public static String getSummary(Context context, DetailedState state, boolean isEphemeral) { 1271 return getSummary(context, null, state, isEphemeral, null); 1272 } 1273 1274 public static String getSummary(Context context, DetailedState state, boolean isEphemeral, 1275 String passpointProvider) { 1276 return getSummary(context, null, state, isEphemeral, passpointProvider); 1277 } 1278 1279 public static String convertToQuotedString(String string) { 1280 return "\"" + string + "\""; 1281 } 1282 1283 private static int getPskType(ScanResult result) { 1284 boolean wpa = result.capabilities.contains("WPA-PSK"); 1285 boolean wpa2 = result.capabilities.contains("WPA2-PSK"); 1286 if (wpa2 && wpa) { 1287 return PSK_WPA_WPA2; 1288 } else if (wpa2) { 1289 return PSK_WPA2; 1290 } else if (wpa) { 1291 return PSK_WPA; 1292 } else { 1293 Log.w(TAG, "Received abnormal flag string: " + result.capabilities); 1294 return PSK_UNKNOWN; 1295 } 1296 } 1297 1298 private static int getSecurity(ScanResult result) { 1299 if (result.capabilities.contains("WEP")) { 1300 return SECURITY_WEP; 1301 } else if (result.capabilities.contains("PSK")) { 1302 return SECURITY_PSK; 1303 } else if (result.capabilities.contains("EAP")) { 1304 return SECURITY_EAP; 1305 } 1306 return SECURITY_NONE; 1307 } 1308 1309 static int getSecurity(WifiConfiguration config) { 1310 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { 1311 return SECURITY_PSK; 1312 } 1313 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || 1314 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { 1315 return SECURITY_EAP; 1316 } 1317 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE; 1318 } 1319 1320 public static String securityToString(int security, int pskType) { 1321 if (security == SECURITY_WEP) { 1322 return "WEP"; 1323 } else if (security == SECURITY_PSK) { 1324 if (pskType == PSK_WPA) { 1325 return "WPA"; 1326 } else if (pskType == PSK_WPA2) { 1327 return "WPA2"; 1328 } else if (pskType == PSK_WPA_WPA2) { 1329 return "WPA_WPA2"; 1330 } 1331 return "PSK"; 1332 } else if (security == SECURITY_EAP) { 1333 return "EAP"; 1334 } 1335 return "NONE"; 1336 } 1337 1338 static String removeDoubleQuotes(String string) { 1339 if (TextUtils.isEmpty(string)) { 1340 return ""; 1341 } 1342 int length = string.length(); 1343 if ((length > 1) && (string.charAt(0) == '"') 1344 && (string.charAt(length - 1) == '"')) { 1345 return string.substring(1, length - 1); 1346 } 1347 return string; 1348 } 1349 1350 public interface AccessPointListener { 1351 void onAccessPointChanged(AccessPoint accessPoint); 1352 void onLevelChanged(AccessPoint accessPoint); 1353 } 1354} 1355