【问题标题】:Android 6 : Connect to specific wifi network programmatically not workingAndroid 6:以编程方式连接到特定的 wifi 网络不起作用
【发布时间】:2016-02-21 17:17:35
【问题描述】:

我正在尝试通过提供 SSID 并使用 WifiManager 配置来连接到 wifi 网络。

基于此线程解决方案: How do I connect to a specific Wi-Fi network in Android programmatically?

调用重新连接方法。但什么也没发生(未连接)。

Android 版本 (6.0.1) 有什么用吗? 如果是,那么如何在 Android 6 上以编程方式执行网络连接?

【问题讨论】:

  • 你找到解决方案了吗?

标签: android wifi android-6.0-marshmallow wifimanager


【解决方案1】:

自 android Marshmallow 以来,您连接到 WiFi 网络的方式发生了一些变化。 下面的代码会对你有所帮助...如果您使用的是 Android 6.0 或低级版本...

public void connectToWifi(){
    try{
        WifiManager wifiManager = (WifiManager) super.getSystemService(android.content.Context.WIFI_SERVICE);
        WifiConfiguration wc = new WifiConfiguration();
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        wc.SSID = "\"NETWORK_NAME\"";
        wc.preSharedKey = "\"PASSWORD\"";
        wc.status = WifiConfiguration.Status.ENABLED;
        wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

        wifiManager.setWifiEnabled(true);
        int netId = wifiManager.addNetwork(wc);
        if (netId == -1) {
            netId = getExistingNetworkId(wc.SSID);
        }
        wifiManager.disconnect();
        wifiManager.enableNetwork(netId, true);
        wifiManager.reconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
private int getExistingNetworkId(String SSID) {
    WifiManager wifiManager = (WifiManager) super.getSystemService(Context.WIFI_SERVICE);
    List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
    if (configuredNetworks != null) {
        for (WifiConfiguration existingConfig : configuredNetworks) {
            if (existingConfig.SSID.equals(SSID)) {
                return existingConfig.networkId;
            }
        }
    }
    return -1;
}

并在Manifest文件中添加权限

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

【讨论】:

    【解决方案2】:

    使用 addNetwork 添加 wifi 配置,然后使用 enableNetwork 连接到它。

        WifiConfiguration wificonfiguration = new WifiConfiguration();
        StringBuffer stringbuffer = new StringBuffer("\"");
        stringbuffer.append((new StringBuilder(String.valueOf(HOTSPOT_NAME))).append("\"").toString());
        wificonfiguration.SSID = stringbuffer.toString();
        wificonfiguration.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
        wificonfiguration.allowedAuthAlgorithms.set(0);
        wificonfiguration.status = 2;
        wificonfiguration.preSharedKey = "\"" + HOTSPOT_PASSWORD + "\"";
    
        int networkId_ = wifi.addNetwork(wificonfiguration);
    
        if(networkId>-1){
    
               boolean status = wifi.enableNetwork(networkId_, true);
    
        }
    

    对于棉花糖:您的应用现在可以更改 WifiConfiguration 对象的状态,前提是您创建了这些对象。您不得修改或删除用户或其他应用创建的 WifiConfiguration 对象。 More info on Marshmallow

    【讨论】:

    • 嗨,那行解决了我的问题:wificonfiguration.allowedKeyManagement.set(KeyMgmt.WPA_PSK);现在连接正常。谢谢
    • @xanexpt:你有没有机会让它在 android 6 上工作?
    【解决方案3】:

    自 Android Lollipop 和 Marshmallow 以来,您连接到 WiFi 网络的方式发生了一些变化。有一篇很好的博客文章,介绍了如何在 Marshmallow 及以下版本上连接到 WiFi 网络

    http://www.intentfilter.com/2016/08/programatically-connecting-to-wifi.html

    这篇文章描述了当 WiFi 网络没有连接并且您想通过该网络发送流量(类似于强制门户)时的场景。但它也解释了完整的过程,适用于普通网络。您不会找到确切的代码,但它仍可能有助于您了解卡在哪里。

    【讨论】:

      【解决方案4】:

      您需要调用 WiFiManager 的 disconnect() 和 reconnect()。这对我有用:

                      WifiConfiguration conf = new WifiConfiguration();
                      conf.hiddenSSID = true;
                      conf.priority = 1000;
                      conf.SSID = "\"" + SSID + "\"";
                      conf.preSharedKey = "\""+Password+"\"";
                      conf.status = WifiConfiguration.Status.ENABLED;
                      conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
      
                      conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                      conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                      conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                      conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
      
                      conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                      conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
      
                      conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                      conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
      
                      conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                      conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                      int res = wifiManager.addNetwork(conf);
                      boolean es = wifiManager.saveConfiguration();
                      Log.d(TAG, "saveConfiguration returned " + es );
                      wifiManager.disconnect();
                      boolean bRet = wifiManager.enableNetwork(res, true);
                      Log.i(TAG, "enableNetwork bRet = " + bRet);
                      wifiManager.reconnect();
      

      【讨论】:

      • 但是我们怎么会发现它的连接,或者有任何密码错误?
      • 它仍然始终连接到任何以前最近的网络,无论您添加/选择哪个新 SSID。编辑:使用@Nishkarsh 的优先方法解决了这个问题
      【解决方案5】:

      这对我来说适用于 WPA 连接。 如果网络已经保存,则无需再次添加。

      private void connectToWifi(final String networkSSID, final String networkPassword) {
          int netID = -1;
          String confSSID = String.format("\"%s\"", networkSSID);
          String confPassword = String.format("\"%s\"", networkPassword);
      
          netID = getExistingNetworkID(confSSID, netID);
          /*
           * If ssid not found in preconfigured list it will return -1
           * then add new wifi
           */
          if (netID == -1) {
      
              Log.d(TAG,"New wifi config added");
      
              WifiConfiguration conf = new WifiConfiguration();
              conf.SSID = confSSID;
              conf.preSharedKey = confPassword;
              netID = wifiManager.addNetwork(conf);
      
          }
          wifiManager.disconnect();
          wifiManager.enableNetwork(netID, true);
          wifiManager.reconnect();
      }
      
      private int getExistingNetworkID (String confSSID, int netID){
          List<WifiConfiguration> wifiConfigurationList = wifiManager.getConfiguredNetworks();
          for (WifiConfiguration item : wifiConfigurationList){
              /*
                Find if the SSID is in the preconfigured list - if found get netID
               */
              if (item.SSID != null && item.SSID.equals(confSSID)){
      
                  Log.d(TAG, "Pre-configured running");
                  netID = item.networkId;
                  break;
              }
          }
          return netID;
      }
      

      【讨论】:

        【解决方案6】:

        这是连接 wifi 的正确方法,而且这个非常短的无样板代码

         fun connectToWifi(ssid: String, password: String) {
            val connManager = context!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            val wifiConfiguration = WifiConfiguration()
            wifiConfiguration.SSID = String.format("\"%s\"", ssid)
            wifiConfiguration.preSharedKey = String.format("\"%s\"", password)
            wifiManager = context!!.getSystemService(Context.WIFI_SERVICE) as WifiManager
            val netId: Int = wifiManager.addNetwork(wifiConfiguration)
            wifiManager.disconnect()
            wifiManager.enableNetwork(netId, true)
            wifiManager.reconnect()
            val config = WifiConfiguration()
            config.SSID == "\"\"" + ssid + "\"\""
            config.preSharedKey == "\"\"" + password + "\"\""
            wifiManager.addNetwork(config)
        }
        

        【讨论】:

          【解决方案7】:

          试试这个并享受:

           int res = mWifiManager.addNetwork(wifiConfiguration);
                                                  if (res == -1) {
                                      // Get existed network id if it is already added to WiFi network
                                      res = getExistingNetworkId(wifiConfiguration.SSID);
                                      Log.d(TAG, "getExistingNetwrkId: " + res);
                                  }
          
                private int getExistingNetworkId(String SSID) {
                      List<WifiConfiguration> configuredNetworks = mWifiManager.getConfiguredNetworks();
                      if (configuredNetworks != null) {
                          for (WifiConfiguration existingConfig : configuredNetworks) {
                              if (SSID.equalsIgnoreCase(existingConfig.SSID)) {
                                  return existingConfig.networkId;
                              }
                          }
                      }
                      return -1;
                  }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-12-26
            • 2016-05-02
            • 2013-04-30
            • 2023-01-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多