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

The following examples show how to use android.net.wifi.WifiManager#addNetwork() . 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: WifiConfigManager.java    From ZXing-Standalone-library 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 2
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 3
Source File: WifiConfigManager.java    From 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 4
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 5
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 6
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 7
Source File: WifiConfigManager.java    From zxingfragmentlib 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 8
Source File: WifiConfigUtil.java    From android-testdpc with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a new Wifi configuration, returning the configuration's networkId, or
 * {@link #INVALID_NETWORK_ID} if the operation fails.
 */
private static int addWifiNetwork(
    WifiManager wifiManager, WifiConfiguration wifiConfiguration) {
  // WifiManager APIs are marked as deprecated but still explicitly supported for DPCs.
  int networkId = wifiManager.addNetwork(wifiConfiguration);
  if (networkId == INVALID_NETWORK_ID) {
    return INVALID_NETWORK_ID;
  }
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
    // Saving the configuration is required pre-O.
    if (!saveAddedWifiConfiguration(wifiManager, networkId)) {
      return INVALID_NETWORK_ID;
    }
  }
  return networkId;
}
 
Example 9
Source File: ChangeWifiNetworkTask.java    From arcusandroid with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 10
Source File: NetworkConnectionUtils.java    From YiZhi with Apache License 2.0 5 votes vote down vote up
/**
 * 连接指定
 *
 * @param manager
 * @param wifiSSID
 * @return
 */
public static boolean connectToSocketWifi(WifiManager manager, String wifiSSID) {
    LogUtils.i("要连接的socket wifi====>" + wifiSSID);
    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.SSID = "\"" + wifiSSID + "\"";
    wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
    wifiConfiguration.wepKeys[0] = "\"" + "\""; //小米手机MIUI7/华为EMUI4.1 需要webKey

    int networkId = manager.addNetwork(wifiConfiguration);

    if (networkId != -1) {
        manager.enableNetwork(networkId, true);
        e("连接设备成功");
        return true;
    } else {
        e("第一次连接失败,尝试第二次。");
        WifiConfiguration wifiConfiguration2 = new WifiConfiguration();
        wifiConfiguration2.SSID = "\"" + wifiSSID + "\"";
        //wifiConfiguration.wepKeys[0] = "\"" + "\"";//去掉webKey  //小米手机MIUI8不能有webKey
        wifiConfiguration2.allowedKeyManagement.set(KeyMgmt.NONE);
        networkId = manager.addNetwork(wifiConfiguration2);
        if (networkId != -1) {
            manager.enableNetwork(networkId, true);
            e("连接设备成功");
            return true;
        }
        e("连接设备失败");
    }
    return 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: PNetwork.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
@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;
        }
    }

}
 
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: WiFi.java    From WifiConnecter with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
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, 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 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: WifiBase.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) context.getSystemService(context.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(context)
                .setCancelable(false)
                .setMessage(String.format(context.getString(R.string.wifi_not_found), getWifiSSID()))
                .setPositiveButton(context.getString(R.string.exit_app), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        getActivity().unregisterReceiver(ScanReceiver.this);
                        getActivity().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;
        }
        try {context.unregisterReceiver(connectionReceiver);} catch (Exception e) {} // do nothing

        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);
        context.registerReceiver(connectionReceiver, intentFilter);
        int netId = wifi.addNetwork(conf);
        wifi.disconnect();
        wifi.enableNetwork(netId, true);
        wifi.reconnect();
        context.unregisterReceiver(this);
    }
}
 
Example 19
Source File: WifiManagerModule.java    From react-native-wifi-manager with MIT License 4 votes vote down vote up
public void connectTo(ScanResult result, String password, String ssid) {
  //Make new configuration
  WifiConfiguration conf = new WifiConfiguration();
  conf.SSID = "\"" + ssid + "\"";
  String Capabilities = result.capabilities;
  if (Capabilities.contains("WPA2")) {
    conf.preSharedKey = "\"" + password + "\"";
  } else if (Capabilities.contains("WPA")) {
    conf.preSharedKey = "\"" + password + "\"";
  } else if (Capabilities.contains("WEP")) {
    conf.wepKeys[0] = "\"" + password + "\"";
    conf.wepTxKeyIndex = 0;
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
  } else {
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
  }
  //Remove the existing configuration for this netwrok
  WifiManager mWifiManager = (WifiManager) getReactApplicationContext().getSystemService(Context.WIFI_SERVICE);
  List<WifiConfiguration> mWifiConfigList = mWifiManager.getConfiguredNetworks();
  String comparableSSID = ('"' + ssid + '"'); //Add quotes because wifiConfig.SSID has them
  for(WifiConfiguration wifiConfig : mWifiConfigList){
    if(wifiConfig.SSID.equals(comparableSSID)){
      int networkId = wifiConfig.networkId;
      mWifiManager.removeNetwork(networkId);
      mWifiManager.saveConfiguration();
    }
  }
  //Add configuration to Android wifi manager settings...
   WifiManager wifiManager = (WifiManager) getReactApplicationContext().getSystemService(Context.WIFI_SERVICE);
   mWifiManager.addNetwork(conf);
  //Enable it so that android can connect
  List < WifiConfiguration > list = mWifiManager.getConfiguredNetworks();
  for (WifiConfiguration i: list) {
    if (i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {
      wifiManager.disconnect();
      wifiManager.enableNetwork(i.networkId, true);
      wifiManager.reconnect();
      break;
    }
  }
}
 
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);
}