我想连接到wifi网络,所以我试试这个:
WifiConfiguration wfc = new WifiConfiguration();
wfc.SSID = "\"".concat( sid ).concat("\"");
wfc.preSharedKey = "\"".concat( pwd ).concat("\"");
WifiManager wfMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
int networkId = wfMgr.addNetwork(wfc);
if (networkId != -1) {
// success, can call wfMgr.enableNetwork(networkId, true) to connect
} else {
// fails
}
但networkId始终为-1 错误在哪里?
清单中还添加了必要的权限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" android:required="true"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" android:required="true"/>
答案 0 :(得分:0)
文档说:
向已配置的网络集添加新的网络描述。将忽略提供的配置对象的networkId字段。
默认情况下,新网络将标记为DISABLED。要启用它, 调用enableNetwork(int,boolean)。参数配置描述配置的变量集,包含在WifiConfiguration对象中。
返回新创建的网络描述的ID。这用于指定要对其执行操作的网络的其他操作。失败时返回-1。
所以,我的猜测是你需要这样做:
wfMgr.enableNetwork(netId,true);
netId:已配置网络列表中的网络ID。
答案 1 :(得分:0)
你可以这样做
public static void addNewConnection(final String networkSSID, String networkPassword, String securityType, Context context)
{
// Default settings for all networks
wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "\"".concat(networkSSID).concat("\"");
wifiConfig.status = WifiConfiguration.Status.ENABLED;
wifiConfig.hiddenSSID = true;
wifiConfig.priority = 40;
connectToNewWifiConfig(wifiConfig, context);
}
private static boolean connectToNewWifiConfig(final WifiConfiguration wc, Context context)
{
wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
boolean success = false;
final int actNetId = wifi.getConnectionInfo().getNetworkId();
WifiInfo wifiInfo = wifi.getConnectionInfo();
String prevNetworkSSID = wifiInfo.getSSID();
int netId = wifi.addNetwork(wc);
if (netId != ApplicationConstants.INVALID_NETWORK_ID)
{
success = wifi.saveConfiguration();
}
return success;
}