0

I was looking on stackoverflow on how to sort a list based on signal strength (referred to as level in the WifiManager library). I saw that you can use the function Collection.sort(). However, I am confused where I put the fact that I want to sort the list via level, where the highest number is at beginning and the lowest is at the bottom.

As you can see it returns a few things in each object: https://developer.android.com/reference/android/net/wifi/ScanResult.html I am not that advanced, but I know I can access the level by doing something like this

for (int i=0; i < scanList.size(); i++) {
    System.out.println(scanList.get(i).level); // Prints the level for each access point
}

WifiManager myWifiManager;
myWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
myWifiManager.startScan();
List<ScanResult> scanList = myWifiManager.getScanResults();
Collections.sort(scanList);
Diego Malone
  • 1,044
  • 9
  • 25
Jake
  • 43
  • 5

1 Answers1

2

you need to pass a comparison logic to Collection sort;

class Signal_Strength_Comparator implements Comparator<ScanResult> {
    @Override
    public int compare(ScanResult scan0, ScanResult scan1) {
        return scan0.level-scan1.level;
    }
}

now pass this to Collection.sort:

WifiManager myWifiManager;
myWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
myWifiManager.startScan();
List<ScanResult> scanList = myWifiManager.getScanResults();
Collections.sort(scanList,new Signal_Strength_Comparator());
kamyar haqqani
  • 748
  • 6
  • 19