public class WifiUtils {
private Context mContext;
private WifiManager mWifiManager;
public WifiUtils(Context context) {
mContext = context;
mWifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
}
public boolean isWifiEnabled() {
return mWifiManager.isWifiEnabled();
}
public boolean startScan() {
return mWifiManager.startScan();
}
public String getConnectedSsid() {
return mWifiManager.getConnectionInfo().getSSID().replace("\"", "");
}
public List<ScanResult> getScanResults() {
return mWifiManager.getScanResults();
}
public void setWifiEnabled(boolean enabled) {
mWifiManager.setWifiEnabled(enabled);
}
public boolean connectWifiPws(String ssid, String pws) {
mWifiManager.disableNetwork(mWifiManager.getConnectionInfo().getNetworkId());
int netId = mWifiManager.addNetwork(getWifiConfig(ssid, pws, true));
return mWifiManager.enableNetwork(netId, true);
}
public boolean connectWifiNoPws(String ssid) {
mWifiManager.disableNetwork(mWifiManager.getConnectionInfo().getNetworkId());
int netId = mWifiManager.addNetwork(getWifiConfig(ssid, "", false));
return mWifiManager.enableNetwork(netId, true);
}
private WifiConfiguration getWifiConfig(String ssid, String pws, boolean isHasPws) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + ssid + "\"";
WifiConfiguration tempConfig = isExist(ssid);
if (tempConfig != null) {
mWifiManager.removeNetwork(tempConfig.networkId);
}
if (isHasPws) {
config.preSharedKey = "\"" + pws + "\"";
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;
} else {
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}
return config;
}
private WifiConfiguration isExist(String ssid) {
List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
for (WifiConfiguration config : configs) {
if (config.SSID.equals("\"" + ssid + "\"")) {
return config;
}
}
return null;
}
public boolean isWifiConnect() {
ConnectivityManager connManager =
(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi.isConnected();
}
}