Java Code Examples for android.net.wifi.WifiManager#enableNetwork()

The following examples show how to use android.net.wifi.WifiManager#enableNetwork() . 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: NetworkHelper.java    From letv with Apache License 2.0 6 votes vote down vote up
public static boolean wifiConnection(Context context, String wifiSSID, String password) {
    WifiManager wifi = (WifiManager) context.getSystemService("wifi");
    String strQuotationSSID = "\"" + wifiSSID + "\"";
    WifiInfo wifiInfo = wifi.getConnectionInfo();
    if (wifiInfo != null && (wifiSSID.equals(wifiInfo.getSSID()) || strQuotationSSID.equals(wifiInfo.getSSID()))) {
        return true;
    }
    List<ScanResult> scanResults = wifi.getScanResults();
    if (scanResults == null || scanResults.size() == 0) {
        return false;
    }
    for (int nAllIndex = scanResults.size() - 1; nAllIndex >= 0; nAllIndex--) {
        String strScanSSID = ((ScanResult) scanResults.get(nAllIndex)).SSID;
        if (wifiSSID.equals(strScanSSID) || strQuotationSSID.equals(strScanSSID)) {
            WifiConfiguration config = new WifiConfiguration();
            config.SSID = strQuotationSSID;
            config.preSharedKey = "\"" + password + "\"";
            config.status = 2;
            return wifi.enableNetwork(wifi.addNetwork(config), false);
        }
    }
    return false;
}
 
Example 2
Source File: WifiConfigManager.java    From reacteu-app with MIT License 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
 * @return network ID of the connected network.
 */
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: WifiConfigManager.java    From barcodescanner-lib-aar with MIT License 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 4
Source File: WifiConfigManager.java    From analyzer-of-android-for-Apache-Weex 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 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
public static boolean reEnableNetworkIfPossible(@Nullable final WifiManager wifiManager, @Nullable final ScanResult scanResult) {
    if (wifiManager == null) {
        return false;
    }
    @Nullable
    final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
    if (configurations == null || scanResult == null || configurations.isEmpty()) {
        return false;
    }
    boolean result = false;
    for (WifiConfiguration wifiConfig : configurations)
        if (Objects.equals(scanResult.BSSID, wifiConfig.BSSID) && Objects.equals(scanResult.SSID, trimQuotes(wifiConfig.SSID))) {
            result = wifiManager.enableNetwork(wifiConfig.networkId, true);
            break;
        }
    wifiLog("reEnableNetworkIfPossible " + result);
    return result;
}
 
Example 7
Source File: ConnectorUtils.java    From WifiUtils with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("UnusedReturnValue")
private static boolean disableAllButOne(@Nullable final WifiManager wifiManager, @Nullable final ScanResult scanResult) {
    if (wifiManager == null) {
        return false;
    }
    @Nullable
    final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
    if (configurations == null || scanResult == null || configurations.isEmpty()) {
        return false;
    }
    boolean result = false;
    for (WifiConfiguration wifiConfig : configurations) {
        if (wifiConfig == null) {
            continue;
        }
        if (Objects.equals(scanResult.BSSID, wifiConfig.BSSID) && Objects.equals(scanResult.SSID, trimQuotes(wifiConfig.SSID))) {
            result = wifiManager.enableNetwork(wifiConfig.networkId, true);
        } else {
            wifiManager.disableNetwork(wifiConfig.networkId);
        }
    }
    return result;
}
 
Example 8
Source File: ConnectorUtils.java    From WifiUtils with Apache License 2.0 6 votes vote down vote up
private static boolean disableAllButOne(@Nullable final WifiManager wifiManager, @Nullable final WifiConfiguration config) {
    if (wifiManager == null) {
        return false;
    }
    @Nullable
    final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
    if (configurations == null || config == null || configurations.isEmpty()) {
        return false;
    }
    boolean result = false;

    for (WifiConfiguration wifiConfig : configurations) {
        if (wifiConfig == null) {
            continue;
        }
        if (wifiConfig.networkId == config.networkId) {
            result = wifiManager.enableNetwork(wifiConfig.networkId, true);
        } else {
            wifiManager.disableNetwork(wifiConfig.networkId);
        }
    }
    wifiLog("disableAllButOne " + result);
    return result;
}
 
