Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 353952fa authored by TreeHugger Robot's avatar TreeHugger Robot Committed by Android (Google) Code Review
Browse files

Merge changes I1a1077c1,I7adb6de2,Ieea1af71

* changes:
  Clean up updateAccessPoints.
  Remove unused variables and resulting conditionals.
  Execute all callbacks on the MainThread.
parents 0b89088c 0d492e83
Loading
Loading
Loading
Loading
+13 −0
Original line number Original line Diff line number Diff line
@@ -622,6 +622,19 @@ public class AccessPoint implements Comparable<AccessPoint> {
        return builder.toString();
        return builder.toString();
    }
    }


    public static String getKey(WifiConfiguration config) {
        StringBuilder builder = new StringBuilder();

        if (TextUtils.isEmpty(config.SSID)) {
            builder.append(config.BSSID);
        } else {
            builder.append(removeDoubleQuotes(config.SSID));
        }

        builder.append(',').append(getSecurity(config));
        return builder.toString();
    }

    public String getKey() {
    public String getKey() {
        return mKey;
        return mKey;
    }
    }
+53 −81
Original line number Original line Diff line number Diff line
@@ -92,8 +92,6 @@ public class WifiTracker implements LifecycleObserver, OnStart, OnStop, OnDestro
     * and used so as to assist with in-the-field WiFi connectivity debugging  */
     * and used so as to assist with in-the-field WiFi connectivity debugging  */
    public static boolean sVerboseLogging;
    public static boolean sVerboseLogging;


    // TODO(b/36733768): Remove flag includeSaved

    // TODO: Allow control of this?
    // TODO: Allow control of this?
    // Combo scans can take 5-6s to complete - set to 10s.
    // Combo scans can take 5-6s to complete - set to 10s.
    private static final int WIFI_RESCAN_INTERVAL_MS = 10 * 1000;
    private static final int WIFI_RESCAN_INTERVAL_MS = 10 * 1000;
@@ -106,8 +104,6 @@ public class WifiTracker implements LifecycleObserver, OnStart, OnStop, OnDestro
    private final NetworkRequest mNetworkRequest;
    private final NetworkRequest mNetworkRequest;
    private final AtomicBoolean mConnected = new AtomicBoolean(false);
    private final AtomicBoolean mConnected = new AtomicBoolean(false);
    private final WifiListener mListener;
    private final WifiListener mListener;
    private final boolean mIncludeSaved;
    private final boolean mIncludeScans;
    @VisibleForTesting MainHandler mMainHandler;
    @VisibleForTesting MainHandler mMainHandler;
    @VisibleForTesting WorkHandler mWorkHandler;
    @VisibleForTesting WorkHandler mWorkHandler;
    private HandlerThread mWorkThread;
    private HandlerThread mWorkThread;
@@ -150,7 +146,6 @@ public class WifiTracker implements LifecycleObserver, OnStart, OnStop, OnDestro


    // TODO(sghuman): Change this to be keyed on AccessPoint.getKey
    // TODO(sghuman): Change this to be keyed on AccessPoint.getKey
    private final HashMap<String, ScanResult> mScanResultCache = new HashMap<>();
    private final HashMap<String, ScanResult> mScanResultCache = new HashMap<>();
    private Integer mScanId = 0;


    private NetworkInfo mLastNetworkInfo;
    private NetworkInfo mLastNetworkInfo;
    private WifiInfo mLastInfo;
    private WifiInfo mLastInfo;
