如何根据信号强度按升序对getScanResults()列表进行排序?

时间:2013-06-24 21:21:24

标签: android sorting wifi signals

我按照以下代码将scanresult存储到列表中:

List<ScanResult> results = wifi.getScanResults();
             sb = new StringBuilder();
            try
            {
                for(int i = 0; i < results.size(); i++){
                    sb.append(new Integer(i+1).toString() + ".");
                    sb.append("SSID:-").append((results.get(i).SSID).toString());
                    sb.append("BSSID:-").append((results.get(i).BSSID).toString());
                    sb.append("Level:-").append((results.get(i).level));
                    sb.append("Frequency:-").append((results.get(i).frequency));
                    sb.append("\n\n");
                }
                textStatus.setText("");
                textStatus.append("\n\n\n");
                textStatus.append(sb);
            }

我想根据信号强度(级别)对此结果进行排序,因此我创建了一个具有数据级别和Mac的2D数组。所以我为此编写了代码:

String rssi[][]=new String[2][results.size()];
for(int i = 0; i <results.size(); i++){
         rssi[0][i] = String.valueOf(results.get(i).level);
         rssi[1][i]= results.get(i).BSSID;
}

StringBuilder tmp=new StringBuilder();
Arrays.sort(rssi,new Comparator<String[]>() {
       @Override
       public int compare(String[] str1, String[] str2) {
           final String lv1= str1[0];
           final String lv2= str2[0];
           return lv1.compareTo(lv2);
       }
);

基于上面的代码,我期望按排序顺序rssi[][],但它没有发生......

1 个答案:

答案 0 :(得分:9)

试试这个

     Comparator<ScanResult> comparator = new Comparator<ScanResult>() {
        @Override
        public int compare(ScanResult lhs, ScanResult rhs) {
            return (lhs.level <rhs.level ? -1 : (lhs.level==rhs.level ? 0 : 1));
        }
     }
     List<ScanResult> results = wifi.getScanResults();
     Collections.sort(results, comparator);

     //Here your list is sorted by level