安卓連接指定wifi

安卓連接指定的wifi,廢話不說,請看代碼。

使用

WifiUtil mWifiUtil = new WifiUtil(this);
mWifiUtil.OpenWifi();
boolean connectNet = mWifiUtil.addNetWork("howard", "12345678", 3);

工具類

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.util.List;

/**
 * wifi設置工具類
 * 
 */
public class WifiUtil {
   // 定義WifiManager對象
   private WifiManager mWifiManager;
   private DhcpInfo dhcpInfo;
   private List<WifiConfiguration> mWifiConfigurations;
   private ConnectivityManager mConnectivityManager;
   public WifiManager getmWifiManager() {
      return mWifiManager;
   }

   // 定義WifiInfo對象
   private WifiInfo mWifiInfo;
   Context context;
   // 掃描出的網絡連接列表
   private List<ScanResult> mWifiList;

   // 構造器
   public WifiUtil(Context context) {
      // 取得WifiManager對象
      mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
      // 取得WifiInfo對象
      mWifiInfo = mWifiManager.getConnectionInfo();
      dhcpInfo  = mWifiManager.getDhcpInfo();
      mWifiConfigurations=mWifiManager.getConfiguredNetworks();
      mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
      this.context = context;

   }
   public void startScan(){
      mWifiManager.startScan();
      mWifiList=mWifiManager.getScanResults();
   }
   /**
    * 獲取掃描到的wifi列表
    */
   public List<ScanResult> getWifiList(){
      return mWifiList;
   }
   // 得到MAC地址
   public String GetMacAddress() {
      return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
   }

   // 得到接入點的BSSID
   public String GetBSSID() {
      return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
   }

   // 得到接入點的SSID
   public String GetSSID() {
      return (mWifiInfo == null) ? "NULL" : mWifiInfo.getSSID();
   }

   // 得到接入點的IP地址
   public String getIPAddress() {
      return (mWifiInfo == null) ? "NULL" : intToIp(dhcpInfo.ipAddress);
   }

   // 得到接入點的子網掩碼
   public String getNetMask() {
      return (mWifiInfo == null) ? "NULL" : intToIp(dhcpInfo.netmask);
   }

   // 關閉WIFI
   public void CloseWifi() {
      if (!mWifiManager.isWifiEnabled()) {
         mWifiManager.setWifiEnabled(false);
      }
   }
    //判斷wifi是否連接
   public static boolean isWifiConnect(Context context) {
      ConnectivityManager connManager = (ConnectivityManager) context
              .getSystemService(context.CONNECTIVITY_SERVICE);
      NetworkInfo mWifi = connManager
              .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
      return mWifi.getState() == NetworkInfo.State.CONNECTED ? true : false;
   }

   public String getSSID() {
      if (mWifiInfo != null) {
         String temp = mWifiInfo.getSSID();
         if (temp != null && (temp.startsWith("\"") && temp.endsWith("\""))) {
            temp = temp.substring(1, temp.length() - 1);
            return temp;
         }
         return temp;
      } else {
         return "";
      }
   }

   // 定義幾種加密方式,一種是WEP,一種是WPA,還有沒有密碼的情況
   /*
    * public enum WifiCipherType { NONE,WEP,WPA,EAP }
    */

   // 判斷wifi是否加密:
   public static String getSecuritys(ScanResult result) {
      if (result.capabilities.contains("WEP")) {
         return "WEP";
      } else if (result.capabilities.contains("PSK")) {
         return "WPA";
      } else if (result.capabilities.contains("EAP")) {
         return "EAP";
      }
      return "NONE";
   }
    //獲取wifi是那個加密類型
   public String getWifiCipherType(Context context, String ssid) {
      String type = null;
      mWifiManager = (WifiManager) context
              .getSystemService(Context.WIFI_SERVICE);
      mWifiList = mWifiManager.getScanResults();
      if (mWifiList != null) {
         for (int i = 0; i < mWifiList.size(); i++) {
            ScanResult sr = mWifiList.get(i);
            if (sr.SSID.equals(ssid))
               type = getSecuritys(sr);
         }
      }
      if (type == null) {
         type = "WPA";
      }
      return type;
   }
   //獲取wifi的信號大小
   public int getSignal(Context context, String ssid) {
      int signal = 100;
      mWifiManager = (WifiManager) context
              .getSystemService(Context.WIFI_SERVICE);
      mWifiList = mWifiManager.getScanResults();
      if (mWifiList != null) {
         for (int i = 0; i < mWifiList.size(); i++) {
            ScanResult sr = mWifiList.get(i);
            if (sr.SSID.equals(ssid))
               signal = Math.abs(sr.level);
         }
      }
      
      return signal;
   }

