android.net.wifi.WifiConfiguration Java Examples

The following examples show how to use android.net.wifi.WifiConfiguration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConnectorUtils.java    From WifiUtils with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: WifiConfigManager.java    From Study_Android_Demo with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example #3
Source File: SetupService.java    From astrobee_android with Apache License 2.0 6 votes vote down vote up
/**
 * 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.");
}
 
Example #4
Source File: IOTWifiModule.java    From react-native-iot-wifi with MIT License 6 votes vote down vote up
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;
}
 
Example #5
Source File: WifiConfigManager.java    From BarcodeEye with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example #6
Source File: ConnectorUtils.java    From WifiUtils with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #7
Source File: IOTWifiModule.java    From react-native-iot-wifi with MIT License 6 votes vote down vote up
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;
}
 
Example #8
Source File: WifiConfigCreationDialog.java    From android-testdpc with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #9
Source File: WiFiUtil.java    From RairDemo with Apache License 2.0 6 votes vote down vote up
/**
 * 添加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;
}
 
Example #10
Source File: AndroidWifiModule.java    From react-native-android-wifi with ISC License 6 votes vote down vote up
@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);
}
 
Example #11
Source File: ConnectorUtils.java    From WifiUtils with Apache License 2.0 5 votes vote down vote up
@RequiresPermission(ACCESS_WIFI_STATE)
static boolean removeWifi(@NonNull final ConnectivityManager connectivityManager, @NonNull final WifiManager wifiManager, @NonNull final String ssid) {
    if (isAndroidQOrLater()) {
        return disconnectAndroidQ(connectivityManager);
    }

    final WifiConfiguration wifiConfiguration = ConfigSecurities.getWifiConfiguration(wifiManager, ssid);
    return cleanPreviousConfiguration(wifiManager, wifiConfiguration);
}
 
Example #12
Source File: WifiIotPlugin.java    From WiFiFlutter with MIT License 5 votes vote down vote up
/**
 * This is a network that does not broadcast its SSID, so an
 * SSID-specific probe request must be used for scans.
 */
private void isSSIDHidden(Result poResult) {
    WifiConfiguration oWiFiConfig = moWiFiAPManager.getWifiApConfiguration();
    if (oWiFiConfig != null && oWiFiConfig.hiddenSSID) {
        poResult.success(oWiFiConfig.hiddenSSID);
        return;
    }
    poResult.error("Exception", "Wifi AP not Supported", null);
}
 
Example #13
Source File: WifiApControl.java    From accesspoint with Apache License 2.0 5 votes vote down vote up
public boolean setWifiApEnabled(WifiConfiguration config, boolean enabled) {
	Object result = invokeQuietly(setWifiApEnabledMethod, wm, config, enabled);
	if (result == null) {
		return false;
	}
	return (Boolean) result;
}
 
Example #14
Source File: WifiConfigManager.java    From android-apps with MIT License 5 votes vote down vote up
private static Integer findNetworkInExistingConfig(WifiManager wifiManager, String ssid) {
  List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
  for (WifiConfiguration existingConfig : existingConfigs) {
    if (existingConfig.SSID.equals(ssid)) {
      return existingConfig.networkId;
    }
  }
  return null;
}
 
Example #15
Source File: HotspotHelper.java    From Easer with GNU General Public License v3.0 5 votes vote down vote up
boolean setApStatus(WifiConfiguration netConfig, boolean enable) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Method setWifiApMethod = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
    boolean apStatus = (boolean) setWifiApMethod.invoke(wifiManager, netConfig, enable);
    if (!apStatus) {
        apStatus = setTethering(enable);
    }
    return apStatus;
}
 
Example #16
Source File: WifiConfigManager.java    From ZXing-Standalone-library with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #17
Source File: WifiApManager.java    From WiFiFlutter with MIT License 5 votes vote down vote up
/**
 * Start AccessPoint mode with the specified
 * configuration. If the radio is already running in
 * AP mode, update the new configuration
 * Note that starting in access point mode disables station
 * mode operation
 *
 * @param wifiConfig SSID, security and channel details as part of WifiConfiguration
 * @return {@code true} if the operation succeeds, {@code false} otherwise
 */
