我试图在我的设备上设置wifi扫描。这是我正在使用的一段代码:
public void start() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
fragmentActivity.registerReceiver(mWifiScanReceiver, intentFilter);
boolean test = wifiManager.startScan();
//the rest of the code
}
和:
private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent intent) {
// This condition is not necessary if you listen to only one action
if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
getSSIDs();
}
}
private void getSSIDs() {
if(!wifiManager.isWifiEnabled()){
Log.i(TAG, "Enabling wi-fi...");
if (wifiManager.setWifiEnabled(true)) {
Log.i(TAG, "Wi-fi enabled");
} else {
Log.w(TAG, "Wi-fi could not be enabled!");
return;
}
}
int count = 0;
while(!wifiManager.isWifiEnabled()){
if(count >= 10){
Log.i(TAG, "Took too long to enable wi-fi, quitting");
return;
}
Log.i(TAG, "Still waiting for wi-fi to enable...");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
List<ScanResult> networkList = wifiManager.getScanResults();
for (ScanResult s : networkList) {
if (s.SSID.length() > 0 && !ssids.contains(s.SSID)) {
ssids.add(s.SSID);
}
}
}
};
问题是当我第一次运行程序时扫描结果为空。它可能是并发问题,因为第二次设置扫描。你知道如何正确地做到这一点吗?