title: Android WifiManager.addNetwork() returns -1
body: <p>I am writing an android app which will connect to a specific WPA access point, when connected, it will issue a http call. It will not save the network config.
  I have read almost every post on stack overflow on connecting to wifi network but can't find the answer which works for me. Here is the code I am using to connect..</p>
  
  <pre><code>    WifiConfiguration wc = new WifiConfiguration();
      wc.allowedAuthAlgorithms.clear();
      wc.allowedGroupCiphers.clear();
      wc.allowedPairwiseCiphers.clear();
      wc.allowedProtocols.clear();
      wc.allowedKeyManagement.clear();
      wc.SSID = "\"".concat("&lt;ssid&gt;").concat("\"");
      wc.preSharedKey = "\"".concat("&lt;password&gt;").concat("\"");
      wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
      wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
      wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
      wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
      wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
      wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
      wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
      wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); // For WPA2
      wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); // For WPA
      wc.priority = 0;
      //wc.hiddenSSID = true;
      wc.status = WifiConfiguration.Status.ENABLED;
      // connect to and enable the connection
      WifiManager wifiManager = (WifiManager) getSystemService(this.WIFI_SERVICE);
      int netId = wifiManager.addNetwork(wc);
      boolean wifiEnabled = wifiManager.enableNetwork(netId, true);
      wifiManager.setWifiEnabled(true);
      Log.d("opener", "addNetwork returned " + netId);
      if (netId &gt; 0) {
          wifiId = netId;
      }
  </code></pre>
  
  <p>However netId is always -1. I have tried it on two different phones (ICS:HTC Rezound  and GingerBread:Motorola DroidX). Both show exactly same results.
  What am I doing wrong?</p>
  
  <p>Edit: I tried same code with WPA2 access point and got very weird results. When this code was run, first time it would return -1, but if I call same method second time with a delay of 1 second, it would return valid netId. So the questions are</p>
  
  <ol>
  <li>why does above code not connect to wpa ?</li>
  <li>in wpa2, why do I need to call above method twice to get connected ? Edit: I observed that I had to connect multiple times to get connected. Sometimes it would take 3-4 times to connect. So for now I am looping until adding config returns >0 id.</li>
  </ol>