我正在尝试保持各种wifi扫描的BSSID和信号强度。但是,我只关心最近的四次扫描。当它扫描四次然后奇怪的事情开始发生时它工作正常,并且就像在第6次扫描后每次扫描的大小(结果的数量)是相同的。这段代码有问题吗?我将结果存储在一个集合列表中(尽管处理数据时我只保留了最近的四个集合)
public class MainActivity extends Activity {
List<HashSet<Pair>> addresses = new ArrayList<HashSet<Pair>>();
List <ScanResults> results;
...
@Override
public void onCreate(Bundle savedInstanceState) {
//This whole part of the code is run once every ten seconds through use of a timer
mainWifi.startScan();
results = mainWifi.getScanResults();
int entry = addresses.size();
if (entry == 4) { // already has 4 addresses
addresses.remove(0); // remove the
// oldest
// set
entry = 3;
}
addresses.add(entry, new HashSet<Pair>());
for (int i = 0; i < results.size(); i++) {
addresses.get(entry).add(new Pair(results.get(i).BSSID,results.get(i).level));
}
}
答案 0 :(得分:2)
<强>更新强>
我建议在SCAN_RESULTS_AVAILABLE_ACTION完成存储您最新的Wifi列表时等待广播的WifiManager.startScan()意图。
我还建议使用for-each循环并创建对最新List的引用,而不是使用get()。在您的活动中:
List<List<Pair<String, Integer>>> addresses = new ArrayList<List<Pair<String, Integer>>>();
List<Pair<String, Integer>> list;
...
public void newWifiResults() {
list = new ArrayList<Pair<String, Integer>>();
if(addresses.size() > 3) {
addresses.remove(0);
results = mainWifi.getScanResults();
for(ScanResult result : results)
list.add(new Pair<String, Integer>(result.BSSID, result.level));
addresses.add(list);
// call mainWifi.startScan() again after a delay
}
你在BroadcastReceiver中捕获SCAN_RESULTS_AVAILABLE_ACTION
:
public class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// We are only listening for one type of intent, no verifying necessary
newWifiResults();
}
}
如果你把它作为嵌套/子类放在Activity中,onReceive()将很容易调用newWifiActivity()。
最后,您需要在“活动:
”中创建对接收器的引用private WifiReceiver wifiReceiver = new WifiReceiver();
在onCreate()或onResume()中,注册接收器:
registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
在匹配方法(onDestroy()或onPause())中取消注册你的接收者:
unregisterReceiver(wifiReceiver);
这涉及更多,但只有在从startScan()返回新结果集时才会运行代码。