以编程方式连接wifi

时间:2017-11-28 08:59:48

标签: android network-programming android-wifi wifimanager

我是Android网络编程的新手。我正在开发一个应用程序,我想以编程方式启用和连接wifi。我搜索了很多教程但是我得到的代码与我在下面写的代码相同。但就我而言,我总是得到 res -1

    WifiConfiguration wifiConf = new WifiConfiguration();
    wifiConf.SSID = '\"' + bestHotspot.SSID + '\"';
    wifiConf.hiddenSSID = true;
    wifiConf.status = WifiConfiguration.Status.ENABLED;
    wifiConf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    wifiConf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    wifiConf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    int res = wPoint.wifiManager.addNetwork(WifiConf);
    Log.d("WPoint WIFI", "add Network returned " + res);
    boolean b = wPoint.wifiManager.enableNetwork(res, true);
    Log.d("WPoint WIFI", "enableNetwork returned " + b);

1 个答案:

答案 0 :(得分:0)

您需要像这样创建WifiConfiguration实例:

String networkSSID = "test";
String networkPass = "pass";

WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";   
// Please note the quotes.String should contain ssid in quotes
Then, for WEP network you need to do this:

conf.wepKeys[0] = "\"" + networkPass + "\""; 
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 
For WPA network you need to add passphrase like this:

conf.preSharedKey = "\""+ networkPass +"\"";
For Open network you need to do this:

conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
Then, you need to add it to Android wifi manager settings:

WifiManager wifiManager = 
(WifiManager)context.getSystemService(Context.WIFI_SERVICE); 
wifiManager.addNetwork(conf);
And finally, you might need to enable it, so Android connects to it:

List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
    if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
         wifiManager.disconnect();
         wifiManager.enableNetwork(i.networkId, true);
         wifiManager.reconnect();               

         break;
    }           
 }
UPD: In case of WEP, if your password is in hex, you do not need to 
 surround it with quotes.