Example 9
Source File: WiFiUtils.java    From FimiX8-RE with MIT License 6 votes vote down vote up
public static boolean connectWifi(WifiManager wifiManager, int netId) {
    if (netId == -1) {
        return false;
    }
    List<WifiConfiguration> wifiConfigList = wifiManager.getConfiguredNetworks();
    if (wifiConfigList == null || wifiConfigList.size() <= 0) {
        return false;
    }
    for (int i = 0; i < wifiConfigList.size(); i++) {
        if (((WifiConfiguration) wifiConfigList.get(i)).networkId == netId) {
            boolean connectOkay = wifiManager.enableNetwork(netId, true);
            wifiManager.saveConfiguration();
            return connectOkay;
        }
    }
    return false;
}
 
Example 10
Source File: ConnectorUtils.java    From WifiUtils with Apache License 2.0 5 votes vote down vote up
static void reenableAllHotspots(@Nullable WifiManager wifi) {
    if (wifi == null) {
        return;
    }
    final List<WifiConfiguration> configurations = wifi.getConfiguredNetworks();
    if (configurations != null && !configurations.isEmpty()) {
        for (final WifiConfiguration config : configurations) {
            wifi.enableNetwork(config.networkId, false);
        }
    }
}
 
Example 11
Source File: NetworkConnectionUtils.java    From YiZhi with Apache License 2.0 5 votes vote down vote up
/**
 * 给温控器成功发送联网命令后,连接温控器连接的wifi节点
 *
 * @param context  上下文对象
 * @param ssid     ssid
 * @param password 密码
 */
public static void connectWifiSSID(Context context, WifiManager manager, String ssid, String
        password) {
    e("reSetNetwork----------连接设备连入的路由---" + ssid);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        e("当前手机系统>=Android6.0,采取兼容模式");
        new WifiAutoConnectManager(manager).connect(ssid, password, WifiAutoConnectManager
                .getCipherType(context, ssid));
    } else {
        int networkId = manager.addNetwork(getWifiConfiguration(manager, ssid, password));
        if (networkId != -1) {
            manager.enableNetwork(networkId, true);
        }
    }
}
 
Example 12
Source File: ChangeWifiNetworkTask.java    From arcusandroid with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to connect to the wifi network identified by networkId. Returns true if the connection
 * attempt was successful; false otherwise.
 *
 * @param networkId
 * @return
 */
private boolean setCurrentWifiNetwork(int networkId) {
    final WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    if (wifiManager == null) {
        return false;
    }

    logger.debug("Changing wifi to network id {}, disconnecting from current network; success={}", networkId, wifiManager.disconnect());

    boolean success = wifiManager.enableNetwork(networkId, true);
    logger.debug("Request to connect to network id {}; success={}", networkId, success);

    return success;
}
 
Example 13
Source File: ConfirmConnectToWifiNetworkActivity.java    From WiFiKeyShare with GNU General Public License v3.0 5 votes vote down vote up
private void doConnect(WifiManager wifiManager) {
    int networkId = wifiManager.addNetwork(wifiConfiguration);

    if (networkId < 0) {
        showFailToast();
    } else {
        boolean connected = wifiManager.enableNetwork(networkId, true);
        if (connected) {
            Toast.makeText(ConfirmConnectToWifiNetworkActivity.this,
                    R.string.confirm_connection_status_wifi_connected, Toast.LENGTH_SHORT).show();
        } else {
            showFailToast();
        }
    }
}
 
