寫在最前,項目中加了一個連接wifi的需求,在之前我是接了一下,發現在android10上wifimanger是不可以用了,需要使用新接口。但是這新接口接上去,連上wifi后沒有數據。然后,就在昨天我又重新試了下,發現之前被拋棄的wifimanger這個接口又可以在android10上用了???而他給出的新接口還是一如既往的不能用。官方文檔上現在記錄的還是新接口,所以就不貼官方文檔地址了,有興趣的可以自己去翻。
在前面記一下遇到的問題和解決方法。
1. 華為手機無法連接保存過的無密碼wifi,無法add上去。
解決方法是,在getConfiguredNetworks()接口里獲取到對應ssid的networdId,然后直接連這個networkId。
2. 抄網上的博客時,無法連接無密碼wifi。
刪除掉如下代碼
config.wepKeys[0] = "";
config.wepTxKeyIndex = 0;
下面貼一下,我的連接代碼
@RequiresApi(api = Build.VERSION_CODES.O) private static boolean connect(String netWorkName, String password, Activity activity) { WifiManager wifiManager; wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE); //獲取系統保存的wifi信息 List<WifiConfiguration> configurationInfos=wifiManager.getConfiguredNetworks(); wifiManager.setWifiEnabled(true); WifiConfiguration config = new WifiConfiguration(); config.allowedAuthAlgorithms.clear(); config.allowedGroupCiphers.clear(); config.allowedKeyManagement.clear(); config.allowedPairwiseCiphers.clear(); config.allowedProtocols.clear(); // 指定對應的SSID config.SSID = "\"" + netWorkName+ "\""; if(password.equals("")){ // config.wepKeys[0] = ""; config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); // config.wepTxKeyIndex = 0; }else{ 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; } int netId = wifiManager.addNetwork(config); if(netId==-1){ for(WifiConfiguration wifiConfiguration : configurationInfos){ if(config.SSID.equals(wifiConfiguration.SSID)){ netId = wifiConfiguration.networkId; } } } // 這個方法的第一個參數是需要連接wifi網絡的networkId,第二個參數是指連接當前wifi網絡是否需要斷開其他網絡 boolean result = wifiManager.enableNetwork(netId, true); return result; }
傳入賬號密碼就可以連接wifi了。