下面列出了怎么用android.net.wifi.WifiConfiguration的API类实例代码及写法,或者点击链接到github查看源代码。
protected WifiConfiguration findCurrentWifiConfiguration() {
MyLog.entry();
WifiConfiguration configuration = null;
if (mWifiManager.isWifiEnabled()) {
final List<WifiConfiguration> configurationList = mWifiManager.getConfiguredNetworks();
final int cur = mWifiManager.getConnectionInfo().getNetworkId();
for (final WifiConfiguration wifiConfiguration : configurationList) {
if (wifiConfiguration.networkId == cur) {
configuration = wifiConfiguration;
break;
}
}
}
MyLog.exit();
return configuration;
}
@ReactMethod
public void isRemoveWifiNetwork(String ssid, final Callback callback) {
List<WifiConfiguration> mWifiConfigList = wifi.getConfiguredNetworks();
if (mWifiConfigList == null) {
return;
}
for (WifiConfiguration wifiConfig : mWifiConfigList) {
String comparableSSID = ('"' + ssid + '"'); //Add quotes because wifiConfig.SSID has them
if(wifiConfig.SSID.equals(comparableSSID)) {
wifi.removeNetwork(wifiConfig.networkId);
wifi.saveConfiguration();
callback.invoke(true);
return;
}
}
callback.invoke(false);
}
static boolean cleanPreviousConfiguration(@Nullable final WifiManager wifiManager, @Nullable final WifiConfiguration config) {
//On Android 6.0 (API level 23) and above if my app did not create the configuration in the first place, it can not remove it either.
if (wifiManager == null) {
return false;
}
wifiLog("Attempting to remove previous network config...");
if (config == null) {
return true;
}
if (wifiManager.removeNetwork(config.networkId)) {
wifiManager.saveConfiguration();
return true;
}
return false;
}
/**
* Update the network: either create a new network or modify an existing network
* @param config the new network configuration
*/
private static void updateNetwork(WifiManager wifiManager, WifiConfiguration config) {
Integer foundNetworkID = findNetworkInExistingConfig(wifiManager, config.SSID);
if (foundNetworkID != null) {
Log.i(TAG, "Removing old configuration for network " + config.SSID);
wifiManager.removeNetwork(foundNetworkID);
wifiManager.saveConfiguration();
}
int networkId = wifiManager.addNetwork(config);
if (networkId >= 0) {
// Try to disable the current network and start a new one.
if (wifiManager.enableNetwork(networkId, true)) {
Log.i(TAG, "Associating to network " + config.SSID);
wifiManager.saveConfiguration();
} else {
Log.w(TAG, "Failed to enable network " + config.SSID);
}
} else {
Log.w(TAG, "Unable to add network " + config.SSID);
}
}
/**
* Clear all existing wifi networks (for those we can actually clear)
*/
private void handleActionClear() {
if (!checkWifi()) return;
boolean save = false;
List<WifiConfiguration> networks = m_wifiManager.getConfiguredNetworks();
for (WifiConfiguration net : networks) {
if (m_wifiManager.removeNetwork(net.networkId)) {
save = true;
} else {
Log.w(TAG, "Unable to remove network: " + net.SSID + ": Permission denied.");
}
}
if (save)
m_wifiManager.saveConfiguration();
Log.i(TAG, "Cleared networks as permitted.");
}
private WifiConfiguration createWifiConfiguration(String ssid, String passphrase, Boolean isWEP) {
WifiConfiguration configuration = new WifiConfiguration();
configuration.SSID = String.format("\"%s\"", ssid);
if (passphrase.equals("")) {
configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
} else if (isWEP) {
configuration.wepKeys[0] = "\"" + passphrase + "\"";
configuration.wepTxKeyIndex = 0;
configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
} else { // WPA/WPA2
configuration.preSharedKey = "\"" + passphrase + "\"";
}
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
return configuration;
}
private boolean removeSSID(String ssid) {
boolean success = true;
// Remove the existing configuration for this network
WifiConfiguration existingNetworkConfigForSSID = getExistingNetworkConfig(ssid);
//No Config found
if (existingNetworkConfigForSSID == null) {
return success;
}
int existingNetworkId = existingNetworkConfigForSSID.networkId;
if (existingNetworkId == -1) {
return success;
}
success = wifiManager.removeNetwork(existingNetworkId) && wifiManager.saveConfiguration();
//If not our config then success would be false
return success;
}
/**
* Update the network: either create a new network or modify an existing network
* @param config the new network configuration
*/
private static void updateNetwork(WifiManager wifiManager, WifiConfiguration config) {
Integer foundNetworkID = findNetworkInExistingConfig(wifiManager, config.SSID);
if (foundNetworkID != null) {
Log.i(TAG, "Removing old configuration for network " + config.SSID);
wifiManager.removeNetwork(foundNetworkID);
wifiManager.saveConfiguration();
}
int networkId = wifiManager.addNetwork(config);
if (networkId >= 0) {
// Try to disable the current network and start a new one.
if (wifiManager.enableNetwork(networkId, true)) {
Log.i(TAG, "Associating to network " + config.SSID);
wifiManager.saveConfiguration();
} else {
Log.w(TAG, "Failed to enable network " + config.SSID);
}
} else {
Log.w(TAG, "Unable to add network " + config.SSID);
}
}
@RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
static boolean cleanPreviousConfiguration(@Nullable final WifiManager wifiManager, @NonNull final ScanResult scanResult) {
if (wifiManager == null) {
return false;
}
//On Android 6.0 (API level 23) and above if my app did not create the configuration in the first place, it can not remove it either.
final WifiConfiguration config = ConfigSecurities.getWifiConfiguration(wifiManager, scanResult);
wifiLog("Attempting to remove previous network config...");
if (config == null) {
return true;
}
if (wifiManager.removeNetwork(config.networkId)) {
wifiManager.saveConfiguration();
return true;
}
return false;
}
/**
* 添加WiFi网络
*
* @param SSID
* @param password
* @param type
*/
public int addWiFiNetwork(String SSID, String password, Data type) {
// 创建WiFi配置
WifiConfiguration configuration = createWifiConfig(SSID, password, type);
// 添加WIFI网络
int networkId = mWifiManager.addNetwork(configuration);
if (networkId == -1) {
return -1;
}
// 使WIFI网络有效
mWifiManager.enableNetwork(networkId, true);
return networkId;
}
private void initialize() {
if (mOldConfig != null) {
mSsidText.setText(mOldConfig.SSID.replace("\"", ""));
mPasswordText.setText("");
if (mOldConfig.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
mSecurityType = SECURITY_TYPE_WPA;
} else if (mOldConfig.allowedAuthAlgorithms.get(
WifiConfiguration.AuthAlgorithm.SHARED)) {
mSecurityType = SECURITY_TYPE_WEP;
} else {
mSecurityType = SECURITY_TYPE_NONE;
}
} else {
mSsidText.setText("");
mPasswordText.setText("");
mSecurityType = SECURITY_TYPE_NONE;
}
mSecurityChoicesSpinner.setSelection(mSecurityType);
}
@Override
public void onApConnectionFailed(WifiConfiguration config) {
clearState();
if (decoratedClient != null) {
decoratedClient.onApConnectionFailed(config);
}
}
/**
* Attempts to connect to the network defined by the given {@link WifiConfiguration}. Callers
* should use the {@link WifiConfigurationBuilder} helper class to create valid
* {@link WifiConfiguration} objects.
*
* @param network
* @return True if the given network could be connected to; false otherwise
*/
private boolean setCurrentWifiNetwork(WifiConfiguration network) {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager == null) {
return false;
}
logger.debug("Changing wifi to network configuration SSID={} with password={}", network.SSID, network.preSharedKey);
// If phone already knows how to connect to this network, then delete it!
if (PhoneWifiHelper.isNetworkConfigured(getApplicationContext(), network.SSID)) {
logger.debug("Network configuration already exists; deleting it.");
if (!wifiManager.removeNetwork(network.networkId)) {
logger.error("Attempt to delete existing network id={} failed. Ignoring.", network.networkId);
}
}
// Try to add this network definition
if (!PhoneWifiHelper.isNetworkConfigured(getApplicationContext(), network.SSID) && wifiManager.addNetwork(network) < 0) {
logger.error("Failed to add WifiConfiguration: {}", network);
return false;
}
// Provided we added the network successfully, try to connect to it
return setCurrentWifiNetwork(network.SSID);
}
public WifiConfiguration getWifiApConfiguration() {
Object result = invokeQuietly(getWifiApConfigurationMethod, wm);
if (result == null) {
return null;
}
return (WifiConfiguration) result;
}
public static WifiConfigCreationDialog newInstance(WifiConfiguration oldConfig,
Listener listener) {
WifiConfigCreationDialog dialog = new WifiConfigCreationDialog();
dialog.mOldConfig = oldConfig;
dialog.mListener = listener;
// For a config to be updated we allow the current password if there is one.
dialog.mPasswordDirty =
// Security type is neither WPA ...
!oldConfig.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)
// ... nor WEP.
&& !oldConfig.allowedAuthAlgorithms.get(WifiConfiguration.AuthAlgorithm.SHARED);
return dialog;
}
private static void changeNetworkWEP(WifiManager wifiManager, WifiParsedResult wifiResult) {
WifiConfiguration config = changeNetworkCommon(wifiResult);
config.wepKeys[0] = quoteNonHex(wifiResult.getPassword(), 10, 26, 58);
config.wepTxKeyIndex = 0;
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
updateNetwork(wifiManager, config);
}
public static WifiConfiguration getConfiguredNetwork (Context context, String ssid) {
final WifiManager wifiManager = getWiFiManager(context);
for (WifiConfiguration i : wifiManager.getConfiguredNetworks()) {
String thisSsid = getUnquotedSsid(i.SSID);
if (!StringUtils.isEmpty(thisSsid) && thisSsid.equals(getUnquotedSsid(ssid))) {
return i;
}
}
return null;
}
@RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
@Nullable
static WifiConfiguration getWifiConfiguration(@NonNull final WifiManager wifiMgr, @NonNull final WifiConfiguration configToFind) {
final String ssid = configToFind.SSID;
if (ssid == null || ssid.isEmpty()) {
return null;
}
final String bssid = configToFind.BSSID != null ? configToFind.BSSID : "";
final String security = getSecurity(configToFind);
final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
if (configurations == null) {
wifiLog("NULL configs");
return null;
}
for (final WifiConfiguration config : configurations) {
if (bssid.equals(config.BSSID) || ssid.equals(config.SSID)) {
final String configSecurity = getSecurity(config);
if (Objects.equals(security, configSecurity)) {
return config;
}
}
}
wifiLog("Couldn't find " + ssid);
return null;
}
/**
* 配置Wifi AP
*
* @param wifiConfig 配置
* @param enable 是否开启, {@code true}为开启, {@code false}为关闭
* @return {@code true} 操作成功, {@code false} 出现异常
*/
private boolean setWifiAp(WifiConfiguration wifiConfig, boolean enable) {
try {
if (enable) {
closeWifi();// 开启热点需要关闭Wifi
}
Method method =
mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
return (Boolean) method.invoke(mWifiManager, wifiConfig, enable);
} catch (Exception e) {
Log.e(this.getClass().toString(), "", e);
return false;
}
}
/**
* This method takes a given String, searches the current list of configured WiFi
* networks, and returns the networkId for the network if the SSID matches. If not,
* it returns -1.
*/
private int ssidToNetworkId(String ssid) {
List<WifiConfiguration> currentNetworks = wifiManager.getConfiguredNetworks();
int networkId = -1;
// For each network in the list, compare the SSID with the given one
for (WifiConfiguration test : currentNetworks) {
if ( test.SSID.equals(ssid) ) {
networkId = test.networkId;
}
}
return networkId;
}
/**
* Configure a network, and connect to it.
* @param wifiMgr
* @param scanResult
* @param password Password for secure network or is ignored.
* @return
*/
public static boolean connectToNewNetwork(final WifiManager wifiMgr, final ScanResult scanResult, final String password) {
//1.获取wifi加密方式(WEP, WPA, WPA2, WPA_EAP, IEEE8021X)
final String security = getScanResultSecurity(scanResult);
if(security.equals(OPEN)) {
final int numOpenNetworksKept = 10;
checkForExcessOpenNetworkAndSave(wifiMgr, numOpenNetworksKept);
}
WifiConfiguration config = new WifiConfiguration();
config.SSID = StringUtils.convertToQuotedString(scanResult.SSID);
config.BSSID = scanResult.BSSID;
setupSecurity(config, security, password);
int id = wifiMgr.addNetwork(config);
if(id == -1) {
return false;
}
if(!wifiMgr.saveConfiguration()) {
return false;
}
config = getWifiConfiguration(wifiMgr, config, security);
if(config == null) {
return false;
}
return connectToConfiguredNetwork(wifiMgr, config, true);
}
public void unsetWifiProxySettings() throws Exception {
MyLog.entry();
final WifiConfiguration config = findCurrentWifiConfiguration();
if (null == config) {
throw new Exception("Current WIFI configuration not found");
}
//get the link properties from the wifi configuration
final Object linkProperties = getField(config, "linkProperties");
if (null == linkProperties) {
throw new Exception("linkProperties not found");
}
//get the setHttpProxy method for LinkProperties
final Class proxyPropertiesClass = Class.forName("android.net.ProxyProperties");
final Class[] setHttpProxyParams = new Class[]{proxyPropertiesClass};
final Class lpClass = Class.forName("android.net.LinkProperties");
final Method setHttpProxy = lpClass.getDeclaredMethod("setHttpProxy", setHttpProxyParams);
setHttpProxy.setAccessible(true);
//pass null as the proxy
final Object[] params = new Object[]{null};
setHttpProxy.invoke(linkProperties, params);
setProxySettings("NONE", config);
saveConfig(config);
MyLog.exit();
}
public static WifiConfiguration getWifiHotspotConfiguration(final Context pContext) throws WifiUtilsException {
final WifiManager wifiManager = WifiUtils.getWifiManager(pContext);
try {
final Method WifiManager_getWifiApState = wifiManager.getClass().getMethod("getWifiApConfiguration");
if (WifiManager_getWifiApState == null) {
throw new WifiUtilsException(new MethodNotFoundException(WifiManager.class.getSimpleName() + ".getWifiApConfiguration()"));
} else {
return (WifiConfiguration)WifiManager_getWifiApState.invoke(wifiManager);
}
} catch (final Throwable t) {
throw new WifiUtilsException(t);
}
}
/**
* This method uses the callbackContext.success method to send a JSONArray of the currently
* configured networks.
*
* @param callbackContext A Cordova callback context
* @return true if network disconnected, false if failed
*/
private boolean listNetworks(CallbackContext callbackContext) {
Log.d(TAG, "WifiWizard2: listNetworks entered.");
List<WifiConfiguration> wifiList = wifiManager.getConfiguredNetworks();
JSONArray returnList = new JSONArray();
for (WifiConfiguration wifi : wifiList) {
returnList.put(wifi.SSID);
}
callbackContext.success(returnList);
return true;
}
@Override
public void onClick(View view) {
if (view == mSaveButton) {
WifiConfiguration config = new WifiConfiguration();
config.SSID = getQuotedString(mSsidText.getText().toString());
updateConfigurationSecurity(config);
if (mOldConfig != null) {
config.networkId = mOldConfig.networkId;
}
boolean success = WifiConfigUtil.saveWifiConfiguration(getActivity(), config);
showToast(success ? R.string.wifi_config_success : R.string.wifi_config_fail);
}
dismiss();
}
@PhonkMethod(description = "Connect to mContext given Wifi network with mContext given 'wpa', 'wep', 'open' type and mContext password", example = "")
@PhonkMethodParam(params = {"ssidName", "type", "password"})
public void connectWifi(String networkSSID, String type, String networkPass) {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String
// should contain ssid in quotes
if (type.equals("wep")) {
// wep
conf.wepKeys[0] = "\"" + networkPass + "\"";
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
} else if (type.equals("wpa")) {
// wpa
conf.preSharedKey = "\"" + networkPass + "\"";
} else if (type.equals("open")) {
// open
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}
WifiManager wifiManager = (WifiManager) getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
}
/**
* Connection confirmation to the specified Wifi.
*
* @param wifiConfig wifi settings
* @param password pasword
*/
private void testConnectWifi(final WifiConfiguration wifiConfig, final String password) {
showConnectionProgress();
final int networkId = mWifiMgr.addNetwork(wifiConfig);
mLogger.info("addNetwork: networkId = " + networkId);
if (networkId != -1) {
mWifiMgr.saveConfiguration();
mWifiMgr.updateNetwork(wifiConfig);
new Thread(() -> {
// Since the addNetwork and does not wait a little from the set is not reflected, to wait a little
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
return;
}
if (!connectWifi(networkId, wifiConfig.SSID)) {
connectTheta();
} else {
if (password != null) {
mSettings.setSSIDPassword(wifiConfig.SSID, password);
}
}
}).start();
} else {
ThetaDialogFragment.showAlert(getActivity(), getString(R.string.theta_confirm_wifi),
getString(R.string.camera_search_message_not_found), null);
mServiceIdView.setText(R.string.camera_search_message_not_found);
}
}
/**
* 创建 Wifi 热点配置 ( 支持 无密码 /WPA2 PSK)
* @param ssid Wifi ssid
* @param pwd 密码 ( 需要大于等于 8 位 )
* @return {@link WifiConfiguration}
*/
public static WifiConfiguration createWifiConfigToAp(final String ssid, final String pwd) {
try {
// 创建一个新的网络配置
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.allowedAuthAlgorithms.clear();
wifiConfig.allowedGroupCiphers.clear();
wifiConfig.allowedKeyManagement.clear();
wifiConfig.allowedPairwiseCiphers.clear();
wifiConfig.allowedProtocols.clear();
wifiConfig.priority = 0;
// 设置连接的 SSID
wifiConfig.SSID = ssid;
// 判断密码
if (TextUtils.isEmpty(pwd)) {
wifiConfig.hiddenSSID = true;
wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
} else {
wifiConfig.preSharedKey = pwd;
wifiConfig.hiddenSSID = true;
wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
// wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifiConfig.status = WifiConfiguration.Status.ENABLED;
}
return wifiConfig;
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "createWifiConfigToAp");
}
return null;
}
protected void saveConfig(WifiConfiguration config) {
MyLog.entry();
mWifiManager.updateNetwork(config);
mWifiManager.saveConfiguration();
mWifiManager.disconnect();
mWifiManager.reconnect();
MyLog.exit();
}
/**
* 判断 Wifi 加密类型, 是否为加密类型
* @param wifiConfig Wifi 配置信息
* @return {@code true} yes, {@code false} no
*/
public static boolean isExistsPwd(final WifiConfiguration wifiConfig) {
if (wifiConfig == null) return false;
int wifiSecurity = getSecurity(wifiConfig);
// 判断是否加密
return (wifiSecurity != SECURITY_NONE);
}