连接到指定的可用wifi网络

时间:2011-04-25 06:04:08

标签: android android-wifi wifimanager

从我的应用程序中,我可以在设备中打开/关闭WIFI并能够扫描可用的网络,但我无法连接到指定的可用网络。这是我正在使用的代码:

 if(wifi.getWifiState()==wifi.WIFI_STATE_DISABLED)
        { 
            wifi.setWifiEnabled(true);

        }
        if(wifi.startScan())
        {
            //ls=(ArrayAdapter<ScanResult>) wifi.getScanResults();
            ls=wifi.getScanResults();

            Log.e("",ls.get(0).toString());
            for(int i=0;i<ls.size();i++)
            {   Log.e("VALUE"," "+ls.get(i).toString());
                Log.e("",""+ls.get(i).SSID);
                if(ls.get(i).SSID.equalsIgnoreCase("SPECTRUM-GREEN"))
                {
                    Log.e("","SPectrum GREEN FOUND.....");

            try{ 
                String ssid="\""+ls.get(i).SSID+"\"";
                Log.e("SSId"," "+ssid);
                config.SSID=ssid;
            }catch(Exception e){Log.e("","Error : "+e.toString());}

            config.preSharedKey="\"password\"";
            config.status=WifiConfiguration.Status.ENABLED;

            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

            int res=wifi.addNetwork(config);
                    Log.e("ENABLE ",""+wifi.enableNetwork(res, false));

                    break;
                }
            }

3 个答案:

答案 0 :(得分:1)

虽然这是一个老问题,如果有人遇到这个,以下帮助我:

void connect (String ssidName) {
    boolean result = false;
    List<WifiConfiguration> arraylist = wifiManager.getConfiguredNetworks();
    for (WifiConfiguration wifiConfiguration : arraylist) {
        String wifiConfigSSID = wifiConfiguration.SSID.replace("\"", "");
        if (wifiConfigSSID.equals(ssidName)) {
            result = wifiManager.enableNetwork(wifiConfiguration.networkId, true);
            break;
        }
    }
}

如果网络已经可用,则无需提供各种参数,包括密码。

答案 1 :(得分:0)

只是评论。您是否尝试连接ad hoc?我读过的“普通”Android手机无法做到这一点......

答案 2 :(得分:0)

您必须禁用其他网络:

wifi.enableNetwork(res, true);