通过programsticly向android设备添加新网络

时间:2017-06-22 20:27:00

标签: java android networking connection wifi

我需要使用以下代码以编程方式连接到我的设备的新wifi网络: `

 try 
{
    String ssid = "\"" + SSID + "\"";
    String pass = "\"" + Pass + "\"";

    for (ScanResult result : results) 
    {
        if (result.SSID.equals(SSID)) 
        {  
            String security = getScanResultSecurity(result);
            if (security.equals("PSK")) {

                   WifiConfiguration con = new WifiConfiguration();
                   con.SSID = ssid;
                   AlertDialog a = new AlertDialog.Builder(MainActivity.this).create();
                   a.setMessage("in");
                   a.show();
                   con.preSharedKey = pass;
                   con.hiddenSSID = true;
                    con.status = WifiConfiguration.Status.ENABLED;
                    con.allowedGroupCiphers.set(WifiConfiguration.Grou  pCipher.TKIP);
                    con.allowedGroupCiphers.set(WifiConfiguration.Grou  pCipher.CCMP);
                    con.allowedKeyManagement.set(WifiConfiguration.Key  Mgmt.WPA_PSK);
                    con.allowedPairwiseCiphers.set(WifiConfiguration.P  airwiseCipher.TKIP);
                    con.allowedPairwiseCiphers.set(WifiConfiguration.P  airwiseCipher.CCMP);
                    con.allowedKeyManagement.set(WifiConfiguration.Key  Mgmt.NONE);
                    con.allowedProtocols.set(WifiConfiguration.Protoco  l.RSN);
                    con.allowedProtocols.set(WifiConfiguration.Protoco  l.WPA);

                    int ntid = wifimanager.addNetwork(con);

                    wifimanager.disconnect();
                    wifimanager.enableNetwork(ntid,true);
                    wifimanager.reconnect();
                    boolean b = wifimanager.saveConfiguration();
                    if (ntid != -1 && b) {

                        AlertDialog a2 = new AlertDialog.Builder(MainActivity.this).create();
                        a2.setMessage("saved");
                        a2.show();
                    }
                }

        }
    }
    catch (Exception ex) {
        AlertDialog a = new AlertDialog.Builder(MainActivity.this).create();
        a.setMessage(ex.getMessage());
        a.show();
    }

`
但我无法将网络添加到我的设备 问题是网络配置无法添加到网络 我不明白为什么不工作没有erorr但没有结果 请帮帮我

1 个答案:

答案 0 :(得分:0)

您应该向清单(和运行时权限)添加权限

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />