android 自動連線WiFi
阿新 • • 發佈:2019-02-03
很久沒有寫部落格了,今天記錄下做專案中發現的問題,關於自動連線WiFi問題,本來在網上找了許多,發現測試下來不太好用,於是找了找原因,再次記錄一下。
先說工具類吧,包含了許多,網上也能找到類似的
public class WifiAdmin { // 定義WifiManager物件 private WifiManager mWifiManager; // 定義WifiInfo物件 private WifiInfo mWifiInfo; // 掃描出的網路連線列表 private List<ScanResult> mWifiList; // 網路連線列表 private List<WifiConfiguration> mWifiConfiguration; // 定義一個WifiLock WifiManager.WifiLock mWifiLock; public WifiManager getmWifiManager() { return mWifiManager; } public void setmWifiManager(WifiManager mWifiManager) { this.mWifiManager = mWifiManager; } // 構造器 public WifiAdmin(Context context) { // 取得WifiManager物件 mWifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); // 取得WifiInfo物件 mWifiInfo = mWifiManager.getConnectionInfo(); } // 開啟WIFI public void openWifi() { if (!mWifiManager.isWifiEnabled()) { mWifiManager.setWifiEnabled(true); } } // 關閉WIFI public void closeWifi() { if (mWifiManager.isWifiEnabled()) { mWifiManager.setWifiEnabled(false); } } // 檢查當前WIFI狀態 public int checkState() { return mWifiManager.getWifiState(); } // 鎖定WifiLock public void acquireWifiLock() { mWifiLock.acquire(); } // 解鎖WifiLock public void releaseWifiLock() { // 判斷時候鎖定 if (mWifiLock.isHeld()) { mWifiLock.acquire(); } } // 建立一個WifiLock public void creatWifiLock() { mWifiLock = mWifiManager.createWifiLock("Test"); } // 得到配置好的網路 public List getConfiguration() { return mWifiConfiguration; } // 指定配置好的網路進行連線 public void connectConfiguration(int index) { // 索引大於配置好的網路索引返回 if (index > mWifiConfiguration.size()) { return; } // 連線配置好的指定ID的網路 mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true); } public void startScan() { mWifiManager.startScan(); // 得到掃描結果 mWifiList = mWifiManager.getScanResults(); // 得到配置好的網路連線 mWifiConfiguration = mWifiManager.getConfiguredNetworks(); } // 得到網路列表 public List getWifiList() { return mWifiManager.getScanResults(); } // 檢視掃描結果 public StringBuilder lookUpScan() { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < mWifiList.size(); i++) { stringBuilder .append("Index_" + new Integer(i + 1).toString() + ":"); // 將ScanResult資訊轉換成一個字串包 // 其中把包括:BSSID、SSID、capabilities、frequency、level stringBuilder.append((mWifiList.get(i)).toString()); stringBuilder.append("/n"); } return stringBuilder; } // 得到MAC地址 public String getMacAddress() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress(); } // 得到接入點的BSSID public String getBSSID() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID(); } // 得到IP地址 public int getIPAddress() { return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress(); } // 得到連線的ID public int getNetworkId() { return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId(); } // 得到WifiInfo的所有資訊包 public String getWifiInfo() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString(); } // 新增一個網路並連線 public void addNetwork(WifiConfiguration wcg) { int wcgID = mWifiManager.addNetwork(wcg); mWifiManager.disconnect(); boolean b = mWifiManager.enableNetwork(wcgID, true); mWifiManager.saveConfiguration(); mWifiManager.reconnect(); System.out.println("b--" + b); } // 斷開指定ID的網路 public void disconnectWifi(int netId) { mWifiManager.disableNetwork(netId); mWifiManager.disconnect(); } //然後是一個實際應用方法,只驗證過沒有密碼的情況: 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 + "\""; config.SSID = "\"" + getTrueSSID(SSID) + "\""; 移除掉之前的wifiWifiConfiguration tempConfig = this.IsExsits(SSID); if (tempConfig != null) { mWifiManager.removeNetwork(tempConfig.networkId); } if (Type == 1)// WIFICIPHER_NOPASS { // config.wepKeys[0] = ""; config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); // config.wepTxKeyIndex = 0; } 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.allowedProtocols.set(WifiConfiguration.Protocol.WPA); 這裡需要注意下有的文章是註釋掉的這一句話,這是不可以的,找了半天才發現原因config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); config.allowedPairwiseCiphers .set(WifiConfiguration.PairwiseCipher.CCMP); config.status = WifiConfiguration.Status.ENABLED; } return config; } public int getCipherType(String ssid) { List<ScanResult> list = mWifiManager.getScanResults(); for (ScanResult scResult : list) { if (!TextUtils.isEmpty(scResult.SSID) && (scResult.SSID.trim().equalsIgnoreCase( "\"" + ssid + "\"") || scResult.SSID.trim() .equalsIgnoreCase(ssid))) { String capabilities = scResult.capabilities; LogUtil.i("hefeng", "capabilities=" + capabilities); if (!TextUtils.isEmpty(capabilities)) { if (capabilities.contains("WPA") || capabilities.contains("wpa")) { return 3; } else if (capabilities.contains("WEP") || capabilities.contains("wep")) { return 2; } else { return 1; } } } } return -1; } private WifiConfiguration IsExsits(String ssid) { List<WifiConfiguration> existingConfigs = mWifiManager .getConfiguredNetworks(); for (WifiConfiguration existingConfig : existingConfigs) { // if (existingConfig.SSID.equals("\"" + SSID + "\"")) { if (existingConfig.SSID.equalsIgnoreCase("\"" + ssid + "\"") || existingConfig.SSID.equalsIgnoreCase(ssid)) { return existingConfig; } } return null; } public boolean ifWifiExsits(String ssid) { mWifiList = getWifiList(); if (mWifiList == null) { return false; } for (int i = 0; i < mWifiList.size(); i++) { if (mWifiList.get(i).SSID.equalsIgnoreCase("\"" + ssid + "\"") || mWifiList.get(i).SSID.equalsIgnoreCase(ssid)) { return true; } } return false; } public String getTrueSSID(String ssid) { LogUtil.e("", ssid + ""); mWifiList = getWifiList(); if (mWifiList == null) { return ssid; } for (int i = 0; i < mWifiList.size(); i++) { if (mWifiList.get(i).SSID.equalsIgnoreCase("\"" + ssid + "\"") || mWifiList.get(i).SSID.equalsIgnoreCase(ssid)) { return mWifiList.get(i).SSID; } } return ssid; } public boolean isConnect(String ssid) { WifiInfo wifiInfo = mWifiManager.getConnectionInfo(); if (wifiInfo != null) { return wifiInfo.getSSID().equalsIgnoreCase("\"" + ssid + "\"") || wifiInfo.getSSID().equalsIgnoreCase(ssid); } return false; } public WifiInfo getCurrentWifiInfo() { return mWifiManager.getConnectionInfo(); } public boolean isWifiEnable() { return mWifiManager.isWifiEnabled(); } 這個大部分和網上的還是一致的,這裡記錄下。
接下來是使用
WifiAdmin wifiAdmin = new WifiAdmin(getActivity()); if (!wifiAdmin.isWifiEnable()) { wifiAdmin.openWifi(); } if (wifiAdmin.getmWifiManager().isWifiEnabled()) { if (!wifiAdmin.isConnect("wifi名稱")) { if (wifiAdmin.ifWifiExsits("wifi名稱")) { wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo("wifi名稱", "wifi密碼", wifiAdmin.getCipherType("wifi名稱"))); } } }
這裡一定要加獲取wifi和改變wifi的許可權!!!!!!!!!
寫到這裡差不多就要結束了,本來開開心心的去試驗,發現在6.0之前的版本是可以的,6.0之後的版本是不可以的,找了一下發現是6.0之後獲取wifi的列表,需要獲取地理位置,進而才能獲取到周圍的WiFi的列表.這裡需要加申請地址位置許可權,這裡就不太多闡述了。
最後一定要加上獲取地理位置許可權