public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
    try {
        if (enabled) { // disable WiFi in any case
            mWifiManager.setWifiEnabled(false);
        }

        Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
        return (Boolean) method.invoke(mWifiManager, wifiConfig, enabled);
    } catch (Exception e) {
        Log.e(this.getClass().toString(), "", e);
        return false;
    }
}
 
Example #18
Source File: HotspotModule.java    From react-native-wifi-hotspot with ISC License 5 votes vote down vote up
@ReactMethod
public void getConfig(Callback success, Callback error) {
    WifiConfiguration session = hotspot.getConfig();
    if(session != null) {
        WritableMap config = Arguments.createMap();
        config.putString("ssid", session.SSID);
        config.putString("password", session.preSharedKey);
        config.putBoolean("status", session.status == 2 ? true : false);
        config.putInt("networkId", session.networkId);

        success.invoke(config);
    } else {
        error.invoke("Can't fitch your configuration");
    }
}
 
Example #19
Source File: WifiApManager.java    From react-native-wifi-hotspot with ISC License 5 votes vote down vote up
/**
 * Sets the Wi-Fi AP Configuration.
 *
 * @return {@code true} if the operation succeeded, {@code false} otherwise
 */
public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) {
    try {
        Method method = mWifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
        return (Boolean) method.invoke(mWifiManager, wifiConfig);
    } catch (Exception e) {
        Log.e(this.getClass().toString(), "", e);
        return false;
    }
}
 
Example #20
Source File: WifisAdapter.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
    wifis.clear();
    if (results.values != null) wifis.addAll((ArrayList<WifiConfiguration>) results.values);
    notifyDataSetChanged();
}
 
Example #21
Source File: WifiUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 设置 IP 地址
 * @param address      IP 地址
 * @param prefixLength 网络前缀长度
 * @param wifiConfig   Wifi 配置信息
 * @throws Exception 设置失败, 抛出异常
 */
private void setIpAddress(final InetAddress address, final int prefixLength, final WifiConfiguration wifiConfig) throws Exception {
    Object linkProperties = getField(wifiConfig, "linkProperties");
    if (linkProperties == null)
        throw new NullPointerException();

    Class laClass = Class.forName("android.net.LinkAddress");
    Constructor laConstructor = laClass.getConstructor(InetAddress.class, int.class);
    Object linkAddress = laConstructor.newInstance(address, prefixLength);
    ArrayList mLinkAddresses = (ArrayList) getDeclaredField(linkProperties, "mLinkAddresses");
    mLinkAddresses.clear();
    mLinkAddresses.add(linkAddress);
}
 
Example #22
Source File: DiscoverDeviceActivity.java    From particle-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onApConnectionFailed(WifiConfiguration config) {
    hideProgressDialog();

    if (!canStartProcessAgain()) {
        onMaxAttemptsReached();
    } else {
        connectToSoftAp(config);
    }
}
 
Example #23
Source File: WifiUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 设置 DNS
 * @param dns        DNS
 * @param wifiConfig Wifi 配置信息
 * @throws Exception 设置失败, 抛出异常
 */
private void setDNS(final InetAddress dns, final WifiConfiguration wifiConfig) throws Exception {
    Object linkProperties = getField(wifiConfig, "linkProperties");
    if (linkProperties == null)
        throw new NullPointerException();

    List<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(linkProperties, "mDnses");
    mDnses.clear(); // or add a new dns address, here I just want to replace DNS1
    mDnses.add(dns);
}
 
Example #24
Source File: WifiUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 设置静态 Wifi 配置信息
 * @param wifiConfig          Wifi 配置信息
 * @param ip                  静态 IP
 * @param gateway             网关
 * @param dns                 DNS
 * @param networkPrefixLength 网络前缀长度
 * @return {@link WifiConfiguration}
 */
