AccessPoint.java revision 0d492e8365d1d8ca3b5469f697e1a9c6b484023b
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 static String getKey(WifiConfiguration config) {
626        StringBuilder builder = new StringBuilder();
627
628        if (TextUtils.isEmpty(config.SSID)) {
629            builder.append(config.BSSID);
630        } else {
631            builder.append(removeDoubleQuotes(config.SSID));
632        }
633
634        builder.append(',').append(getSecurity(config));
635        return builder.toString();
636    }
637
638    public String getKey() {
639        return mKey;
640    }
641
642    public boolean matches(WifiConfiguration config) {
643        if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) {
644            return ssid.equals(removeDoubleQuotes(config.SSID)) && config.FQDN.equals(mConfig.FQDN);
645        } else {
646            return ssid.equals(removeDoubleQuotes(config.SSID))
647                    && security == getSecurity(config)
648                    && (mConfig == null || mConfig.shared == config.shared);
649        }
650    }
651
652    public WifiConfiguration getConfig() {
653        return mConfig;
654    }
655
656    public String getPasspointFqdn() {
657        return mFqdn;
658    }
659
660    public void clearConfig() {
661        mConfig = null;
662        networkId = WifiConfiguration.INVALID_NETWORK_ID;
663    }
664
665    public WifiInfo getInfo() {
666        return mInfo;
667    }
668
669    /**
670     * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1.
671     *
672     * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will
673     * always return at least 0.
674     */
675    public int getLevel() {
676        return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
677    }
678
679    public int getRssi() {
680        return mRssi;
681    }
682
683    /**
684     * Returns the underlying scan result set.
685     *
686     * <p>Callers should not modify this set.
687     */
688    public Set<ScanResult> getScanResults() { return mScanResults; }
689
690    public Map<String, TimestampedScoredNetwork> getScoredNetworkCache() {
691        return mScoredNetworkCache;
692    }
693
694    /**
695     * Updates {@link #mRssi}.
696     *
697     * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned.
698     * If the given AccessPoint is not active, a value will be calculated from previous scan
699     * results, returning the best RSSI for all matching AccessPoints averaged with the previous
700     * value. If the access point is not connected and there are no scan results, the rssi will be
701     * set to {@link #UNREACHABLE_RSSI}.
702     */
703    private void updateRssi() {
704        if (this.isActive()) {
705            return;
706        }
707
708        int rssi = UNREACHABLE_RSSI;
709        for (ScanResult result : mScanResults) {
710            if (result.level > rssi) {
711                rssi = result.level;
712            }
713        }
714
715        if (rssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) {
716            mRssi = (mRssi + rssi) / 2; // half-life previous value
717        } else {
718            mRssi = rssi;
719        }
720    }
721
722    /**
723     * Returns if the network should be considered metered.
724     */
725    public boolean isMetered() {
726        return mIsScoredNetworkMetered
727                || WifiConfiguration.isMetered(mConfig, mInfo);
728    }
729
730    public NetworkInfo getNetworkInfo() {
731        return mNetworkInfo;
732    }
733
734    public int getSecurity() {
735        return security;
736    }
737
738    public String getSecurityString(boolean concise) {
739        Context context = mContext;
740        if (isPasspoint() || isPasspointConfig()) {
741            return concise ? context.getString(R.string.wifi_security_short_eap) :
742                context.getString(R.string.wifi_security_eap);
743        }
744        switch(security) {
745            case SECURITY_EAP:
746                return concise ? context.getString(R.string.wifi_security_short_eap) :
747                    context.getString(R.string.wifi_security_eap);
748            case SECURITY_PSK:
749                switch (pskType) {
750                    case PSK_WPA:
751                        return concise ? context.getString(R.string.wifi_security_short_wpa) :
752                            context.getString(R.string.wifi_security_wpa);
753                    case PSK_WPA2:
754                        return concise ? context.getString(R.string.wifi_security_short_wpa2) :
755                            context.getString(R.string.wifi_security_wpa2);
756                    case PSK_WPA_WPA2:
757                        return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
758                            context.getString(R.string.wifi_security_wpa_wpa2);
759                    case PSK_UNKNOWN:
760                    default:
761                        return concise ? context.getString(R.string.wifi_security_short_psk_generic)
762                                : context.getString(R.string.wifi_security_psk_generic);
763                }
764            case SECURITY_WEP:
765                return concise ? context.getString(R.string.wifi_security_short_wep) :
766                    context.getString(R.string.wifi_security_wep);
767            case SECURITY_NONE:
768            default:
769                return concise ? "" : context.getString(R.string.wifi_security_none);
770        }
771    }
772
773    public String getSsidStr() {
774        return ssid;
775    }
776
777    public String getBssid() {
778        return bssid;
779    }
780
781    public CharSequence getSsid() {
782        final SpannableString str = new SpannableString(ssid);
783        str.setSpan(new TtsSpan.TelephoneBuilder(ssid).build(), 0, ssid.length(),
784                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
785        return str;
786    }
787
788    public String getConfigName() {
789        if (mConfig != null && mConfig.isPasspoint()) {
790            return mConfig.providerFriendlyName;
791        } else if (mFqdn != null) {
792            return mProviderFriendlyName;
793        } else {
794            return ssid;
795        }
796    }
797
798    public DetailedState getDetailedState() {
799        if (mNetworkInfo != null) {
800            return mNetworkInfo.getDetailedState();
801        }
802        Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
803        return null;
804    }
805
806    public boolean isCarrierAp() {
807        return mIsCarrierAp;
808    }
809
810    public int getCarrierApEapType() {
811        return mCarrierApEapType;
812    }
813
814    public String getCarrierName() {
815        return mCarrierName;
816    }
817
818    public String getSavedNetworkSummary() {
819        WifiConfiguration config = mConfig;
820        if (config != null) {
821            PackageManager pm = mContext.getPackageManager();
822            String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
823            int userId = UserHandle.getUserId(config.creatorUid);
824            ApplicationInfo appInfo = null;
825            if (config.creatorName != null && config.creatorName.equals(systemName)) {
826                appInfo = mContext.getApplicationInfo();
827            } else {
828                try {
829                    IPackageManager ipm = AppGlobals.getPackageManager();
830                    appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
831                } catch (RemoteException rex) {
832                }
833            }
834            if (appInfo != null &&
835                    !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
836                    !appInfo.packageName.equals(
837                    mContext.getString(R.string.certinstaller_package))) {
838                return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
839            }
840        }
841        return "";
842    }
843
844    public String getSummary() {
845        return getSettingsSummary(mConfig);
846    }
847
848    public String getSettingsSummary() {
849        return getSettingsSummary(mConfig);
850    }
851
852    private String getSettingsSummary(WifiConfiguration config) {
853        // Update to new summary
854        StringBuilder summary = new StringBuilder();
855
856        if (isActive() && config != null && config.isPasspoint()) {
857            // This is the active connection on passpoint
858            summary.append(getSummary(mContext, getDetailedState(),
859                    false, config.providerFriendlyName));
860        } else if (isActive() && config != null && getDetailedState() == DetailedState.CONNECTED
861                && mIsCarrierAp) {
862            summary.append(String.format(mContext.getString(R.string.connected_via_carrier), mCarrierName));
863        } else if (isActive()) {
864            // This is the active connection on non-passpoint network
865            summary.append(getSummary(mContext, getDetailedState(),
866                    mInfo != null && mInfo.isEphemeral()));
867        } else if (config != null && config.isPasspoint()
868                && config.getNetworkSelectionStatus().isNetworkEnabled()) {
869            String format = mContext.getString(R.string.available_via_passpoint);
870            summary.append(String.format(format, config.providerFriendlyName));
871        } else if (config != null && config.hasNoInternetAccess()) {
872            int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
873                    ? R.string.wifi_no_internet_no_reconnect
874                    : R.string.wifi_no_internet;
875            summary.append(mContext.getString(messageID));
876        } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
877            WifiConfiguration.NetworkSelectionStatus networkStatus =
878                    config.getNetworkSelectionStatus();
879            switch (networkStatus.getNetworkSelectionDisableReason()) {
880                case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
881                    summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
882                    break;
883                case WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD:
884                    summary.append(mContext.getString(R.string.wifi_check_password_try_again));
885                    break;
886                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
887                case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
888                    summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
889                    break;
890                case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
891                    summary.append(mContext.getString(R.string.wifi_disabled_generic));
892                    break;
893            }
894        } else if (config != null && config.getNetworkSelectionStatus().isNotRecommended()) {
895            summary.append(mContext.getString(R.string.wifi_disabled_by_recommendation_provider));
896        } else if (mIsCarrierAp) {
897            summary.append(String.format(mContext.getString(R.string.available_via_carrier), mCarrierName));
898        } else if (!isReachable()) { // Wifi out of range
899            summary.append(mContext.getString(R.string.wifi_not_in_range));
900        } else { // In range, not disabled.
901            if (config != null) { // Is saved network
902                // Last attempt to connect to this failed. Show reason why
903                switch (config.recentFailure.getAssociationStatus()) {
904                    case WifiConfiguration.RecentFailure.STATUS_AP_UNABLE_TO_HANDLE_NEW_STA:
905                        summary.append(mContext.getString(
906                                R.string.wifi_ap_unable_to_handle_new_sta));
907                        break;
908                    default:
909                        // "Saved"
910                        summary.append(mContext.getString(R.string.wifi_remembered));
911                        break;
912                }
913            }
914        }
915
916        if (WifiTracker.sVerboseLogging) {
917            summary.append(WifiUtils.buildLoggingSummary(this, config));
918        }
919
920        // If Speed label and summary are both present, use the preference combination to combine
921        // the two, else return the non-null one.
922        if (getSpeedLabel() != null && summary.length() != 0) {
923            return mContext.getResources().getString(
924                    R.string.preference_summary_default_combination,
925                    getSpeedLabel(),
926                    summary.toString());
927        } else if (getSpeedLabel() != null) {
928            return getSpeedLabel();
929        } else {
930            return summary.toString();
931        }
932    }
933
934    /**
935     * Return whether this is the active connection.
936     * For ephemeral connections (networkId is invalid), this returns false if the network is
937     * disconnected.
938     */
939    public boolean isActive() {
940        return mNetworkInfo != null &&
941                (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
942                 mNetworkInfo.getState() != State.DISCONNECTED);
943    }
944
945    public boolean isConnectable() {
946        return getLevel() != -1 && getDetailedState() == null;
947    }
948
949    public boolean isEphemeral() {
950        return mInfo != null && mInfo.isEphemeral() &&
951                mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
952    }
953
954    /**
955     * Return true if this AccessPoint represents a Passpoint AP.
956     */
957    public boolean isPasspoint() {
958        return mConfig != null && mConfig.isPasspoint();
959    }
960
961    /**
962     * Return true if this AccessPoint represents a Passpoint provider configuration.
963     */
964    public boolean isPasspointConfig() {
965        return mFqdn != null;
966    }
967
968    /**
969     * Return whether the given {@link WifiInfo} is for this access point.
970     * If the current AP does not have a network Id then the config is used to
971     * match based on SSID and security.
972     */
973    private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
974        if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
975            return networkId == info.getNetworkId();
976        } else if (config != null) {
977            return matches(config);
978        }
979        else {
980            // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
981            // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
982            // TODO: Handle hex string SSIDs.
983            return ssid.equals(removeDoubleQuotes(info.getSSID()));
984        }
985    }
986
987    public boolean isSaved() {
988        return networkId != WifiConfiguration.INVALID_NETWORK_ID;
989    }
990
991    public Object getTag() {
992        return mTag;
993    }
994
995    public void setTag(Object tag) {
996        mTag = tag;
997    }
998
999    /**
1000     * Generate and save a default wifiConfiguration with common values.
1001     * Can only be called for unsecured networks.
1002     */
1003    public void generateOpenNetworkConfig() {
1004        if (security != SECURITY_NONE)
1005            throw new IllegalStateException();
1006        if (mConfig != null)
1007            return;
1008        mConfig = new WifiConfiguration();
1009        mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
1010        mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
1011    }
1012
1013    public void saveWifiState(Bundle savedState) {
1014        if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
1015        savedState.putInt(KEY_SECURITY, security);
1016        savedState.putInt(KEY_SPEED, mSpeed);
1017        savedState.putInt(KEY_PSKTYPE, pskType);
1018        if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
1019        savedState.putParcelable(KEY_WIFIINFO, mInfo);
1020        savedState.putParcelableArray(KEY_SCANRESULTS,
1021                mScanResults.toArray(new Parcelable[mScanResults.size()]));
1022        savedState.putParcelableArrayList(KEY_SCOREDNETWORKCACHE,
1023                new ArrayList<>(mScoredNetworkCache.values()));
1024        if (mNetworkInfo != null) {
1025            savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
1026        }
1027        if (mFqdn != null) {
1028            savedState.putString(KEY_FQDN, mFqdn);
1029        }
1030        if (mProviderFriendlyName != null) {
1031            savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
1032        }
1033        savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp);
1034        savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType);
1035        savedState.putString(KEY_CARRIER_NAME, mCarrierName);
1036    }
1037
1038    public void setListener(AccessPointListener listener) {
1039        mAccessPointListener = listener;
1040    }
1041
1042    /**
1043     * Sets {@link #mScanResults} to the given collection.
1044     *
1045     * @param scanResults a collection of scan results to add to the internal set
1046     * @throws IllegalArgumentException if any of the given ScanResults did not belong to this AP
1047     */
1048    void setScanResults(Collection<ScanResult> scanResults) {
1049
1050        // Validate scan results are for current AP only
1051        String key = getKey();
1052        for (ScanResult result : scanResults) {
1053            String scanResultKey = AccessPoint.getKey(result);
1054            if (!mKey.equals(scanResultKey)) {
1055                throw new IllegalArgumentException(
1056                        String.format("ScanResult %s\nkey of %s did not match current AP key %s",
1057                                      result, scanResultKey, key));
1058            }
1059        }
1060
1061
1062        int oldLevel = getLevel();
1063        mScanResults.clear();
1064        mScanResults.addAll(scanResults);
1065        updateRssi();
1066        int newLevel = getLevel();
1067
1068        // If newLevel is 0, there will be no displayed Preference since the AP is unreachable
1069        if (newLevel > 0 && newLevel != oldLevel) {
1070            // Only update labels on visible rssi changes
1071            updateSpeed();
1072            if (mAccessPointListener != null) {
1073                mAccessPointListener.onLevelChanged(this);
1074            }
1075        }
1076
1077        if (mAccessPointListener != null) {
1078            mAccessPointListener.onAccessPointChanged(this);
1079        }
1080
1081        if (!scanResults.isEmpty()) {
1082            ScanResult result = scanResults.iterator().next();
1083
1084            // This flag only comes from scans, is not easily saved in config
1085            if (security == SECURITY_PSK) {
1086                pskType = getPskType(result);
1087            }
1088
1089            // The carrier info in the ScanResult is set by the platform based on the SSID and will
1090            // always be the same for all matching scan results.
1091            mIsCarrierAp = result.isCarrierAp;
1092            mCarrierApEapType = result.carrierApEapType;
1093            mCarrierName = result.carrierName;
1094        }
1095    }
1096
1097    /** Attempt to update the AccessPoint and return true if an update occurred. */
1098    public boolean update(
1099            @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
1100
1101        boolean updated = false;
1102        final int oldLevel = getLevel();
1103        if (info != null && isInfoForThisAccessPoint(config, info)) {
1104            updated = (mInfo == null);
1105            if (mConfig != config) {
1106                // We do not set updated = true as we do not want to increase the amount of sorting
1107                // and copying performed in WifiTracker at this time. If issues involving refresh
1108                // are still seen, we will investigate further.
1109                update(config); // Notifies the AccessPointListener of the change
1110            }
1111            if (mRssi != info.getRssi() && info.getRssi() != WifiInfo.INVALID_RSSI) {
1112                mRssi = info.getRssi();
1113                updated = true;
1114            } else if (mNetworkInfo != null && networkInfo != null
1115                    && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) {
1116                updated = true;
1117            }
1118            mInfo = info;
1119            mNetworkInfo = networkInfo;
1120        } else if (mInfo != null) {
1121            updated = true;
1122            mInfo = null;
1123            mNetworkInfo = null;
1124        }
1125        if (updated && mAccessPointListener != null) {
1126            mAccessPointListener.onAccessPointChanged(this);
1127
1128            if (oldLevel != getLevel() /* current level */) {
1129                mAccessPointListener.onLevelChanged(this);
1130            }
1131        }
1132
1133        return updated;
1134    }
1135
1136    void update(@Nullable WifiConfiguration config) {
1137        mConfig = config;
1138        networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID;
1139        if (mAccessPointListener != null) {
1140            mAccessPointListener.onAccessPointChanged(this);
1141        }
1142    }
1143
1144    @VisibleForTesting
1145    void setRssi(int rssi) {
1146        mRssi = rssi;
1147    }
1148
1149    /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
1150    void setUnreachable() {
1151        setRssi(AccessPoint.UNREACHABLE_RSSI);
1152    }
1153
1154    int getSpeed() { return mSpeed;}
1155
1156    @Nullable
1157    String getSpeedLabel() {
1158        return getSpeedLabel(mSpeed);
1159    }
1160
1161    @Nullable
1162    @Speed
1163    private int roundToClosestSpeedEnum(int speed) {
1164        if (speed < Speed.SLOW) {
1165            return Speed.NONE;
1166        } else if (speed < (Speed.SLOW + Speed.MODERATE) / 2) {
1167            return Speed.SLOW;
1168        } else if (speed < (Speed.MODERATE + Speed.FAST) / 2) {
1169            return Speed.MODERATE;
1170        } else if (speed < (Speed.FAST + Speed.VERY_FAST) / 2) {
1171            return Speed.FAST;
1172        } else {
1173            return Speed.VERY_FAST;
1174        }
1175    }
1176
1177    @Nullable
1178    String getSpeedLabel(@Speed int speed) {
1179        switch (speed) {
1180            case Speed.VERY_FAST:
1181                return mContext.getString(R.string.speed_label_very_fast);
1182            case Speed.FAST:
1183                return mContext.getString(R.string.speed_label_fast);
1184            case Speed.MODERATE:
1185                return mContext.getString(R.string.speed_label_okay);
1186            case Speed.SLOW:
1187                return mContext.getString(R.string.speed_label_slow);
1188            case Speed.NONE:
1189            default:
1190                return null;
1191        }
1192    }
1193
1194    /** Return true if the current RSSI is reachable, and false otherwise. */
1195    public boolean isReachable() {
1196        return mRssi != UNREACHABLE_RSSI;
1197    }
1198
1199    public static String getSummary(Context context, String ssid, DetailedState state,
1200            boolean isEphemeral, String passpointProvider) {
1201        if (state == DetailedState.CONNECTED && ssid == null) {
1202            if (TextUtils.isEmpty(passpointProvider) == false) {
1203                // Special case for connected + passpoint networks.
1204                String format = context.getString(R.string.connected_via_passpoint);
1205                return String.format(format, passpointProvider);
1206            } else if (isEphemeral) {
1207                // Special case for connected + ephemeral networks.
1208                final NetworkScoreManager networkScoreManager = context.getSystemService(
1209                        NetworkScoreManager.class);
1210                NetworkScorerAppData scorer = networkScoreManager.getActiveScorer();
1211                if (scorer != null && scorer.getRecommendationServiceLabel() != null) {
1212                    String format = context.getString(R.string.connected_via_network_scorer);
1213                    return String.format(format, scorer.getRecommendationServiceLabel());
1214                } else {
1215                    return context.getString(R.string.connected_via_network_scorer_default);
1216                }
1217            }
1218        }
1219
1220        // Case when there is wifi connected without internet connectivity.
1221        final ConnectivityManager cm = (ConnectivityManager)
1222                context.getSystemService(Context.CONNECTIVITY_SERVICE);
1223        if (state == DetailedState.CONNECTED) {
1224            IWifiManager wifiManager = IWifiManager.Stub.asInterface(
1225                    ServiceManager.getService(Context.WIFI_SERVICE));
1226            NetworkCapabilities nc = null;
1227
1228            try {
1229                nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1230            } catch (RemoteException e) {}
1231
1232            if (nc != null) {
1233                if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
1234                    int id = context.getResources()
1235                            .getIdentifier("network_available_sign_in", "string", "android");
1236                    return context.getString(id);
1237                } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
1238                    return context.getString(R.string.wifi_connected_no_internet);
1239                }
1240            }
1241        }
1242        if (state == null) {
1243            Log.w(TAG, "state is null, returning empty summary");
1244            return "";
1245        }
1246        String[] formats = context.getResources().getStringArray((ssid == null)
1247                ? R.array.wifi_status : R.array.wifi_status_with_ssid);
1248        int index = state.ordinal();
1249
1250        if (index >= formats.length || formats[index].length() == 0) {
1251            return "";
1252        }
1253        return String.format(formats[index], ssid);
1254    }
1255
1256    public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
1257        return getSummary(context, null, state, isEphemeral, null);
1258    }
1259
1260    public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
1261            String passpointProvider) {
1262        return getSummary(context, null, state, isEphemeral, passpointProvider);
1263    }
1264
1265    public static String convertToQuotedString(String string) {
1266        return "\"" + string + "\"";
1267    }
1268
1269    private static int getPskType(ScanResult result) {
1270        boolean wpa = result.capabilities.contains("WPA-PSK");
1271        boolean wpa2 = result.capabilities.contains("WPA2-PSK");
1272        if (wpa2 && wpa) {
1273            return PSK_WPA_WPA2;
1274        } else if (wpa2) {
1275            return PSK_WPA2;
1276        } else if (wpa) {
1277            return PSK_WPA;
1278        } else {
1279            Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
1280            return PSK_UNKNOWN;
1281        }
1282    }
1283
1284    private static int getSecurity(ScanResult result) {
1285        if (result.capabilities.contains("WEP")) {
1286            return SECURITY_WEP;
1287        } else if (result.capabilities.contains("PSK")) {
1288            return SECURITY_PSK;
1289        } else if (result.capabilities.contains("EAP")) {
1290            return SECURITY_EAP;
1291        }
1292        return SECURITY_NONE;
1293    }
1294
1295    static int getSecurity(WifiConfiguration config) {
1296        if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1297            return SECURITY_PSK;
1298        }
1299        if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1300                config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1301            return SECURITY_EAP;
1302        }
1303        return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
1304    }
1305
1306    public static String securityToString(int security, int pskType) {
1307        if (security == SECURITY_WEP) {
1308            return "WEP";
1309        } else if (security == SECURITY_PSK) {
1310            if (pskType == PSK_WPA) {
1311                return "WPA";
1312            } else if (pskType == PSK_WPA2) {
1313                return "WPA2";
1314            } else if (pskType == PSK_WPA_WPA2) {
1315                return "WPA_WPA2";
1316            }
1317            return "PSK";
1318        } else if (security == SECURITY_EAP) {
1319            return "EAP";
1320        }
1321        return "NONE";
1322    }
1323
1324    static String removeDoubleQuotes(String string) {
1325        if (TextUtils.isEmpty(string)) {
1326            return "";
1327        }
1328        int length = string.length();
1329        if ((length > 1) && (string.charAt(0) == '"')
1330                && (string.charAt(length - 1) == '"')) {
1331            return string.substring(1, length - 1);
1332        }
1333        return string;
1334    }
1335
1336    public interface AccessPointListener {
1337        void onAccessPointChanged(AccessPoint accessPoint);
1338        void onLevelChanged(AccessPoint accessPoint);
1339    }
1340}
1341