在我的 Android 应用程序中,我曾经执行以下步骤:
1) 打开 wifi(如果已关闭);
2)连接到特定的wifi(如果找到);
3)在新的wifi网络中做一些事情;
4) 返回第一步之前的网络状态;
如何保存网络状态并重新设置?
最佳答案
将其添加到 list 中 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-
permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-
permission>
检查 wifi 是否打开和关闭 boolean wifiEnabled = wifiManager.isWifiEnabled()
启用和禁用 wifi
WifiManager wifiManager = (WifiManager)
this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
保存新的无线网络
WifiConfiguration conf = new WifiConfiguration();
String ssid = "GGP";
String password = "%5EyS0X-n$2c9";
conf.SSID = "\"" + ssid + "\""; // Please note the quotes. String should contain SSID in quotes
conf.preSharedKey = "\"" + password + "\"";
String security = "WPA2 Personal";
//WPA2 Encryption
if (security.equalsIgnoreCase("WPA2 Personal")) {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
Objects.requireNonNull(wifiManager).setWifiEnabled(true);
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + ssid + "\""; // Please note the quotes. String should contain SSID in quotes
conf.preSharedKey = "\"" + password + "\"";
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.status = WifiConfiguration.Status.ENABLED;
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
// turns on Wifi
Objects.requireNonNull(wifiManager).setWifiEnabled(true);
// add wifi configuration to Device.
int newNetworkId = wifiManager.addNetwork(conf);
Log.e(TAG, "Wifi Profile added");
// try to connect to this network
wifiManager.enableNetwork(newNetworkId, true);
// saves configuration else after reboot it will be gone
wifiManager.saveConfiguration();
}
}
关于java - 设置保存的网络设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60091700/