   // 打開WIFI
   public boolean OpenWifi() {
      boolean bRet = true;
      if (!mWifiManager.isWifiEnabled()) {
         bRet = mWifiManager.setWifiEnabled(true);
         while (mWifiList == null || mWifiList.size() == 0) {
            try {
               Thread.currentThread().sleep(2000);
               mWifiManager.startScan();
               mWifiList = mWifiManager.getScanResults();
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
         }
      }
      return bRet;
   }
   //斷判某個wifi是否是連接成功的那個wifi
   public boolean isConnectedWifi(Context context, String myssid){
      mWifiManager = (WifiManager) context
            .getSystemService(Context.WIFI_SERVICE);
      if (isWifiConnect(context)) {

         WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
         String ssid = wifiInfo.getSSID();
         if (ssid != null && ssid.contains(myssid)) {
            return true;
         } else {
            return false;
         }
      }else{
         return false;
      }
   }

   // 查看以前是否也配置過這個網絡
   private WifiConfiguration IsExsits(String SSID) {
      List<WifiConfiguration> existingConfigs = mWifiManager
              .getConfiguredNetworks();
      if (existingConfigs != null) {
         for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
               return existingConfig;
            }
         }
      }
      return null;
   }
    //刪除原來的所有連接
   private void deleteWifiConnect() {
      List<WifiConfiguration> existingConfigs = mWifiManager
              .getConfiguredNetworks();
      if (existingConfigs != null) {
         for (WifiConfiguration existingConfig : existingConfigs) {
            mWifiManager.disableNetwork(existingConfig.networkId);
         }

      }
   }

   // 提供一個外部接口,傳入要連接的無線網
   public boolean connectNet(String SSID, String Password, String Type) {
      WifiConfiguration tempConfig = this.IsExsits(SSID);
      if (tempConfig != null) {
         mWifiManager.removeNetwork(tempConfig.networkId);
      }
//    deleteWifiConnect();
//    forgetWifi(SSID);
      WifiConfiguration wifiConfig = this
              .CreateWifiInfo(SSID, Password, Type);
      int netID = mWifiManager.addNetwork(wifiConfig);
      boolean bRet = mWifiManager.enableNetwork(netID, true);
      mWifiManager.reconnect();
      return bRet;
   }
   public boolean connectNewNet(String SSID, String Password, int Type){
      WifiConfiguration configuration = this
            .createWifiInfo(SSID, Password, Type);
      int wcgId=mWifiManager.addNetwork(configuration);
      mWifiManager.enableNetwork(wcgId, true);
      boolean reconnect = mWifiManager.reconnect();
      return reconnect;
   }

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

      if (Type.equals("NONE")) {
         config.wepKeys[0] = "";
         config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
         config.wepTxKeyIndex = 0;
      } else if (Type.equals("WEP")) {
         config.preSharedKey = "\"" + Password + "\"";
         config.hiddenSSID = true;
         config.allowedAuthAlgorithms
                 .set(WifiConfiguration.AuthAlgorithm.SHARED);
         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
         config.allowedGroupCiphers
                 .set(WifiConfiguration.GroupCipher.WEP104);
         config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
         config.wepTxKeyIndex = 0;
      } else if (Type.equals("WPA")) {
         config.preSharedKey = "\"" + Password + "\"";
         config.hiddenSSID = true;
         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
         config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
         config.allowedPairwiseCiphers
                 .set(WifiConfiguration.PairwiseCipher.TKIP);
         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
         config.allowedPairwiseCiphers
                 .set(WifiConfiguration.PairwiseCipher.CCMP);
         config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);// 對應wpa2加密方式
         config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);// 對應wpa加密方式
         config.status = WifiConfiguration.Status.ENABLED;
      } else if (Type.equals("EAP")) {
         config.preSharedKey = "\"" + Password + "\"";
         config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
         config.allowedKeyManagement
                 .set(WifiConfiguration.KeyMgmt.IEEE8021X);// 20120723新增
      }
      return config;
   }
   public WifiConfiguration createWifiInfo(String SSID, String Password, int Type){
      WifiConfiguration config = new WifiConfiguration();
      config.allowedAuthAlgorithms.clear();
      config.allowedGroupCiphers.clear();
      config.allowedKeyManagement.clear();
      config.allowedPairwiseCiphers.clear();
      config.allowedProtocols.clear();
      config.SSID = "\"" + SSID + "\"";

      if(Type == 1) //WIFICIPHER_NOPASS
      {
         config.hiddenSSID = true;
         config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
      }

      if(Type == 2) //WIFICIPHER_WEP
      {
         config.hiddenSSID = true;
         config.wepKeys[0]= "\""+Password+"\"";
         config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
         config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
         config.wepTxKeyIndex = 0;
      }
      if(Type == 3) //WIFICIPHER_WPA
      {
         config.preSharedKey = "\""+Password+"\"";
         config.hiddenSSID = true;
         config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
         config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
         config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
         config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
         config.status = WifiConfiguration.Status.ENABLED;
      }
      return config;
   }
   public void addNetWork(WifiConfiguration configuration){

      //mWifiManager.saveConfiguration();
   }
   /**
    * 移除wifi,因爲權限,無法移除的時候,需要手動去翻wifi列表刪除
    * 注意:!!!只能移除自己應用創建的wifi。
    * 刪除掉app,再安裝的,都不算自己應用,具體看removeNetwork源碼
    *
    */
   public boolean forgetWifi(String SSID){
      WifiConfiguration tempConfig = this.IsExsits(SSID);
      if (tempConfig != null) {
         Log.d("howard","tempConfig.networkId="+tempConfig.networkId);
         return  mWifiManager.removeNetwork(tempConfig.networkId);
         //mWifiManager.saveConfiguration();
      }
      return false;
   }

   private String intToIp(int paramInt) {
      return (paramInt & 0xFF) + "." + (0xFF & paramInt >> 8) + "." + (0xFF & paramInt >> 16) + "."
            + (0xFF & paramInt >> 24);
   }
   public boolean addNetWork(String SSID, String password, int Type)
   {
      int netId = -1;
    /*先執行刪除wifi操作,1.如果刪除的成功說明這個wifi配置是由本APP配置出來的;
                       2.這樣可以避免密碼錯誤之後,同名字的wifi配置存在,無法連接;
                       3.wifi直接連接成功過,不刪除也能用, netId = getExitsWifiConfig(SSID).networkId;*/
      if (forgetWifi(SSID))
      {
         //移除成功,就新建一個
         netId = mWifiManager.addNetwork(createWifiInfo(SSID, password, Type));
      } else
      {
         //刪除不成功,要麼這個wifi配置以前就存在過,要麼是還沒連接過的
         if (getExitsWifiConfig(SSID) != null)
         {
            //這個wifi是連接過的,如果這個wifi在連接之後改了密碼,那就只能手動去刪除了
            netId = getExitsWifiConfig(SSID).networkId;
         } else
         {
            //沒連接過的,新建一個wifi配置
            netId = mWifiManager.addNetwork(createWifiInfo(SSID, password, Type));
         }
      }

      //這個方法的第一個參數是需要連接wifi網絡的networkId,第二個參數是指連接當前wifi網絡是否需要斷開其他網絡
      //無論是否連接上,都返回true。。。。
      boolean enableNetwork = mWifiManager.enableNetwork(netId, true);
      return enableNetwork;
   }

   /**
    * 獲取配置過的wifiConfiguration
    */
   public WifiConfiguration getExitsWifiConfig(String SSID)
   {
      List<WifiConfiguration> wifiConfigurationList = mWifiManager.getConfiguredNetworks();
      for (WifiConfiguration wifiConfiguration : wifiConfigurationList)
      {
         if (wifiConfiguration.SSID.equals("\"" + SSID + "\""))
         {
            return wifiConfiguration;
         }
      }
      return null;
   }

}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章