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