我有一些代码应该通过意图中的额外传递的 SSID 并连接到它,目前它只是将我传递给它的那些设置为 disabled。所有试图通过的 SSID 之前都已连接。我不确定它的原因是否已经存在具有 SSID 的网络配置,但它可能与它有关...
package com.wt.checkin;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
public class WifiSwitcher extends BroadcastReceiver {
@SuppressWarnings("static-access")
@Override
public void onReceive(Context arg0, Intent arg1) {
Bundle extras = arg1.getExtras();
WifiManager wifiMan = (WifiManager) arg0
.getSystemService(Context.WIFI_SERVICE);
if (wifiMan.getWifiState() == 1) {
wifiMan.setWifiEnabled(true);
try {
Thread.currentThread().sleep(2500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
WifiConfiguration tmpConfig = new WifiConfiguration();
tmpConfig.SSID = extras.getString("SSID");
tmpConfig.status = WifiConfiguration.Status.ENABLED;
int netId = wifiMan.addNetwork(tmpConfig);
wifiMan.enableNetwork(netId, true);
}
}
这是工作代码:
package com.wt.checkin;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
public class WifiSwitcher extends BroadcastReceiver {
@SuppressWarnings("static-access")
@Override
public void onReceive(Context arg0, Intent arg1) {
Bundle extras = arg1.getExtras();
WifiManager wifiMan = (WifiManager) arg0
.getSystemService(Context.WIFI_SERVICE);
if (wifiMan.getWifiState() == 1) {
wifiMan.setWifiEnabled(true);
try {
Thread.currentThread().sleep(2500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}**
WifiConfiguration Config = new WifiConfiguration();
WifiInfo Info = wifiMan.getConnectionInfo();
String SSID = extras.getString("SSID");
Config.SSID = "\"" + SSID+"\"";
wifiMan.addNetwork(Config);
List<WifiConfiguration> list = wifiMan.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + SSID + "\"")) {
wifiMan.disconnect();
wifiMan.enableNetwork(i.networkId, true);
wifiMan.reconnect();
break;
}
}
}
}