Android网络未添加到Wifi列表

时间:2016-01-13 13:07:18

标签: java android

我正在使用一个功能将网络添加到wifi列表中:

 public void connecttowifi(String networkSSID, String networkPass) {
        try {
            WifiConfiguration conf = new WifiConfiguration();
            conf.SSID = "\"" + networkSSID + "\"";
            conf.preSharedKey = "\""+ networkPass +"\"";
            conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
            wifiManager.addNetwork(conf);
            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;
                }
            }

        } catch (Exception ex) {
            Log.d("Wifi exception is",ex.toString());
        }
    }

在MainActivity.java中我写道:

 connecttowifi("333","333");

网络没有添加,没有发现异常,有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

也许你可以登录循环

打印所有ConfiguredNetworks的SSID

我想这就是问题所在:

class IterableIterable<T> implements Iterable<T> {

  private final Iterable<? extends Iterable<T>> i;

  public IterableIterable(Iterable<? extends Iterable<T>> i) {
    this.i = i;
  }

  @Override
  public Iterator<T> iterator() {
    return new IIT();
  }

  private class IIT implements Iterator<T> {

    // Pull an iterator.
    final Iterator<? extends Iterable<T>> iit = i.iterator();
    // The current Iterator<T>
    Iterator<T> it = null;
    // The current T.
    T next = null;

    @Override
    public boolean hasNext() {
      boolean finished = false;
      while (next == null && !finished) {
        if (it == null || !it.hasNext()) {
          if (iit.hasNext()) {
            it = iit.next().iterator();
          } else {
            // All over when we've exhausted the list of lists.
            finished = true;
          }
        }
        if (it != null && it.hasNext()) {
          // Get another from the current list.
          next = it.next();
        }
      }
      return next != null;
    }

    @Override
    public T next() {
      T n = next;
      next = null;
      return n;
    }

  }

}

起飞&#34; \&#34;到下面

if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\""))
希望这有帮助!!

答案 1 :(得分:0)

conf.SSID = "\"" + networkSSID + "\"";
conf.preSharedKey = "\""+ networkPass +"\"";

networkSSID和networkPass是String的实例,不需要转义

conf.SSID =  networkSSID ;
conf.preSharedKey = networkPass;