Android wifi 连接上网

最近公司在做Wi-Fi连接上网,之间没做过这方面的东西,查了好多资料终于搞明白了一些东西,这里做一些记录,下面是我的Wi-Fi连接测试代码工具类,这里贴出来方便以后查阅,也希望能帮到一些遇到同样需求的小伙伴。

import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiEnterpriseConfig;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import java.util.List;

public class WifiAutoConnectManager {

   private static final String TAG = WifiAutoConnectManager.class
         .getSimpleName();

   WifiManager wifiManager;
   Handler mHandler;

   public void sendMsg(String info) {
      if (mHandler != null) {
         Message msg = new Message();
         msg.obj = info;
         mHandler.sendMessage(msg); 
      } else {
         Log.e("wifi", info);
      }
   }


   public enum WifiCipherType {
      WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
   }

   
   public WifiAutoConnectManager(WifiManager wifiManager) {
      this.wifiManager = wifiManager;
   }

    
   public void connect(String ssid,String userName, String password, WifiCipherType type) {
      Thread thread = new Thread(new ConnectRunnable(ssid,userName, password, type));
      thread.start();
   }

     
   private WifiConfiguration isExsits(String SSID) {
      List<WifiConfiguration> existingConfigs = wifiManager
            .getConfiguredNetworks();
      for (WifiConfiguration existingConfig : existingConfigs) {
         if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
            return existingConfig;
         }
      }
      return null;
   }

   private WifiConfiguration createWifiInfo(String SSID, String Password,
         WifiCipherType Type) {
      WifiConfiguration config = new WifiConfiguration();
      config.allowedAuthAlgorithms.clear();
      config.allowedGroupCiphers.clear();
      config.allowedKeyManagement.clear();
      config.allowedPairwiseCiphers.clear();
      config.allowedProtocols.clear();
      config.SSID = "\"" + SSID + "\"";

      System.out.println("查看config wepkey 内容:"+config.wepKeys);

      // nopass
      if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
         // config.wepKeys[0] = "";
         config.allowedKeyManagement.set(KeyMgmt.NONE);
         // config.wepTxKeyIndex = 0;
      }
      // wep
      if (Type == WifiCipherType.WIFICIPHER_WEP) {
         if (!TextUtils.isEmpty(Password)) {
            if (isHexWepKey(Password)) {
               config.wepKeys[0] = Password;
            } else {
               config.wepKeys[0] = "\"" + Password + "\"";
            }
         }
         config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
         config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
         config.allowedKeyManagement.set(KeyMgmt.NONE);

         config.wepTxKeyIndex = 0;
      }

      // wpa
      if (Type == WifiCipherType.WIFICIPHER_WPA) {
         config.preSharedKey = "\"" + Password + "\"";
         config.hiddenSSID = true;
         config.allowedAuthAlgorithms
               .set(AuthAlgorithm.OPEN);
         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

         config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);// 直连Wi-Fi
         //config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
         //config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
         config.allowedPairwiseCiphers
               .set(WifiConfiguration.PairwiseCipher.TKIP);
          
         // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
         config.allowedPairwiseCiphers
               .set(WifiConfiguration.PairwiseCipher.CCMP);

         config.status = WifiConfiguration.Status.ENABLED;
      }
      return config;
   }

    
   private boolean openWifi() {
      boolean bRet = true;
      if (!wifiManager.isWifiEnabled()) {
         bRet = wifiManager.setWifiEnabled(true);
      }
      return bRet;
   }

   class ConnectRunnable implements Runnable {
      private String ssid;

      private String password;

      private WifiCipherType type;

      private String userName;

      public ConnectRunnable(String ssid,String userName, String password, WifiCipherType type) {
         this.ssid = ssid;
         this.password = password;
         this.type = type;
         this.userName = userName;
      }

      @Override
      public void run() {
         try {
            
            openWifi();
            sendMsg("opened");
            Thread.sleep(200);
             
            while (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
               try {
                   
                  Thread.sleep(100);
               } catch (InterruptedException ie) {
               }
            }

            WifiConfiguration wifiConfig = createWifiInfo(ssid, password,type);
            //WifiConfiguration wifiConfig = WPAConfiguration.setWifiConfigurations(ssid,userName,password);

            //
            if (wifiConfig == null) {
               sendMsg("wifiConfig is null!");
               return;
            }

            WifiConfiguration tempConfig = isExsits(ssid);

            if (tempConfig != null) {
               wifiManager.removeNetwork(tempConfig.networkId);
            }

            int netID = wifiManager.addNetwork(wifiConfig);
            boolean enabled = wifiManager.enableNetwork(netID, true);
            sendMsg("enableNetwork status enable=" + enabled);
            boolean connected = wifiManager.reconnect();
            sendMsg("enableNetwork connected=" + connected);
            sendMsg("���ӳɹ�!");
         } catch (Exception e) {
            // TODO: handle exception
            sendMsg(e.getMessage());
            e.printStackTrace();
         }
      }
   }

   private static boolean isHexWepKey(String wepKey) {
      final int len = wepKey.length();

      // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
      if (len != 10 && len != 26 && len != 58) {
         return false;
      }

      return isHex(wepKey);
   }

   private static boolean isHex(String key) {
      for (int i = key.length() - 1; i >= 0; i--) {
         final char c = key.charAt(i);
         if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a'
               && c <= 'f')) {
            return false;
         }
      }

      return true;
   }
}
连接Wi-Fi的工具类,上面的代码,当我调用的时候,是这样写的,如下:

WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiAutoConnectManager wac = new WifiAutoConnectManager(wifiManager);
//连接Wi-Fi
wac.connect(wifissid,userName,password,
        password.equals("") ? WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS: WifiAutoConnectManager.WifiCipherType.WIFICIPHER_WPA);
其实回过头来看这个功能其实主要代码是创建正确的 WifiConfiguration 对象,然后添加到 
int netID = wifiManager.addNetwork(wifiConfig);
boolean enabled = wifiManager.enableNetwork(netID, true); 
这里再说另外一种情况,需要用用户名和密码方式连接Wi-Fi的情况,这是就需要引用Android的另外一个WifiEnterpriseConfig:

 WifiConfiguration config = new WifiConfiguration();
 config.allowedAuthAlgorithms.clear();
 config.allowedGroupCiphers.clear();
 config.allowedKeyManagement.clear();
 config.allowedPairwiseCiphers.clear();
 config.allowedProtocols.clear();
 config.SSID = "\"" + SSID + "\"";
 config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
 config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
 WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
 enterpriseConfig.setIdentity(username);
 enterpriseConfig.setPassword(password);
 enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.PEAP);
 config.enterpriseConfig = enterpriseConfig;
还是以上面代码为例说明,需要将WifiConfiguration的创建对象稍做修改,修改createWifiInfo方法的这个if条件中的代码同时传入对应Wi-Fi的用户名和密码:

// wpa
        if (Type == WifiAutoConnectManager.WifiCipherType.WIFICIPHER_WPA) {
            //////////////////////////////////////
            config.allowedAuthAlgorithms.clear();
            config.allowedGroupCiphers.clear();
            config.allowedKeyManagement.clear();
            config.allowedPairwiseCiphers.clear();
            config.allowedProtocols.clear();
            config.SSID = "\"" + SSID + "\"";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);

            WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
            enterpriseConfig.setIdentity(username);
            enterpriseConfig.setPassword(Password);
            enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.PEAP);
            config.enterpriseConfig = enterpriseConfig;

            config.status = WifiConfiguration.Status.ENABLED;
        }



发布了175 篇原创文章 · 获赞 35 · 访问量 28万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览