private WifiConfiguration setStaticWifiConfig(final WifiConfiguration wifiConfig, final String ip,
                                              final String gateway, final String dns, final int networkPrefixLength) {
    try {
        if (ip == null || gateway == null) return null;
        // 设置 InetAddress
        InetAddress intetAddress = InetAddress.getByName(ip);
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH) { // 旧的版本, 5.0 之前
            // 设置 IP 分配方式, 静态 IP
            setEnumField(wifiConfig, "STATIC", "ipAssignment");
            // 设置不用代理
            setEnumField(wifiConfig, "NONE", "proxySettings");
            // 设置 IP 地址
            setIpAddress(intetAddress, networkPrefixLength, wifiConfig);
            // 设置网关
            setGateway(InetAddress.getByName(gateway), wifiConfig);
            if (dns != null) { // 判断是否需要设置域名
                // 设置 DNS
                setDNS(InetAddress.getByName(dns), wifiConfig);
            }
        } else { // 5.0 新版本改变到其他地方
            Object object = getDeclaredField(wifiConfig, "mIpConfiguration");
            // 设置 IP 分配方式, 静态 IP
            setEnumField(object, "STATIC", "ipAssignment");
            // 设置不用代理
            setEnumField(object, "NONE", "proxySettings");
            // 设置 IP 地址、网关、DNS
            setStaticIpConfig(ip, gateway, dns, networkPrefixLength, object);
        }
        return wifiConfig;
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "setStaticWifiConfig");
    }
    return null;
}
 
Example #25
Source File: WifiUtil.java    From ShareBox with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the Wi-Fi AP Configuration.
 * @return AP details in {@link WifiConfiguration}
 */
public static WifiConfiguration getWifiApConfiguration(WifiManager wifiManager) {
    try {
        Method method = wifiManager.getClass().getMethod("getWifiApConfiguration");

        return (WifiConfiguration) method.invoke(wifiManager);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #26
Source File: NfcUtils.java    From WiFiKeyShare with GNU General Public License v3.0 5 votes vote down vote up
private static void populateAllowedKeyManagement(BitSet allowedKeyManagement, short authType) {
    if (authType == AUTH_TYPE_WPA_PSK || authType == AUTH_TYPE_WPA2_PSK) {
        allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    } else if (authType == AUTH_TYPE_WPA_EAP || authType == AUTH_TYPE_WPA2_EAP) {
        allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
    } else if (authType == AUTH_TYPE_OPEN) {
        allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    }
}
 
Example #27
Source File: WifiConfigManager.java    From zxingfragmentlib with Apache License 2.0 5 votes vote down vote up
private static Integer findNetworkInExistingConfig(WifiManager wifiManager, String ssid) {
  Iterable<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
  for (WifiConfiguration existingConfig : existingConfigs) {
    String existingSSID = existingConfig.SSID;
    if (existingSSID != null && existingSSID.equals(ssid)) {
      return existingConfig.networkId;
    }
  }
  return null;
}
 
Example #28
Source File: WifiHelper.java    From BaseProject with MIT License 5 votes vote down vote up
/**
 * 是否配置过当前wifi
 */
@RequiresPermission(Manifest.permission.ACCESS_WIFI_STATE) public WifiConfiguration existConfig(
        @NonNull ScanResult scanResult) {
    // 查看该网络是否已经配置过
    for (WifiConfiguration config : getConfiguration()) {
        if (config.SSID.equals("\"" + scanResult.SSID + "\"")) {
            return config;
        }
    }
    return null;
}
 
Example #29
Source File: WifiUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 判断 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);
}
 
Example #30
Source File: WifiUtils.java    From FlyWoo with Apache License 2.0 5 votes vote down vote up
public static String getApSSID() {
    try {
        Method localMethod = mWifiManager.getClass().getDeclaredMethod("getWifiApConfiguration",
                new Class[0]);
        if (localMethod == null)
            return null;
        Object localObject1 = localMethod.invoke(mWifiManager, new Object[0]);
        if (localObject1 == null)
            return null;
        WifiConfiguration localWifiConfiguration = (WifiConfiguration) localObject1;
        if (localWifiConfiguration.SSID != null)
            return localWifiConfiguration.SSID;
        Field localField1 = WifiConfiguration.class.getDeclaredField("mWifiApProfile");
        if (localField1 == null)
            return null;
        localField1.setAccessible(true);
        Object localObject2 = localField1.get(localWifiConfiguration);
        localField1.setAccessible(false);
        if (localObject2 == null)
            return null;
        Field localField2 = localObject2.getClass().getDeclaredField("SSID");
        localField2.setAccessible(true);
        Object localObject3 = localField2.get(localObject2);
        if (localObject3 == null)
            return null;
        localField2.setAccessible(false);
        String str = (String) localObject3;
        return str;
    } catch (Exception localException) {
    }
    return null;
}