@@ -189,16 +184,18 @@ public class WifiTracker implements LifecycleObserver, OnStart, OnStop, OnDestro
    @Deprecated
    @Deprecated
    public WifiTracker(Context context, WifiListener wifiListener,
    public WifiTracker(Context context, WifiListener wifiListener,
            boolean includeSaved, boolean includeScans) {
            boolean includeSaved, boolean includeScans) {
        this(context, wifiListener, includeSaved, includeScans,
        this(context, wifiListener,
                context.getSystemService(WifiManager.class),
                context.getSystemService(WifiManager.class),
                context.getSystemService(ConnectivityManager.class),
                context.getSystemService(ConnectivityManager.class),
                context.getSystemService(NetworkScoreManager.class),
                context.getSystemService(NetworkScoreManager.class),
                newIntentFilter());
                newIntentFilter());
    }
    }


    // TODO(Sghuman): Clean up includeSaved and includeScans from all constructors and linked
    // calling apps once IC window is complete
    public WifiTracker(Context context, WifiListener wifiListener,
    public WifiTracker(Context context, WifiListener wifiListener,
            @NonNull Lifecycle lifecycle, boolean includeSaved, boolean includeScans) {
            @NonNull Lifecycle lifecycle, boolean includeSaved, boolean includeScans) {
        this(context, wifiListener, includeSaved, includeScans,
        this(context, wifiListener,
                context.getSystemService(WifiManager.class),
                context.getSystemService(WifiManager.class),
                context.getSystemService(ConnectivityManager.class),
                context.getSystemService(ConnectivityManager.class),
                context.getSystemService(NetworkScoreManager.class),
                context.getSystemService(NetworkScoreManager.class),
@@ -208,19 +205,13 @@ public class WifiTracker implements LifecycleObserver, OnStart, OnStop, OnDestro


    @VisibleForTesting
    @VisibleForTesting
    WifiTracker(Context context, WifiListener wifiListener,
    WifiTracker(Context context, WifiListener wifiListener,
            boolean includeSaved, boolean includeScans,
            WifiManager wifiManager, ConnectivityManager connectivityManager,
            WifiManager wifiManager, ConnectivityManager connectivityManager,
            NetworkScoreManager networkScoreManager,
            NetworkScoreManager networkScoreManager,
            IntentFilter filter) {
            IntentFilter filter) {
        if (!includeSaved && !includeScans) {
            throw new IllegalArgumentException("Must include either saved or scans");
        }
        mContext = context;
        mContext = context;
        mMainHandler = new MainHandler(Looper.getMainLooper());
        mMainHandler = new MainHandler(Looper.getMainLooper());
        mWifiManager = wifiManager;
        mWifiManager = wifiManager;
        mIncludeSaved = includeSaved;
        mListener = new WifiListenerWrapper(wifiListener);
        mIncludeScans = includeScans;
        mListener = wifiListener;
        mConnectivityManager = connectivityManager;
        mConnectivityManager = connectivityManager;


        // check if verbose logging has been turned on or off
        // check if verbose logging has been turned on or off
@@ -458,7 +449,6 @@ public class WifiTracker implements LifecycleObserver, OnStart, OnStop, OnDestro
    private void handleResume() {
    private void handleResume() {
        mScanResultCache.clear();
        mScanResultCache.clear();
        mSeenBssids.clear();
        mSeenBssids.clear();
        mScanId = 0;
    }
    }


    private Collection<ScanResult> updateScanResultCache(final List<ScanResult> newResults) {
    private Collection<ScanResult> updateScanResultCache(final List<ScanResult> newResults) {
@@ -533,7 +523,7 @@ public class WifiTracker implements LifecycleObserver, OnStart, OnStop, OnDestro
    /**
    /**
     * Update the internal list of access points.
     * Update the internal list of access points.
     *
     *
     * <p>Do not called directly (except for forceUpdate), use {@link #updateAccessPoints()} which
     * <p>Do not call directly (except for forceUpdate), use {@link #updateAccessPoints()} which
     * respects {@link #mStaleScanResults}.
     * respects {@link #mStaleScanResults}.
     */
     */
    @GuardedBy("mLock")
    @GuardedBy("mLock")
@@ -542,7 +532,7 @@ public class WifiTracker implements LifecycleObserver, OnStart, OnStop, OnDestro
        WifiConfiguration connectionConfig = null;
        WifiConfiguration connectionConfig = null;
        if (mLastInfo != null) {
        if (mLastInfo != null) {
            connectionConfig = getWifiConfigurationForNetworkId(
            connectionConfig = getWifiConfigurationForNetworkId(
                    mLastInfo.getNetworkId(), mWifiManager.getConfiguredNetworks());
                    mLastInfo.getNetworkId(), configs);
        }
        }


        // Swap the current access points into a cached list.
        // Swap the current access points into a cached list.
@@ -554,43 +544,12 @@ public class WifiTracker implements LifecycleObserver, OnStart, OnStop, OnDestro
            accessPoint.clearConfig();
            accessPoint.clearConfig();
        }
        }


    /* Lookup table to more quickly update AccessPoints by only considering objects with the
     * correct SSID.  Maps SSID -> List of AccessPoints with the given SSID.  */
        Multimap<String, AccessPoint> existingApMap = new Multimap<String, AccessPoint>();

        final Collection<ScanResult> results = updateScanResultCache(newScanResults);
        final Collection<ScanResult> results = updateScanResultCache(newScanResults);


        // TODO(sghuman): This entire block only exists to populate the WifiConfiguration for
        final Map<String, WifiConfiguration> configsByKey = new ArrayMap(configs.size());
        // APs, remove and refactor
        if (configs != null) {
        if (configs != null) {
            for (WifiConfiguration config : configs) {
            for (WifiConfiguration config : configs) {
                if (config.selfAdded && config.numAssociation == 0) {
                configsByKey.put(AccessPoint.getKey(config), config);
                    continue;
                }
                AccessPoint accessPoint = getCachedOrCreate(config, cachedAccessPoints);
                if (mLastInfo != null && mLastNetworkInfo != null) {
                    accessPoint.update(connectionConfig, mLastInfo, mLastNetworkInfo);
                }
                if (mIncludeSaved) {
                    // If saved network not present in scan result then set its Rssi to
                    // UNREACHABLE_RSSI
                    boolean apFound = false;
                    for (ScanResult result : results) {
                        if (result.SSID.equals(accessPoint.getSsidStr())) {
                            apFound = true;
                            break;
                        }
                    }
                    if (!apFound) {
                        accessPoint.setUnreachable();
                    }
                    accessPoints.add(accessPoint);
                    existingApMap.put(accessPoint.getSsidStr(), accessPoint);
                } else {
                    // If we aren't using saved networks, drop them into the cache so that
                    // we have access to their saved info.
                    cachedAccessPoints.add(accessPoint);
                }
            }
            }
        }
        }


@@ -626,42 +585,22 @@ public class WifiTracker implements LifecycleObserver, OnStart, OnStop, OnDestro
            for (Map.Entry<String, List<ScanResult>> entry : scanResultsByApKey.entrySet()) {
            for (Map.Entry<String, List<ScanResult>> entry : scanResultsByApKey.entrySet()) {
                // List can not be empty as it is dynamically constructed on each iteration
                // List can not be empty as it is dynamically constructed on each iteration
                ScanResult firstResult = entry.getValue().get(0);
                ScanResult firstResult = entry.getValue().get(0);
                boolean found = false;
                for (AccessPoint accessPoint : existingApMap.getAll(firstResult.SSID)) {
                    accessPoint.setScanResults(entry.getValue());
                    found = true;
                    break;
                }


                // Only create a new AP / add to the list if it wasn't already in the saved configs
                if (!found) {
                AccessPoint accessPoint =
                AccessPoint accessPoint =
                        getCachedOrCreate(entry.getValue(), cachedAccessPoints);
                        getCachedOrCreate(entry.getValue(), cachedAccessPoints);
                if (mLastInfo != null && mLastNetworkInfo != null) {
                if (mLastInfo != null && mLastNetworkInfo != null) {
                    accessPoint.update(connectionConfig, mLastInfo, mLastNetworkInfo);
                    accessPoint.update(connectionConfig, mLastInfo, mLastNetworkInfo);
                }
                }


                    // TODO(sghuman): Move isPasspointNetwork logic into AccessPoint.java
                // Update the matching config if there is one, to populate saved network info
                    if (firstResult.isPasspointNetwork()) {
                WifiConfiguration config = configsByKey.get(entry.getKey());
                        // Retrieve a WifiConfiguration for a Passpoint provider that matches
                        // the given ScanResult.  This is used for showing that a given AP
                        // (ScanResult) is available via a Passpoint provider (provider friendly
                        // name).
                        try {
                            WifiConfiguration config =
                                    mWifiManager.getMatchingWifiConfig(firstResult);
                if (config != null) {
                if (config != null) {
                    accessPoint.update(config);
                    accessPoint.update(config);
                }
                }
                        } catch (UnsupportedOperationException e) {
                            // Passpoint not supported on the device.
                        }
                    }


                accessPoints.add(accessPoint);
                accessPoints.add(accessPoint);
            }
            }
        }
        }
        }


        requestScoresForNetworkKeys(scoresToRequest);
        requestScoresForNetworkKeys(scoresToRequest);
        for (AccessPoint ap : accessPoints) {
        for (AccessPoint ap : accessPoints) {
@@ -1052,6 +991,39 @@ public class WifiTracker implements LifecycleObserver, OnStart, OnStop, OnDestro
        }
        }
    }
    }


    /**
     * Wraps the given {@link WifiListener} instance and executes it's methods on the Main Thread.
     *
     * <p>This mechanism allows us to no longer need a separate MainHandler and WorkHandler, which
     * were previously both performing work, while avoiding errors which occur from executing
     * callbacks which manipulate UI elements from a different thread than the MainThread.
     */
    private static class WifiListenerWrapper implements WifiListener {

        private final Handler mHandler;
        private final WifiListener mDelegatee;

        public WifiListenerWrapper(WifiListener listener) {
            mHandler = new Handler(Looper.getMainLooper());
            mDelegatee = listener;
        }

        @Override
        public void onWifiStateChanged(int state) {
            mHandler.post(() -> mDelegatee.onWifiStateChanged(state));
        }

        @Override
        public void onConnectedChanged() {
            mHandler.post(() -> mDelegatee.onConnectedChanged());
        }

        @Override
        public void onAccessPointsChanged() {
            mHandler.post(() -> mDelegatee.onAccessPointsChanged());
        }
    }

    public interface WifiListener {
    public interface WifiListener {
        /**
        /**
         * Called when the state of Wifi has changed, the state will be one of
         * Called when the state of Wifi has changed, the state will be one of
+2 −6
Original line number Original line Diff line number Diff line
@@ -281,8 +281,6 @@ public class WifiTrackerTest {
        final WifiTracker wifiTracker = new WifiTracker(
        final WifiTracker wifiTracker = new WifiTracker(
                mContext,
                mContext,
                mockWifiListener,
                mockWifiListener,
                true,
                true,
                mockWifiManager,
                mockWifiManager,
                mockConnectivityManager,
                mockConnectivityManager,
                mockNetworkScoreManager,
                mockNetworkScoreManager,
@@ -687,6 +685,7 @@ public class WifiTrackerTest {
     */
     */
    @Test
    @Test
    public void trackPasspointApWithPasspointDisabled() throws Exception {
    public void trackPasspointApWithPasspointDisabled() throws Exception {
        // TODO(sghuman): Delete this test and replace with a passpoint test
        WifiTracker tracker = createMockedWifiTracker();
        WifiTracker tracker = createMockedWifiTracker();


        // Add a Passpoint AP to the scan results.
        // Add a Passpoint AP to the scan results.
@@ -709,10 +708,7 @@ public class WifiTrackerTest {
        when(mockWifiManager.getConfiguredNetworks())
        when(mockWifiManager.getConfiguredNetworks())
                .thenReturn(new ArrayList<WifiConfiguration>());
                .thenReturn(new ArrayList<WifiConfiguration>());
        when(mockWifiManager.getScanResults()).thenReturn(results);
        when(mockWifiManager.getScanResults()).thenReturn(results);
        doThrow(new UnsupportedOperationException())
                .when(mockWifiManager).getMatchingWifiConfig(any(ScanResult.class));
        tracker.forceUpdate();
        tracker.forceUpdate();
        verify(mockWifiManager).getMatchingWifiConfig(any(ScanResult.class));
    }
    }


    @Test
    @Test
@@ -758,7 +754,7 @@ public class WifiTrackerTest {
        tracker.forceUpdate();
        tracker.forceUpdate();


        verify(mockWifiManager).getConnectionInfo();
        verify(mockWifiManager).getConnectionInfo();
        verify(mockWifiManager, times(2)).getConfiguredNetworks();
        verify(mockWifiManager, times(1)).getConfiguredNetworks();
        verify(mockConnectivityManager).getNetworkInfo(any(Network.class));
        verify(mockConnectivityManager).getNetworkInfo(any(Network.class));


        verify(mockWifiListener, never()).onAccessPointsChanged(); // mStaleAccessPoints is true
        verify(mockWifiListener, never()).onAccessPointsChanged(); // mStaleAccessPoints is true