【问题标题】:Connect to Wifi programmatically not working for Android Marshmallow?以编程方式连接到 Wifi 不适用于 Android Marshmallow?
【发布时间】:2016-11-15 18:18:44
【问题描述】:
String BACKSLASH = "\"";
String NETWROK_SECURITY_WEP = "WEP";
String NETWROK_SECURITY_NONE = "NONE";
String NETWROK_SECURITY_WPA = "WPA";
String NETWROK_SECURITY_WPA2 = "WPA2";
String NETWROK_SECURITY_WPA_WPA2 = "WPA/WPA2 PSK";
String NETWROK_ADDITIONAL_SECURITY_TKIP = "TKIP";
String NETWROK_ADDITIONAL_SECURITY_AES = "AES";
String NETWROK_ADDITIONAL_SECURITY_WEP = "WEP";
String NETWROK_ADDITIONAL_SECURITY_NONE = "NONE";
int FAILED_TO_ADD_NETWORK = -1;

WifiConfiguration conf = new WifiConfiguration();
String wifiName = sSid;
conf.SSID = BACKSLASH + wifiName + BACKSLASH;
String securityType = NETWROK_SECURITY_WPA_WPA2;

if (NETWROK_SECURITY_WEP.equalsIgnoreCase(securityType)) {
    conf.wepKeys[0] = pass;
    conf.wepTxKeyIndex = 0;
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
} else if (NETWROK_SECURITY_NONE.equalsIgnoreCase(securityType)) {
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
} else if (NETWROK_SECURITY_WPA.equalsIgnoreCase(securityType)
        || NETWROK_SECURITY_WPA2.equalsIgnoreCase(securityType)
        || NETWROK_SECURITY_WPA_WPA2.equalsIgnoreCase(securityType)) {
    conf.preSharedKey = BACKSLASH + pass + BACKSLASH;
    conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    conf.status = WifiConfiguration.Status.ENABLED;
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
}
String wlanAdditionalSecurity = "";
if (NETWROK_ADDITIONAL_SECURITY_TKIP.equalsIgnoreCase(wlanAdditionalSecurity)) {
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
} else if (NETWROK_ADDITIONAL_SECURITY_AES.equalsIgnoreCase(wlanAdditionalSecurity)) {
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
} else if (NETWROK_ADDITIONAL_SECURITY_WEP.equalsIgnoreCase(wlanAdditionalSecurity)) {
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
} else if (NETWROK_ADDITIONAL_SECURITY_NONE.equalsIgnoreCase(wlanAdditionalSecurity)) {
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.NONE);
}
WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
int res = wifiManager.addNetwork(conf);
wifiManager.disconnect();
wifiManager.reconnect();

if (true) {

    wifiManager.enableNetwork(res, true);

    wifiManager.saveConfiguration();
    wifiManager.setWifiEnabled(true);

    new AppPreferences(mContext).setPrefrenceLong("connectTime", Calendar.getInstance().getTimeInMillis());
}
if (res != -1) {

    setFalseOther(mm);
    notifyDataSetChanged();

    Intent i = new Intent(mContext, Connect.class);
    i.putExtra("networkName", mm.getName());
    i.putExtra("networkId", mm.getId());
    i.putExtra("AdminID", mm.getUserId());
    i.putExtra("networkConnection", "true");

    mContext.startActivity(i);

} else {

}

此代码用于连接 WiFi。它在 Android Lollipop 上运行良好,但我想以编程方式为 Marshmallow 设置配置。我已授予所有运行时权限和危险权限,但仍然没有帮助,也无法删除已保存的 WiFi 密码。如果有人为 Marshmallow 做过这件事,那将会很有帮助。

【问题讨论】:

    标签: android android-wifi android-6.0-marshmallow


    【解决方案1】:

    嗯...我们对 Marshmallow 中连接到 wifi 网络的代码进行了一些小改动... 我认为下面的代码会为你工作......

    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);
            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】:

      好吧,我想我已经找到了解决方案……经过测试并且工作正常……

      public boolean connectToWifi(String knownSSID,String key) {
      
          try{
              //If Wifi is not enabled, enable it
              if (!mWifiManager.isWifiEnabled()) {
                  Log.v(LOG_TAG, "Wifi is not enabled, enable it");
                  mWifiManager.setWifiEnabled(true);
              }
              WifiConfiguration config = new WifiConfiguration();
              config.SSID = convertToQuotedString(knownSSID);
              // if key is empty means it is open network-- I am considering like this
              if(key.isEmpty()){
                  config.allowedKeyManagement.set(KeyMgmt.NONE);
              } else {
                  config.preSharedKey = convertToQuotedString(key);
              }
      
              int networkId = mWifiManager.addNetwork(config);
              // it will return -1 if the config is already saved..
              if(networkId == -1){
                  networkId = getExistingNetworkId(config.SSID);
              }
              boolean es = mWifiManager.saveConfiguration();
      
              mWifiManager.disconnect();
              // giving time to disconnect here.
              Thread.sleep(3*1000);
              boolean bRet = mWifiManager.enableNetwork(networkId, true);
              mWifiManager.reconnect();
      
          } catch(InterruptedException e) {
      
          }
      

      }

      public 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;
      }
      

      【讨论】:

        【解决方案3】:

        从 Android 6 开始,您无法修改不是您创建的 wifi 配置。如果我记得,Android 6.0+ 也不再需要在 SSID 名称周围加上引号。

        这是我的流程 - 与您的略有不同: 添加网络() 保存配置() 启用网络()

        【讨论】:

        • 感谢韦恩的回复。实际上我的代码在棉花糖中不起作用。每当我尝试通过提供 SSID 和密码连接到其他网络时,它仍然连接到前一个网络。您能否在这里分享您的 POC,这会有所帮助。
        • 而且每当我尝试连接到其他网络时,我的应用程序都卡住了,我遇到了这个问题“无法 chmod(/sdcard/appName): android.system.ErrnoException: chmod failed: EPERM (Operation不允许)" ..
        【解决方案4】:

        我在 Android 6-Marshmallow 中遇到过此类错误。经过大量搜索和编码后,我设法通过添加如下额外权限来解决问题:

        &lt;uses-permission android:name="android.permission.WRITE_SETTINGS"/&gt;

        希望对新手有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-23
          • 1970-01-01
          • 2017-06-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多