AccessPoint.java revision 51365c3b4c1dc6575882bfe6285bdf3598cac5d2
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.app.AppGlobals; 20import android.content.Context; 21import android.content.pm.ApplicationInfo; 22import android.content.pm.IPackageManager; 23import android.content.pm.PackageManager; 24import android.net.ConnectivityManager; 25import android.net.Network; 26import android.net.NetworkCapabilities; 27import android.net.NetworkInfo; 28import android.net.NetworkInfo.DetailedState; 29import android.net.NetworkInfo.State; 30import android.net.wifi.IWifiManager; 31import android.net.wifi.ScanResult; 32import android.net.wifi.WifiConfiguration; 33import android.net.wifi.WifiConfiguration.KeyMgmt; 34import android.net.wifi.WifiInfo; 35import android.net.wifi.WifiManager; 36import android.os.Bundle; 37import android.os.RemoteException; 38import android.os.ServiceManager; 39import android.os.UserHandle; 40import android.support.annotation.NonNull; 41import android.text.Spannable; 42import android.text.SpannableString; 43import android.text.TextUtils; 44import android.text.style.TtsSpan; 45import android.util.Log; 46import android.util.LruCache; 47 48import com.android.settingslib.R; 49 50import java.util.ArrayList; 51import java.util.Map; 52 53 54public class AccessPoint implements Comparable<AccessPoint> { 55 static final String TAG = "SettingsLib.AccessPoint"; 56 57 /** 58 * Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels 59 */ 60 public static final int LOWER_FREQ_24GHZ = 2400; 61 62 /** 63 * Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels 64 */ 65 public static final int HIGHER_FREQ_24GHZ = 2500; 66 67 /** 68 * Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels 69 */ 70 public static final int LOWER_FREQ_5GHZ = 4900; 71 72 /** 73 * Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels 74 */ 75 public static final int HIGHER_FREQ_5GHZ = 5900; 76 77 78 /** 79 * Experimental: we should be able to show the user the list of BSSIDs and bands 80 * for that SSID. 81 * For now this data is used only with Verbose Logging so as to show the band and number 82 * of BSSIDs on which that network is seen. 83 */ 84 public LruCache<String, ScanResult> mScanResultCache = new LruCache<String, ScanResult>(32); 85 86 private static final String KEY_NETWORKINFO = "key_networkinfo"; 87 private static final String KEY_WIFIINFO = "key_wifiinfo"; 88 private static final String KEY_SCANRESULT = "key_scanresult"; 89 private static final String KEY_SSID = "key_ssid"; 90 private static final String KEY_SECURITY = "key_security"; 91 private static final String KEY_PSKTYPE = "key_psktype"; 92 private static final String KEY_SCANRESULTCACHE = "key_scanresultcache"; 93 private static final String KEY_CONFIG = "key_config"; 94 95 /** 96 * These values are matched in string arrays -- changes must be kept in sync 97 */ 98 public static final int SECURITY_NONE = 0; 99 public static final int SECURITY_WEP = 1; 100 public static final int SECURITY_PSK = 2; 101 public static final int SECURITY_EAP = 3; 102 103 private static final int PSK_UNKNOWN = 0; 104 private static final int PSK_WPA = 1; 105 private static final int PSK_WPA2 = 2; 106 private static final int PSK_WPA_WPA2 = 3; 107 108 public static final int SIGNAL_LEVELS = 4; 109 110 private final Context mContext; 111 112 private String ssid; 113 private String bssid; 114 private int security; 115 private int networkId = WifiConfiguration.INVALID_NETWORK_ID; 116 117 private int pskType = PSK_UNKNOWN; 118 119 private WifiConfiguration mConfig; 120 121 private int mRssi = Integer.MAX_VALUE; 122 private long mSeen = 0; 123 124 private WifiInfo mInfo; 125 private NetworkInfo mNetworkInfo; 126 private AccessPointListener mAccessPointListener; 127 128 private Object mTag; 129 130 public AccessPoint(Context context, Bundle savedState) { 131 mContext = context; 132 mConfig = savedState.getParcelable(KEY_CONFIG); 133 if (mConfig != null) { 134 loadConfig(mConfig); 135 } 136 if (savedState.containsKey(KEY_SSID)) { 137 ssid = savedState.getString(KEY_SSID); 138 } 139 if (savedState.containsKey(KEY_SECURITY)) { 140 security = savedState.getInt(KEY_SECURITY); 141 } 142 if (savedState.containsKey(KEY_PSKTYPE)) { 143 pskType = savedState.getInt(KEY_PSKTYPE); 144 } 145 mInfo = (WifiInfo) savedState.getParcelable(KEY_WIFIINFO); 146 if (savedState.containsKey(KEY_NETWORKINFO)) { 147 mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO); 148 } 149 if (savedState.containsKey(KEY_SCANRESULTCACHE)) { 150 ArrayList<ScanResult> scanResultArrayList = 151 savedState.getParcelableArrayList(KEY_SCANRESULTCACHE); 152 mScanResultCache.evictAll(); 153 for (ScanResult result : scanResultArrayList) { 154 mScanResultCache.put(result.BSSID, result); 155 } 156 } 157 update(mConfig, mInfo, mNetworkInfo); 158 mRssi = getRssi(); 159 mSeen = getSeen(); 160 } 161 162 AccessPoint(Context context, ScanResult result) { 163 mContext = context; 164 initWithScanResult(result); 165 } 166 167 AccessPoint(Context context, WifiConfiguration config) { 168 mContext = context; 169 loadConfig(config); 170 } 171 172 @Override 173 public int compareTo(@NonNull AccessPoint other) { 174 // Active one goes first. 175 if (isActive() && !other.isActive()) return -1; 176 if (!isActive() && other.isActive()) return 1; 177 178 // Reachable one goes before unreachable one. 179 if (mRssi != Integer.MAX_VALUE && other.mRssi == Integer.MAX_VALUE) return -1; 180 if (mRssi == Integer.MAX_VALUE && other.mRssi != Integer.MAX_VALUE) return 1; 181 182 // Configured one goes before unconfigured one. 183 if (networkId != WifiConfiguration.INVALID_NETWORK_ID 184 && other.networkId == WifiConfiguration.INVALID_NETWORK_ID) return -1; 185 if (networkId == WifiConfiguration.INVALID_NETWORK_ID 186 && other.networkId != WifiConfiguration.INVALID_NETWORK_ID) return 1; 187 188 // Sort by signal strength, bucketed by level 189 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS) 190 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS); 191 if (difference != 0) { 192 return difference; 193 } 194 // Sort by ssid. 195 return ssid.compareToIgnoreCase(other.ssid); 196 } 197 198 @Override 199 public boolean equals(Object other) { 200 if (!(other instanceof AccessPoint)) return false; 201 return (this.compareTo((AccessPoint) other) == 0); 202 } 203 204 @Override 205 public int hashCode() { 206 int result = 0; 207 if (mInfo != null) result += 13 * mInfo.hashCode(); 208 result += 19 * mRssi; 209 result += 23 * networkId; 210 result += 29 * ssid.hashCode(); 211 return result; 212 } 213 214 @Override 215 public String toString() { 216 StringBuilder builder = new StringBuilder().append("AccessPoint(") 217 .append(ssid); 218 if (isSaved()) { 219 builder.append(',').append("saved"); 220 } 221 if (isActive()) { 222 builder.append(',').append("active"); 223 } 224 if (isEphemeral()) { 225 builder.append(',').append("ephemeral"); 226 } 227 if (isConnectable()) { 228 builder.append(',').append("connectable"); 229 } 230 if (security != SECURITY_NONE) { 231 builder.append(',').append(securityToString(security, pskType)); 232 } 233 return builder.append(')').toString(); 234 } 235 236 public boolean matches(ScanResult result) { 237 return ssid.equals(result.SSID) && security == getSecurity(result); 238 } 239 240 public boolean matches(WifiConfiguration config) { 241 if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) { 242 return config.FQDN.equals(mConfig.providerFriendlyName); 243 } else { 244 return ssid.equals(removeDoubleQuotes(config.SSID)) 245 && security == getSecurity(config) 246 && (mConfig == null || mConfig.shared == config.shared); 247 } 248 } 249 250 public WifiConfiguration getConfig() { 251 return mConfig; 252 } 253 254 public void clearConfig() { 255 mConfig = null; 256 networkId = WifiConfiguration.INVALID_NETWORK_ID; 257 } 258 259 public WifiInfo getInfo() { 260 return mInfo; 261 } 262 263 public int getLevel() { 264 if (mRssi == Integer.MAX_VALUE) { 265 return -1; 266 } 267 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS); 268 } 269 270 public int getRssi() { 271 int rssi = Integer.MIN_VALUE; 272 for (ScanResult result : mScanResultCache.snapshot().values()) { 273 if (result.level > rssi) { 274 rssi = result.level; 275 } 276 } 277 278 return rssi; 279 } 280 281 public long getSeen() { 282 long seen = 0; 283 for (ScanResult result : mScanResultCache.snapshot().values()) { 284 if (result.timestamp > seen) { 285 seen = result.timestamp; 286 } 287 } 288 289 return seen; 290 } 291 292 public NetworkInfo getNetworkInfo() { 293 return mNetworkInfo; 294 } 295 296 public int getSecurity() { 297 return security; 298 } 299 300 public String getSecurityString(boolean concise) { 301 Context context = mContext; 302 if (mConfig != null && mConfig.isPasspoint()) { 303 return concise ? context.getString(R.string.wifi_security_short_eap) : 304 context.getString(R.string.wifi_security_eap); 305 } 306 switch(security) { 307 case SECURITY_EAP: 308 return concise ? context.getString(R.string.wifi_security_short_eap) : 309 context.getString(R.string.wifi_security_eap); 310 case SECURITY_PSK: 311 switch (pskType) { 312 case PSK_WPA: 313 return concise ? context.getString(R.string.wifi_security_short_wpa) : 314 context.getString(R.string.wifi_security_wpa); 315 case PSK_WPA2: 316 return concise ? context.getString(R.string.wifi_security_short_wpa2) : 317 context.getString(R.string.wifi_security_wpa2); 318 case PSK_WPA_WPA2: 319 return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) : 320 context.getString(R.string.wifi_security_wpa_wpa2); 321 case PSK_UNKNOWN: 322 default: 323 return concise ? context.getString(R.string.wifi_security_short_psk_generic) 324 : context.getString(R.string.wifi_security_psk_generic); 325 } 326 case SECURITY_WEP: 327 return concise ? context.getString(R.string.wifi_security_short_wep) : 328 context.getString(R.string.wifi_security_wep); 329 case SECURITY_NONE: 330 default: 331 return concise ? "" : context.getString(R.string.wifi_security_none); 332 } 333 } 334 335 public String getSsidStr() { 336 return ssid; 337 } 338 339 public String getBssid() { 340 return bssid; 341 } 342 343 public CharSequence getSsid() { 344 SpannableString str = new SpannableString(ssid); 345 str.setSpan(new TtsSpan.VerbatimBuilder(ssid).build(), 0, ssid.length(), 346 Spannable.SPAN_INCLUSIVE_INCLUSIVE); 347 return str; 348 } 349 350 public String getConfigName() { 351 if (mConfig != null && mConfig.isPasspoint()) { 352 return mConfig.providerFriendlyName; 353 } else { 354 return ssid; 355 } 356 } 357 358 public DetailedState getDetailedState() { 359 return mNetworkInfo != null ? mNetworkInfo.getDetailedState() : null; 360 } 361 362 public String getSavedNetworkSummary() { 363 WifiConfiguration config = mConfig; 364 if (config != null) { 365 PackageManager pm = mContext.getPackageManager(); 366 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID); 367 int userId = UserHandle.getUserId(config.creatorUid); 368 ApplicationInfo appInfo = null; 369 if (config.creatorName != null && config.creatorName.equals(systemName)) { 370 appInfo = mContext.getApplicationInfo(); 371 } else { 372 try { 373 IPackageManager ipm = AppGlobals.getPackageManager(); 374 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId); 375 } catch (RemoteException rex) { 376 } 377 } 378 if (appInfo != null && 379 !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) && 380 !appInfo.packageName.equals( 381 mContext.getString(R.string.certinstaller_package))) { 382 return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm)); 383 } 384 } 385 return ""; 386 } 387 388 public String getSummary() { 389 return getSettingsSummary(mConfig); 390 } 391 392 public String getSettingsSummary() { 393 return getSettingsSummary(mConfig); 394 } 395 396 private String getSettingsSummary(WifiConfiguration config) { 397 // Update to new summary 398 StringBuilder summary = new StringBuilder(); 399 400 if (isActive() && config != null && config.isPasspoint()) { 401 // This is the active connection on passpoint 402 summary.append(getSummary(mContext, getDetailedState(), 403 false, config.providerFriendlyName)); 404 } else if (isActive()) { 405 // This is the active connection on non-passpoint network 406 summary.append(getSummary(mContext, getDetailedState(), 407 mInfo != null && mInfo.isEphemeral())); 408 } else if (config != null && config.isPasspoint()) { 409 String format = mContext.getString(R.string.available_via_passpoint); 410 summary.append(String.format(format, config.providerFriendlyName)); 411 } else if (config != null && config.hasNoInternetAccess()) { 412 summary.append(mContext.getString(R.string.wifi_no_internet)); 413 } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) { 414 WifiConfiguration.NetworkSelectionStatus networkStatus = 415 config.getNetworkSelectionStatus(); 416 switch (networkStatus.getNetworkSelectionDisableReason()) { 417 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE: 418 summary.append(mContext.getString(R.string.wifi_disabled_password_failure)); 419 break; 420 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE: 421 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE: 422 summary.append(mContext.getString(R.string.wifi_disabled_network_failure)); 423 break; 424 case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION: 425 summary.append(mContext.getString(R.string.wifi_disabled_generic)); 426 break; 427 } 428 } else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range 429 summary.append(mContext.getString(R.string.wifi_not_in_range)); 430 } else { // In range, not disabled. 431 if (config != null) { // Is saved network 432 summary.append(mContext.getString(R.string.wifi_remembered)); 433 } 434 } 435 436 if (WifiTracker.sVerboseLogging > 0) { 437 // Add RSSI/band information for this config, what was seen up to 6 seconds ago 438 // verbose WiFi Logging is only turned on thru developers settings 439 if (mInfo != null && mNetworkInfo != null) { // This is the active connection 440 summary.append(" f=" + Integer.toString(mInfo.getFrequency())); 441 } 442 summary.append(" " + getVisibilityStatus()); 443 if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) { 444 summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString()); 445 if (config.getNetworkSelectionStatus().getDisableTime() > 0) { 446 long now = System.currentTimeMillis(); 447 long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000; 448 long sec = diff%60; //seconds 449 long min = (diff/60)%60; //minutes 450 long hour = (min/60)%60; //hours 451 summary.append(", "); 452 if (hour > 0) summary.append(Long.toString(hour) + "h "); 453 summary.append( Long.toString(min) + "m "); 454 summary.append( Long.toString(sec) + "s "); 455 } 456 summary.append(")"); 457 } 458 459 if (config != null) { 460 WifiConfiguration.NetworkSelectionStatus networkStatus = 461 config.getNetworkSelectionStatus(); 462 for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE; 463 index < WifiConfiguration.NetworkSelectionStatus 464 .NETWORK_SELECTION_DISABLED_MAX; index++) { 465 if (networkStatus.getDisableReasonCounter(index) != 0) { 466 summary.append(" " + WifiConfiguration.NetworkSelectionStatus 467 .getNetworkDisableReasonString(index) + "=" 468 + networkStatus.getDisableReasonCounter(index)); 469 } 470 } 471 } 472 } 473 return summary.toString(); 474 } 475 476 /** 477 * Returns the visibility status of the WifiConfiguration. 478 * 479 * @return autojoin debugging information 480 * TODO: use a string formatter 481 * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"] 482 * For instance [-40,5/-30,2] 483 */ 484 private String getVisibilityStatus() { 485 StringBuilder visibility = new StringBuilder(); 486 StringBuilder scans24GHz = null; 487 StringBuilder scans5GHz = null; 488 String bssid = null; 489 490 long now = System.currentTimeMillis(); 491 492 if (mInfo != null) { 493 bssid = mInfo.getBSSID(); 494 if (bssid != null) { 495 visibility.append(" ").append(bssid); 496 } 497 visibility.append(" rssi=").append(mInfo.getRssi()); 498 visibility.append(" "); 499 visibility.append(" score=").append(mInfo.score); 500 visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate)); 501 visibility.append(String.format("%.1f,", mInfo.txRetriesRate)); 502 visibility.append(String.format("%.1f ", mInfo.txBadRate)); 503 visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate)); 504 } 505 506 int rssi5 = WifiConfiguration.INVALID_RSSI; 507 int rssi24 = WifiConfiguration.INVALID_RSSI; 508 int num5 = 0; 509 int num24 = 0; 510 int numBlackListed = 0; 511 int n24 = 0; // Number scan results we included in the string 512 int n5 = 0; // Number scan results we included in the string 513 Map<String, ScanResult> list = mScanResultCache.snapshot(); 514 // TODO: sort list by RSSI or age 515 for (ScanResult result : list.values()) { 516 517 if (result.frequency >= LOWER_FREQ_5GHZ 518 && result.frequency <= HIGHER_FREQ_5GHZ) { 519 // Strictly speaking: [4915, 5825] 520 // number of known BSSID on 5GHz band 521 num5 = num5 + 1; 522 } else if (result.frequency >= LOWER_FREQ_24GHZ 523 && result.frequency <= HIGHER_FREQ_24GHZ) { 524 // Strictly speaking: [2412, 2482] 525 // number of known BSSID on 2.4Ghz band 526 num24 = num24 + 1; 527 } 528 529 530 if (result.frequency >= LOWER_FREQ_5GHZ 531 && result.frequency <= HIGHER_FREQ_5GHZ) { 532 if (result.level > rssi5) { 533 rssi5 = result.level; 534 } 535 if (n5 < 4) { 536 if (scans5GHz == null) scans5GHz = new StringBuilder(); 537 scans5GHz.append(" \n{").append(result.BSSID); 538 if (bssid != null && result.BSSID.equals(bssid)) scans5GHz.append("*"); 539 scans5GHz.append("=").append(result.frequency); 540 scans5GHz.append(",").append(result.level); 541 scans5GHz.append("}"); 542 n5++; 543 } 544 } else if (result.frequency >= LOWER_FREQ_24GHZ 545 && result.frequency <= HIGHER_FREQ_24GHZ) { 546 if (result.level > rssi24) { 547 rssi24 = result.level; 548 } 549 if (n24 < 4) { 550 if (scans24GHz == null) scans24GHz = new StringBuilder(); 551 scans24GHz.append(" \n{").append(result.BSSID); 552 if (bssid != null && result.BSSID.equals(bssid)) scans24GHz.append("*"); 553 scans24GHz.append("=").append(result.frequency); 554 scans24GHz.append(",").append(result.level); 555 scans24GHz.append("}"); 556 n24++; 557 } 558 } 559 } 560 visibility.append(" ["); 561 if (num24 > 0) { 562 visibility.append("(").append(num24).append(")"); 563 if (n24 <= 4) { 564 if (scans24GHz != null) { 565 visibility.append(scans24GHz.toString()); 566 } 567 } else { 568 visibility.append("max=").append(rssi24); 569 if (scans24GHz != null) { 570 visibility.append(",").append(scans24GHz.toString()); 571 } 572 } 573 } 574 visibility.append(";"); 575 if (num5 > 0) { 576 visibility.append("(").append(num5).append(")"); 577 if (n5 <= 4) { 578 if (scans5GHz != null) { 579 visibility.append(scans5GHz.toString()); 580 } 581 } else { 582 visibility.append("max=").append(rssi5); 583 if (scans5GHz != null) { 584 visibility.append(",").append(scans5GHz.toString()); 585 } 586 } 587 } 588 if (numBlackListed > 0) 589 visibility.append("!").append(numBlackListed); 590 visibility.append("]"); 591 592 return visibility.toString(); 593 } 594 595 /** 596 * Return whether this is the active connection. 597 * For ephemeral connections (networkId is invalid), this returns false if the network is 598 * disconnected. 599 */ 600 public boolean isActive() { 601 return mNetworkInfo != null && 602 (networkId != WifiConfiguration.INVALID_NETWORK_ID || 603 mNetworkInfo.getState() != State.DISCONNECTED); 604 } 605 606 public boolean isConnectable() { 607 return getLevel() != -1 && getDetailedState() == null; 608 } 609 610 public boolean isEphemeral() { 611 return mInfo != null && mInfo.isEphemeral() && 612 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED; 613 } 614 615 public boolean isPasspoint() { 616 return mConfig != null && mConfig.isPasspoint(); 617 } 618 619 /** 620 * Return whether the given {@link WifiInfo} is for this access point. 621 * If the current AP does not have a network Id then the config is used to 622 * match based on SSID and security. 623 */ 624 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) { 625 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) { 626 return networkId == info.getNetworkId(); 627 } else if (config != null) { 628 return matches(config); 629 } 630 else { 631 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID. 632 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID). 633 // TODO: Handle hex string SSIDs. 634 return ssid.equals(removeDoubleQuotes(info.getSSID())); 635 } 636 } 637 638 public boolean isSaved() { 639 return networkId != WifiConfiguration.INVALID_NETWORK_ID; 640 } 641 642 public Object getTag() { 643 return mTag; 644 } 645 646 public void setTag(Object tag) { 647 mTag = tag; 648 } 649 650 /** 651 * Generate and save a default wifiConfiguration with common values. 652 * Can only be called for unsecured networks. 653 */ 654 public void generateOpenNetworkConfig() { 655 if (security != SECURITY_NONE) 656 throw new IllegalStateException(); 657 if (mConfig != null) 658 return; 659 mConfig = new WifiConfiguration(); 660 mConfig.SSID = AccessPoint.convertToQuotedString(ssid); 661 mConfig.allowedKeyManagement.set(KeyMgmt.NONE); 662 } 663 664 void loadConfig(WifiConfiguration config) { 665 if (config.isPasspoint()) 666 ssid = config.providerFriendlyName; 667 else 668 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID)); 669 670 bssid = config.BSSID; 671 security = getSecurity(config); 672 networkId = config.networkId; 673 mConfig = config; 674 } 675 676 private void initWithScanResult(ScanResult result) { 677 ssid = result.SSID; 678 bssid = result.BSSID; 679 security = getSecurity(result); 680 if (security == SECURITY_PSK) 681 pskType = getPskType(result); 682 mRssi = result.level; 683 mSeen = result.timestamp; 684 } 685 686 public void saveWifiState(Bundle savedState) { 687 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr()); 688 savedState.putInt(KEY_SECURITY, security); 689 savedState.putInt(KEY_PSKTYPE, pskType); 690 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig); 691 savedState.putParcelable(KEY_WIFIINFO, mInfo); 692 savedState.putParcelableArrayList(KEY_SCANRESULTCACHE, 693 new ArrayList<ScanResult>(mScanResultCache.snapshot().values())); 694 if (mNetworkInfo != null) { 695 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo); 696 } 697 } 698 699 public void setListener(AccessPointListener listener) { 700 mAccessPointListener = listener; 701 } 702 703 boolean update(ScanResult result) { 704 if (matches(result)) { 705 /* Update the LRU timestamp, if BSSID exists */ 706 mScanResultCache.get(result.BSSID); 707 708 /* Add or update the scan result for the BSSID */ 709 mScanResultCache.put(result.BSSID, result); 710 711 int oldLevel = getLevel(); 712 int oldRssi = getRssi(); 713 mSeen = getSeen(); 714 mRssi = (getRssi() + oldRssi)/2; 715 int newLevel = getLevel(); 716 717 if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) { 718 mAccessPointListener.onLevelChanged(this); 719 } 720 // This flag only comes from scans, is not easily saved in config 721 if (security == SECURITY_PSK) { 722 pskType = getPskType(result); 723 } 724 725 if (mAccessPointListener != null) { 726 mAccessPointListener.onAccessPointChanged(this); 727 } 728 729 return true; 730 } 731 return false; 732 } 733 734 boolean update(WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) { 735 boolean reorder = false; 736 if (info != null && isInfoForThisAccessPoint(config, info)) { 737 reorder = (mInfo == null); 738 mRssi = info.getRssi(); 739 mInfo = info; 740 mNetworkInfo = networkInfo; 741 if (mAccessPointListener != null) { 742 mAccessPointListener.onAccessPointChanged(this); 743 } 744 } else if (mInfo != null) { 745 reorder = true; 746 mInfo = null; 747 mNetworkInfo = null; 748 if (mAccessPointListener != null) { 749 mAccessPointListener.onAccessPointChanged(this); 750 } 751 } 752 return reorder; 753 } 754 755 void update(WifiConfiguration config) { 756 mConfig = config; 757 networkId = config.networkId; 758 if (mAccessPointListener != null) { 759 mAccessPointListener.onAccessPointChanged(this); 760 } 761 } 762 763 void setRssi(int rssi) { 764 mRssi = rssi; 765 } 766 767 public static String getSummary(Context context, String ssid, DetailedState state, 768 boolean isEphemeral, String passpointProvider) { 769 if (state == DetailedState.CONNECTED && ssid == null) { 770 if (TextUtils.isEmpty(passpointProvider) == false) { 771 // Special case for connected + passpoint networks. 772 String format = context.getString(R.string.connected_via_passpoint); 773 return String.format(format, passpointProvider); 774 } else if (isEphemeral) { 775 // Special case for connected + ephemeral networks. 776 return context.getString(R.string.connected_via_wfa); 777 } 778 } 779 780 // Case when there is wifi connected without internet connectivity. 781 final ConnectivityManager cm = (ConnectivityManager) 782 context.getSystemService(Context.CONNECTIVITY_SERVICE); 783 if (state == DetailedState.CONNECTED) { 784 IWifiManager wifiManager = IWifiManager.Stub.asInterface( 785 ServiceManager.getService(Context.WIFI_SERVICE)); 786 Network nw; 787 788 try { 789 nw = wifiManager.getCurrentNetwork(); 790 } catch (RemoteException e) { 791 nw = null; 792 } 793 NetworkCapabilities nc = cm.getNetworkCapabilities(nw); 794 if (nc != null && !nc.hasCapability(nc.NET_CAPABILITY_VALIDATED)) { 795 return context.getString(R.string.wifi_connected_no_internet); 796 } 797 } 798 799 String[] formats = context.getResources().getStringArray((ssid == null) 800 ? R.array.wifi_status : R.array.wifi_status_with_ssid); 801 int index = state.ordinal(); 802 803 if (index >= formats.length || formats[index].length() == 0) { 804 return ""; 805 } 806 return String.format(formats[index], ssid); 807 } 808 809 public static String getSummary(Context context, DetailedState state, boolean isEphemeral) { 810 return getSummary(context, null, state, isEphemeral, null); 811 } 812 813 public static String getSummary(Context context, DetailedState state, boolean isEphemeral, 814 String passpointProvider) { 815 return getSummary(context, null, state, isEphemeral, passpointProvider); 816 } 817 818 public static String convertToQuotedString(String string) { 819 return "\"" + string + "\""; 820 } 821 822 private static int getPskType(ScanResult result) { 823 boolean wpa = result.capabilities.contains("WPA-PSK"); 824 boolean wpa2 = result.capabilities.contains("WPA2-PSK"); 825 if (wpa2 && wpa) { 826 return PSK_WPA_WPA2; 827 } else if (wpa2) { 828 return PSK_WPA2; 829 } else if (wpa) { 830 return PSK_WPA; 831 } else { 832 Log.w(TAG, "Received abnormal flag string: " + result.capabilities); 833 return PSK_UNKNOWN; 834 } 835 } 836 837 private static int getSecurity(ScanResult result) { 838 if (result.capabilities.contains("WEP")) { 839 return SECURITY_WEP; 840 } else if (result.capabilities.contains("PSK")) { 841 return SECURITY_PSK; 842 } else if (result.capabilities.contains("EAP")) { 843 return SECURITY_EAP; 844 } 845 return SECURITY_NONE; 846 } 847 848 static int getSecurity(WifiConfiguration config) { 849 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { 850 return SECURITY_PSK; 851 } 852 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || 853 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { 854 return SECURITY_EAP; 855 } 856 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE; 857 } 858 859 public static String securityToString(int security, int pskType) { 860 if (security == SECURITY_WEP) { 861 return "WEP"; 862 } else if (security == SECURITY_PSK) { 863 if (pskType == PSK_WPA) { 864 return "WPA"; 865 } else if (pskType == PSK_WPA2) { 866 return "WPA2"; 867 } else if (pskType == PSK_WPA_WPA2) { 868 return "WPA_WPA2"; 869 } 870 return "PSK"; 871 } else if (security == SECURITY_EAP) { 872 return "EAP"; 873 } 874 return "NONE"; 875 } 876 877 static String removeDoubleQuotes(String string) { 878 if (TextUtils.isEmpty(string)) { 879 return ""; 880 } 881 int length = string.length(); 882 if ((length > 1) && (string.charAt(0) == '"') 883 && (string.charAt(length - 1) == '"')) { 884 return string.substring(1, length - 1); 885 } 886 return string; 887 } 888 889 public interface AccessPointListener { 890 void onAccessPointChanged(AccessPoint accessPoint); 891 void onLevelChanged(AccessPoint accessPoint); 892 } 893} 894