我正在尝试通过提供 SSID 并使用 WifiManager 配置来连接到 WiFi 网络。
基于此线程解决方案: 如何以编程方式连接到 Android 中的特定 Wi-Fi 网络?
调用reconnect方法。但什么也没发生(未连接)。
Android 版本(6.0.1)有什么用吗? 如果是,那么如何在 Android 6 上以编程方式执行网络连接?
Android Marshmallow 中连接 WiFi 网络的一些事情发生了变化。 以下代码将帮助您...如果您使用的是 Android 6.0 或低版本...
public void connectToWifi(){
try{
WifiManager wifiManager = (WifiManager) super.getSystemService(android.content.Context.WIFI_SERVICE);
WifiConfiguration wc = new WifiConfiguration();
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
wc.SSID = "\"NETWORK_NAME\"";
wc.preSharedKey = "\"PASSWORD\"";
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifiManager.setWifiEnabled(true);
int netId = wifiManager.addNetwork(wc);
if (netId == -1) {
netId = getExistingNetworkId(wc.SSID);
}
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
private int getExistingNetworkId(String SSID) {
WifiManager wifiManager = (WifiManager) super.getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
if (configuredNetworks != null) {
for (WifiConfiguration existingConfig : configuredNetworks) {
if (existingConfig.SSID.equals(SSID)) {
return existingConfig.networkId;
}
}
}
return -1;
}
并在Manifest文件中添加权限
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
使用addNetwork添加wifi配置,然后使用enableNetwork连接到它。
WifiConfiguration wificonfiguration = new WifiConfiguration();
StringBuffer stringbuffer = new StringBuffer("\"");
stringbuffer.append((new StringBuilder(String.valueOf(HOTSPOT_NAME))).append("\"").toString());
wificonfiguration.SSID = stringbuffer.toString();
wificonfiguration.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
wificonfiguration.allowedAuthAlgorithms.set(0);
wificonfiguration.status = 2;
wificonfiguration.preSharedKey = "\"" + HOTSPOT_PASSWORD + "\"";
int networkId_ = wifi.addNetwork(wificonfiguration);
if(networkId>-1){
boolean status = wifi.enableNetwork(networkId_, true);
}
对于棉花糖:仅当您创建了 WifiConfiguration 对象时,您的应用程序现在才可以更改这些对象。您不得修改或删除用户或其他应用程序创建的 WifiConfiguration 对象。 有关棉花糖的更多信息
自 Android Lollipop 和 Marshmallow 以来,连接 WiFi 网络的方式发生了一些变化。有一篇不错的博客文章,介绍如何在 Marshmallow 及以下版本上连接 WiFi 网络
http://www.intentfilter.com/2016/08/programatically-connecting-to-wifi.html
这篇文章描述了当 WiFi 网络没有连接并且您希望通过该网络(类似于强制门户)发送流量时的场景。但它也解释了完整的过程并且适用于普通网络。您找不到确切的代码,但它仍然可能有助于了解您陷入困境的位置。
需要调用WiFiManager的disconnect()和reconnect()。这对我有用:
WifiConfiguration conf = new WifiConfiguration();
conf.hiddenSSID = true;
conf.priority = 1000;
conf.SSID = "\"" + SSID + "\"";
conf.preSharedKey = "\""+Password+"\"";
conf.status = WifiConfiguration.Status.ENABLED;
conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
int res = wifiManager.addNetwork(conf);
boolean es = wifiManager.saveConfiguration();
Log.d(TAG, "saveConfiguration returned " + es );
wifiManager.disconnect();
boolean bRet = wifiManager.enableNetwork(res, true);
Log.i(TAG, "enableNetwork bRet = " + bRet);
wifiManager.reconnect();
这对我来说适用于 WPA 连接。 如果已保存网络,则无需再次添加。
private void connectToWifi(final String networkSSID, final String networkPassword) {
int netID = -1;
String confSSID = String.format("\"%s\"", networkSSID);
String confPassword = String.format("\"%s\"", networkPassword);
netID = getExistingNetworkID(confSSID, netID);
/*
* If ssid not found in preconfigured list it will return -1
* then add new wifi
*/
if (netID == -1) {
Log.d(TAG,"New wifi config added");
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = confSSID;
conf.preSharedKey = confPassword;
netID = wifiManager.addNetwork(conf);
}
wifiManager.disconnect();
wifiManager.enableNetwork(netID, true);
wifiManager.reconnect();
}
private int getExistingNetworkID (String confSSID, int netID){
List<WifiConfiguration> wifiConfigurationList = wifiManager.getConfiguredNetworks();
for (WifiConfiguration item : wifiConfigurationList){
/*
Find if the SSID is in the preconfigured list - if found get netID
*/
if (item.SSID != null && item.SSID.equals(confSSID)){
Log.d(TAG, "Pre-configured running");
netID = item.networkId;
break;
}
}
return netID;
}
这是连接 wifi 的正确方法,而且这个非常短的无样板代码
fun connectToWifi(ssid: String, password: String) {
val connManager = context!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
val wifiConfiguration = WifiConfiguration()
wifiConfiguration.SSID = String.format("\"%s\"", ssid)
wifiConfiguration.preSharedKey = String.format("\"%s\"", password)
wifiManager = context!!.getSystemService(Context.WIFI_SERVICE) as WifiManager
val netId: Int = wifiManager.addNetwork(wifiConfiguration)
wifiManager.disconnect()
wifiManager.enableNetwork(netId, true)
wifiManager.reconnect()
val config = WifiConfiguration()
config.SSID == "\"\"" + ssid + "\"\""
config.preSharedKey == "\"\"" + password + "\"\""
wifiManager.addNetwork(config)
}
尝试一下并享受:
int res = mWifiManager.addNetwork(wifiConfiguration);
if (res == -1) {
// Get existed network id if it is already added to WiFi network
res = getExistingNetworkId(wifiConfiguration.SSID);
Log.d(TAG, "getExistingNetwrkId: " + res);
}
private int getExistingNetworkId(String SSID) {
List<WifiConfiguration> configuredNetworks = mWifiManager.getConfiguredNetworks();
if (configuredNetworks != null) {
for (WifiConfiguration existingConfig : configuredNetworks) {
if (SSID.equalsIgnoreCase(existingConfig.SSID)) {
return existingConfig.networkId;
}
}
}
return -1;
}