Example 14
Source File: ConnectorUtils.java    From WifiUtils with Apache License 2.0 5 votes vote down vote up
@RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
private static boolean connectToConfiguredNetwork(@Nullable WifiManager wifiManager, @Nullable WifiConfiguration config, boolean reassociate) {
    if (config == null || wifiManager == null) {
        return false;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return disableAllButOne(wifiManager, config) && (reassociate ? wifiManager.reassociate() : wifiManager.reconnect());
    }

    // Make it the highest priority.
    int newPri = getMaxPriority(wifiManager) + 1;
    if (newPri > MAX_PRIORITY) {
        newPri = shiftPriorityAndSave(wifiManager);
        config = ConfigSecurities.getWifiConfiguration(wifiManager, config);
        if (config == null) {
            return false;
        }
    }

    // Set highest priority to this configured network
    config.priority = newPri;
    int networkId = wifiManager.updateNetwork(config);
    if (networkId == -1) {
        return false;
    }

    // Do not disable others
    if (!wifiManager.enableNetwork(networkId, false)) {
        return false;
    }

    if (!wifiManager.saveConfiguration()) {
        return false;
    }

    // We have to retrieve the WifiConfiguration after save.
    config = ConfigSecurities.getWifiConfiguration(wifiManager, config);
    return config != null && disableAllButOne(wifiManager, config) && (reassociate ? wifiManager.reassociate() : wifiManager.reconnect());
}
 
Example 15
Source File: WifiScannerService.java    From karmadetector with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean createDecoyNetwork() {
    decoySsid = "KD-" + getRandomString(13);

    wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.SSID = decoySsid;
    wifiConfiguration.preSharedKey = "\"".concat(getRandomString(63)).concat("\"");
    wifiConfiguration.hiddenSSID = true;
    wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
    wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

    //Log.d("WifiPreference", "going to add network " + decoySsid);
    int networkId = wifiManager.addNetwork(wifiConfiguration);
    if (networkId == -1) {
        addToLog("Error adding decoy network!");
        return false;
    }
    //Log.d("WifiPreference", "add Network returned " + networkId);
    boolean es = wifiManager.saveConfiguration();
    //Log.d("WifiPreference", "saveConfiguration returned " + es);
    if (!es) {
        addToLog("Error saving the network configuration for the decoy network!");
        return false;
    }
    boolean b = wifiManager.enableNetwork(networkId, false);
    //Log.d("WifiPreference", "enableNetwork returned " + b);
    if (!b) {
        addToLog("Error enabling the decoy network!");
        return false;
    }
    return true;
}
 
Example 16
Source File: WifiHelper.java    From android-wear-gopro-remote with Apache License 2.0 4 votes vote down vote up
public static boolean connectToWifi(Context context, int networkId) {

        if(networkId <= -3) return false; // Do nothing

        final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager == null) {
            Logger.error(TAG, "No WiFi manager");
            return false;
        }

        WifiInfo info = wifiManager.getConnectionInfo();
        if(info != null && info.getNetworkId() == networkId) {
            return true;
        }

        if(networkId == -2) { // Disable
            return wifiManager.setWifiEnabled(false);
        }

        if(!wifiManager.isWifiEnabled()) {
            return false;
        }

        if (!wifiManager.disconnect()) {
            Logger.error(TAG, "WiFi disconnect failed");
            return false;
        }

        if(networkId == -1) { // Disconnect
            return true;
        }

        if (!wifiManager.enableNetwork(networkId, true)) {
            Logger.error(TAG, "Could not enable WiFi.");
            return false;
        }

        if (!wifiManager.reconnect()) {
            Logger.error(TAG, "WiFi reconnect failed");
            return false;
        }

        return true;
    }
 
