Java 设置保存的网络设置

Java 设置保存的网络设置,java,android,networking,Java,Android,Networking,在我的Android应用程序中,我通常会执行以下步骤: 1) 打开wifi(如果已关闭) 2) 连接到特定的wifi(如果找到) 3) 在新的wifi网络中有所作为 4) 返回到第一步之前的网络状态 如何保存网络状态并重新设置?将其添加到清单 检查wifi是否打开和关闭boolean wifiEnabled=wifiManager.isWifiEnabled() 启用和禁用wifi WifiManager wifiManager = (WifiManager) this.getApplica

在我的Android应用程序中,我通常会执行以下步骤:

1) 打开wifi(如果已关闭)
2) 连接到特定的wifi(如果找到)
3) 在新的wifi网络中有所作为
4) 返回到第一步之前的网络状态


如何保存网络状态并重新设置?

将其添加到清单

检查wifi是否打开和关闭
boolean wifiEnabled=wifiManager.isWifiEnabled()

启用和禁用wifi

WifiManager wifiManager = (WifiManager) 
this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
保存新的wifi

  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();
            }
        }