在Android中,要更改Wi-Fi配置,您需要使用WifiManager
类
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
WifiManager
实例:WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
// 打开Wi-Fi
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
// 关闭Wi-Fi
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "\"" + networkSSID + "\""; // 请将networkSSID替换为您的网络名称
wifiConfig.preSharedKey = "\"" + networkPassword + "\""; // 请将networkPassword替换为您的网络密码
int netId = wifiManager.addNetwork(wifiConfig);
if (netId == -1) {
netId = wifiManager.updateNetwork(wifiConfig);
}
if (netId != -1) {
wifiManager.disconnect(); // 断开当前连接的Wi-Fi
wifiManager.enableNetwork(netId, true); // 启用新的Wi-Fi配置
wifiManager.reconnect(); // 重新连接到新的Wi-Fi
}
示例代码片段仅供参考,请根据您的应用程序需求进行调整。