Example 17
Source File: WifiBaseActivity.java    From android-wifi-activity with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
    List<ScanResult> scanResultList = wifi.getScanResults();
    boolean found = false;
    String security = null;
    for (ScanResult scanResult : scanResultList) {
        if (scanResult.SSID.equals(getWifiSSID())) {
            security = getScanResultSecurity(scanResult);
            found = true;
            break; // found don't need continue
        }
    }
    if (!found) {
        // if no wifi network with the specified ssid is not found exit
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        new AlertDialog.Builder(WifiBaseActivity.this)
                .setCancelable(false)
                .setMessage(String.format(getString(R.string.wifi_not_found), getWifiSSID()))
                .setPositiveButton(getString(R.string.exit_app), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        unregisterReceiver(ScanReceiver.this);
                        finish();
                    }
                })
                .show();
    } else {
        // configure based on security
        final WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + getWifiSSID() + "\"";
        switch (security) {
            case WEP:
                conf.wepKeys[0] = "\"" + getWifiPass() + "\"";
                conf.wepTxKeyIndex = 0;
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                break;
            case PSK:
                conf.preSharedKey = "\"" + getWifiPass() + "\"";
                break;
            case OPEN:
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                break;
        }
        connectionReceiver = new ConnectionReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        registerReceiver(connectionReceiver, intentFilter);
        List<WifiConfiguration> list = wifi.getConfiguredNetworks();
        for( WifiConfiguration i : list ) {
            wifi.removeNetwork(i.networkId);
            wifi.saveConfiguration();
        }
        int netId = wifi.addNetwork(conf);
        wifi.enableNetwork(netId, true);
        wifi.reconnect();
        unregisterReceiver(this);

    }
}
 
Example 18
Source File: WifiHelper.java    From android-wear-gopro-remote with Apache License 2.0 4 votes vote down vote up
public static boolean connectToWifi(Context context, final String ssid, String password) {

        int networkId = -1;
        int c;

        final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager == null) {
            Logger.error(TAG, "No WiFi manager");
            return false;
        }

        List<WifiConfiguration> list;

        if (wifiManager.isWifiEnabled()) {
            list = wifiManager.getConfiguredNetworks();
        } else {
            if (!wifiManager.setWifiEnabled(true)) {
                Logger.error(TAG, "Enable WiFi failed");
                return false;
            }
            c = 0;
            do {
                Utils.sleep(500);
                list = wifiManager.getConfiguredNetworks();
            } while (list == null && ++c < 10);
        }

        if (list == null) {
            Logger.error(TAG, "Could not get WiFi network list");
            return false;
        }

        for (WifiConfiguration i : list) {
            if (i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {
                networkId = i.networkId;
                break;
            }
        }

        WifiInfo info;
        if (networkId < 0) {
            WifiConfiguration conf = new WifiConfiguration();
            conf.SSID = "\"" + ssid + "\"";
            conf.preSharedKey = "\"" + password + "\"";
            networkId = wifiManager.addNetwork(conf);
            if (networkId < 0) {
                Logger.error(TAG, "New WiFi config failed");
                return false;
            }
        } else {
            info = wifiManager.getConnectionInfo();
            if (info != null) {
                if (info.getNetworkId() == networkId) {
                    if(Logger.DEBUG) Logger.debug(TAG, "Already connected to " + ssid);
                    return true;
                }
            }
        }

        if (!wifiManager.disconnect()) {
            Logger.error(TAG, "WiFi disconnect failed");
            return false;
        }

        if (!wifiManager.enableNetwork(networkId, true)) {
            Logger.error(TAG, "Could not enable WiFi.");
            return false;
        }

        if (!wifiManager.reconnect()) {
            Logger.error(TAG, "WiFi reconnect failed");
            return false;
        }

        c = 0;
        do {
            info = wifiManager.getConnectionInfo();
            if (info != null && info.getNetworkId() == networkId &&
                    info.getSupplicantState() == SupplicantState. COMPLETED &&  info.getIpAddress() != 0) {
                if(Logger.DEBUG) Logger.debug(TAG, "Successfully connected to %s %d", ssid, info.getIpAddress());
                return true;
            }
            Utils.sleep(500);
        } while (++c < 30);

        Logger.error(TAG, "Failed to connect to " + ssid);
        return false;
    }
 
Example 19
Source File: WiFi.java    From WifiConnecter with Apache License 2.0 4 votes vote down vote up
/**
 * Connect to a configured network.
 * @param wifiManager
 * @param config
 * @param numOpenNetworksKept Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT
 * @return
 */
