我正在尝试连接到Android上的特定Wifi网络(WPA2),但不知何故,它无法在运行Android 4.1.2版的特定设备上运行。鉴于相同的代码正在运行Android版本4.4.2& 4.4.4。在设备上它不工作,我看到网络被成功添加,因为我可以手动连接而无需明确输入密钥。代码段粘贴在下面。不知道我在这里做错了什么或者是否有版本依赖?
private boolean connectToWifi(String networkSSID, String networkPass) {
networkSSID = "\"" + networkSSID + "\"";
WifiManager wifiMgr = (WifiManager)(this.getSystemService(Context.WIFI_SERVICE));
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
if(wifiInfo != null) {
String name = wifiInfo.getSSID();
if(name.equalsIgnoreCase(networkSSID)) {
return true;
}
}
int networkId = -1;
WifiManager wifiManager = (WifiManager)(this.getSystemService(Context.WIFI_SERVICE));
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals(networkSSID)) {
break;
}
}
if(networkId == -1) {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = networkSSID;
conf.preSharedKey = "\"" + networkPass + "\"";
networkId = wifiManager.addNetwork(conf);
if(networkId == -1)
return false;
}
boolean retval = false;
list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals(networkSSID)) {
this.addDebugMessage("Trying to connect to p2p network");
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
retval = wifiManager.reconnect();
break;
}
}
return retval;
}
清单中还添加了必要的权限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" android:required="true"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" android:required="true"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" android:required="true"/>
<uses-permission android:name="android.permission.INTERNET" android:required="true"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" android:required="true"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" android:required="true"/>