我有一些代码应该通过意图中的额外内容传递SSID并连接到它,目前它只是将我传递给它的那些设置为禁用。我试图通过的所有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;
}
}
}
}
答案 0 :(得分:1)
对于遇到类似问题的其他人,我想发布此相关问题:How do I connect to a specific Wi-Fi network in Android programmatically?
OP似乎正在做一些非常相似的事情,我注意到与以下方面有所区别:
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wm.disconnect(); //not in OP
wm.enableNetwork(i.networkId, true);
wm.reconnect(); //not in OP
break;
}
}
我标记了我认为应该添加的行。看起来您必须以非常特定的方式格式化SSID,这在其他SO线程中有概述。