public static boolean connectToConfiguredNetwork( final WifiManager wifiMgr, WifiConfiguration config, boolean reassociate) {
	final String security = getWifiConfigurationSecurity(config);
	
	int oldPri = config.priority;
	// Make it the highest priority.
	int newPri = getMaxPriority(wifiMgr) + 1;
	if(newPri > MAX_PRIORITY) {
		newPri = shiftPriorityAndSave(wifiMgr);
		config = getWifiConfiguration(wifiMgr, config, security);
		if(config == null) {
			return false;
		}
	}
	
	// Set highest priority to this configured network
	config.priority = newPri;
	int networkId = wifiMgr.updateNetwork(config);
	if(networkId == -1) {
		return false;
	}
	
	// Do not disable others
	if(!wifiMgr.enableNetwork(networkId, false)) {
		config.priority = oldPri;
		return false;
	}
	
	if(!wifiMgr.saveConfiguration()) {
		config.priority = oldPri;
		return false;
	}
	
	// We have to retrieve the WifiConfiguration after save.
	config = getWifiConfiguration(wifiMgr, config, security);
	if(config == null) {
		return false;
	}
	
	// Disable others, but do not save.
	// Just to force the WifiManager to connect to it.
	if(!wifiMgr.enableNetwork(config.networkId, true)) {
		return false;
	}
	
	final boolean connect = reassociate ? wifiMgr.reassociate() : wifiMgr.reconnect();
	if(!connect) {
		return false;
	}
	
	return true;
}
 
Example 20
Source File: WiFiUtils.java    From FimiX8-RE with MIT License 4 votes vote down vote up
public static boolean connectToAP(ScanResult device, String passkey, Context context) {
    if (device == null) {
        return false;
    }
    scanResult = device;
    WifiManager mWifiManager = (WifiManager) context.getSystemService("wifi");
    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.allowedAuthAlgorithms.clear();
    wifiConfiguration.allowedGroupCiphers.clear();
    wifiConfiguration.allowedKeyManagement.clear();
    wifiConfiguration.allowedPairwiseCiphers.clear();
    wifiConfiguration.allowedProtocols.clear();
    String networkSSID = device.SSID;
    String networkPass = passkey;
    String securityMode = getScanResultSecurity(device.capabilities);
    if (securityMode.equalsIgnoreCase("OPEN")) {
        wifiConfiguration.SSID = "\"" + networkSSID + "\"";
        wifiConfiguration.allowedKeyManagement.set(0);
        netId = mWifiManager.addNetwork(wifiConfiguration);
        if (netId == -1) {
            return false;
        }
    } else if (securityMode.equalsIgnoreCase("WEP")) {
        wifiConfiguration.SSID = "\"" + networkSSID + "\"";
        wifiConfiguration.wepKeys[0] = "\"" + networkPass + "\"";
        wifiConfiguration.wepTxKeyIndex = 0;
        wifiConfiguration.allowedKeyManagement.set(0);
        wifiConfiguration.allowedGroupCiphers.set(0);
        netId = mWifiManager.addNetwork(wifiConfiguration);
        if (netId == -1) {
            return false;
        }
    } else {
        wifiConfiguration.SSID = "\"" + networkSSID + "\"";
        wifiConfiguration.preSharedKey = "\"" + networkPass + "\"";
        wifiConfiguration.hiddenSSID = true;
        wifiConfiguration.status = 2;
        wifiConfiguration.allowedGroupCiphers.set(2);
        wifiConfiguration.allowedGroupCiphers.set(3);
        wifiConfiguration.allowedKeyManagement.set(1);
        wifiConfiguration.allowedPairwiseCiphers.set(1);
        wifiConfiguration.allowedPairwiseCiphers.set(2);
        wifiConfiguration.allowedProtocols.set(1);
        wifiConfiguration.allowedProtocols.set(0);
        netId = mWifiManager.addNetwork(wifiConfiguration);
        if (netId == -1) {
            return false;
        }
    }
    return mWifiManager.enableNetwork(netId, true);
}