我使用WifiManager扫描可用的wifi,
mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mainWifi.startScan();
我可以获得网络列表。
但是当我在这种情况下尝试连接到Speecific wifi SSID String hotspot="some_wifi_name";
时,它会将热点添加到WifiConfig,但之后它会在连接时进入无限循环并再次扫描结果,循环继续。
以下是Broadcast Receiver
我用来连接我的SSID,
class WifiReceiver extends BroadcastReceiver {
ArrayList<String> connections = new ArrayList<String>();
WifiConfiguration conf;
public void onReceive(Context c, Intent intent) {
WifiManager wifiManager = (WifiManager) c
.getSystemService(Context.WIFI_SERVICE);
List<ScanResult> wifiList;
wifiList = mainWifi.getScanResults();
for (int i = 0; i < wifiList.size(); i++) {
String ssid = wifiList.get(i).SSID;
int rssi = wifiList.get(i).level;
Log.d("SSID: ", "" + wifiList.get(i).SSID.toString()
+ " signal: " + rssi);
if (ssid != null && ssid.equals(hotspot)) {
Log.d("SSID Hotspot: ",
"" + wifiList.get(i).SSID.toString());
conf = new WifiConfiguration();
conf.SSID = "\"" + hotspot + "\"";
conf.allowedKeyManagement
.set(WifiConfiguration.KeyMgmt.NONE);
wifiManager.addNetwork(conf);
}
}
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
loops:
for (WifiConfiguration j : list) {
if (j.SSID != null && j.SSID.equals("\"" + hotspot + "\"")) {
Log.d("Config", "" + j.SSID);
wifiManager.disconnect();
wifiManager.enableNetwork(j.networkId, true);
wifiManager.reconnect();
}
}
}
}
为什么它在获得所需的SSID后再次扫描wifi并进入无限循环,哪里是错误的。
答案 0 :(得分:1)
此代码可让您连接到具体的SSID:
public void connectToWifi(String ssid) {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + ssid + "\""; // Please note the quotes.
// String should contain
// ssid in quotes
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiMgr.addNetwork(conf);
Log.d(TAG, ssid+" added");
List<WifiConfiguration> list = wifiMgr.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {
wifiMgr.disconnect();
wifiMgr.enableNetwork(i.networkId, true);
wifiMgr.reconnect();
Log.d(PluginConstants.LOG_TAG, "conneting to: ssid");
break;
}
}
}
答案 1 :(得分:1)
将A SSID添加到配置列表后,我取消注册了BroadcastReceiver
。
所以在下次扫描后,该功能将无法执行。