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