我有一台服务器是另一个Android设备。服务器启动一个wifi热点。 在我的客户端上,我尝试自动连接到热点。
我在onStart()的新线程中调用此函数:
private void enableWifi(){
if(!wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(true);
Log.i("Wifi", "Wifi enabled");
}
if(getNetworkId() == -1){
addNetwork();
}
while(!isConnected(context)){
wifiManager.disconnect();
wifiManager.enableNetwork(getNetworkId(),true);
wifiManager.reconnect();
Log.i("Wifi", "Connecting to Hotspot");
try {
Thread.sleep(TIMEOUT);
} catch (InterruptedException e) {
Log.e("Wifi", "Thread interrupted: " + e);
}
}
Log.i("Wifi", "Connected to Hotspot");
}
private int getNetworkId(){
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + wifiName + "\"")) {
return i.networkId;
}
}
return -1;
}
private void addNetwork(){
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\\" + wifiName + "\\";
wifiConfiguration.preSharedKey = "\\" + wifiPassword + "\\";
wifiManager.addNetwork(wifiConfiguration);
Log.i("Wifi", "Added Hotspot to configured Networks");
}
wifiManager.addNetwork()返回-1
答案 0 :(得分:4)
看起来您的问题是您在SSID和密码中使用反斜杠而不是引号。
试试这个:
wifiConfiguration.SSID = "\"" + wifiName + "\"";
wifiConfiguration.preSharedKey = "\"" + wifiPassword + "\"";