¿Cómo me conecto a una red Wi-Fi específica en Android mediante progtwigción?

Quiero diseñar una aplicación que muestre una lista de redes Wi-Fi disponibles y conectarse a la red que el usuario seleccione.

Implementé la parte que muestra los resultados del análisis. Ahora quiero conectarme a una red particular seleccionada por el usuario de la lista de resultados del análisis.

¿Cómo hago esto?

    Necesitas crear WifiConfiguration instancia de WifiConfiguration como esta:

     String networkSSID = "test"; String networkPass = "pass"; WifiConfiguration conf = new WifiConfiguration(); conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain ssid in quotes 

    Entonces, para la red WEP necesita hacer esto:

     conf.wepKeys[0] = "\"" + networkPass + "\""; conf.wepTxKeyIndex = 0; conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 

    Para la red WPA, necesita agregar una frase de contraseña como esta:

     conf.preSharedKey = "\""+ networkPass +"\""; 

    Para la red Abierta necesitas hacer esto:

     conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); 

    Luego, debes agregarlo a la configuración del administrador wifi de Android:

     WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); wifiManager.addNetwork(conf); 

    Y finalmente, es posible que deba habilitarlo, para que Android se conecte a él:

     List 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; } } 

    UPD: en el caso de WEP, si su contraseña está en hexadecimal, no necesita rodearlo con comillas.

    La respuesta anterior funciona , pero la solución puede ser más simple. No es necesario realizar un bucle a través de la lista de redes configuradas ya que obtiene la identificación de la red cuando agrega la red a través del Administrador de Wifi.

    Entonces, la solución completa y simplificada sería algo como esto:

     WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = String.format("\"%s\"", ssid); wifiConfig.preSharedKey = String.format("\"%s\"", key); WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE); //remember id int netId = wifiManager.addNetwork(wifiConfig); wifiManager.disconnect(); wifiManager.enableNetwork(netId, true); wifiManager.reconnect(); 

    Antes de conectar la red WiFi, debe verificar el tipo de seguridad de la red WIFI. La clase ScanResult tiene capacidades. Este campo te da el tipo de red

    Consulte: https://developer.android.com/reference/android/net/wifi/ScanResult.html#capabilities

    Hay tres tipos de redes WIFI.

    Primero, crea una instancia de un objeto WifiConfiguration y completa el SSID de la red (ten en cuenta que debe estar entre comillas dobles), establece el estado inicial en disabled y especifica la prioridad de la red (los números alrededor de 40 parecen funcionar bien).

     WifiConfiguration wfc = new WifiConfiguration(); wfc.SSID = "\"".concat(ssid).concat("\""); wfc.status = WifiConfiguration.Status.DISABLED; wfc.priority = 40; 

    Ahora, para la parte más complicada: tenemos que llenar varios miembros de WifiConfiguration para especificar el modo de seguridad de la red. Para redes abiertas.

     wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wfc.allowedAuthAlgorithms.clear(); wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); 

    Para redes que usan WEP; tenga en cuenta que la clave WEP también está entre comillas dobles.

     wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); if (isHexString(password)) wfc.wepKeys[0] = password; else wfc.wepKeys[0] = "\"".concat(password).concat("\""); wfc.wepTxKeyIndex = 0; 

    Para las redes que usan WPA y WPA2, podemos establecer los mismos valores para cualquiera de las dos.

     wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wfc.preSharedKey = "\"".concat(password).concat("\""); 

    Finalmente, podemos agregar la red a la lista conocida de WifiManager

     WifiManager wfMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); int networkId = wfMgr.addNetwork(wfc); if (networkId != -1) { // success, can call wfMgr.enableNetwork(networkId, true) to connect } 

    Crédito a @ raji-twigmoorthi y @kenota

    La solución que funcionó para mí es la combinación de colaboradores anteriores en este hilo.

    Para obtener ScanResult aquí está el proceso.

     WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled() == false) { Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show(); wifi.setWifiEnabled(true); } BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context c, Intent intent) { wifi.getScanResults(); } }; 

    Aviso para unregister el unregister en onPause y onStop live this unregisterReceiver(broadcastReceiver);

     public void connectWiFi(ScanResult scanResult) { try { Log.v("rht", "Item clicked, SSID " + scanResult.SSID + " Security : " + scanResult.capabilities); String networkSSID = scanResult.SSID; String networkPass = "12345678"; WifiConfiguration conf = new WifiConfiguration(); conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain ssid in quotes conf.status = WifiConfiguration.Status.ENABLED; conf.priority = 40; if (scanResult.capabilities.toUpperCase().contains("WEP")) { Log.v("rht", "Configuring WEP"); conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN); conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA); conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); if (networkPass.matches("^[0-9a-fA-F]+$")) { conf.wepKeys[0] = networkPass; } else { conf.wepKeys[0] = "\"".concat(networkPass).concat("\""); } conf.wepTxKeyIndex = 0; } else if (scanResult.capabilities.toUpperCase().contains("WPA")) { Log.v("rht", "Configuring WPA"); conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN); conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA); conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); conf.preSharedKey = "\"" + networkPass + "\""; } else { Log.v("rht", "Configuring OPEN network"); conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN); conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA); conf.allowedAuthAlgorithms.clear(); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); } WifiManager wifiManager = (WifiManager) WiFiApplicationCore.getAppContext().getSystemService(Context.WIFI_SERVICE); int networkId = wifiManager.addNetwork(conf); Log.v("rht", "Add result " + networkId); List list = wifiManager.getConfiguredNetworks(); for (WifiConfiguration i : list) { if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) { Log.v("rht", "WifiConfiguration SSID " + i.SSID); boolean isDisconnected = wifiManager.disconnect(); Log.v("rht", "isDisconnected : " + isDisconnected); boolean isEnabled = wifiManager.enableNetwork(i.networkId, true); Log.v("rht", "isEnabled : " + isEnabled); boolean isReconnected = wifiManager.reconnect(); Log.v("rht", "isReconnected : " + isReconnected); break; } } } catch (Exception e) { e.printStackTrace(); } } 

    Esta es una actividad que puede crear una subclase para forzar la conexión a un wifi específico: https://github.com/zoltanersek/android-wifi-activity/blob/master/app/src/main/java/com/zoltanersek/androidwifiactivity/ WifiActivity.java

    Tendrá que subclasificar esta actividad e implementar sus métodos:

     public class SampleActivity extends WifiBaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected int getSecondsTimeout() { return 10; } @Override protected String getWifiSSID() { return "WifiNetwork"; } @Override protected String getWifiPass() { return "123456"; } } 

    Si su dispositivo conoce las configuraciones de Wifi (ya almacenadas), podemos evitar la ciencia de cohetes. Simplemente recorra las configuraciones y verifique si el SSID se corresponde. Si es así, conéctate y regresa .

    Establecer permisos:

       

    Conectar:

      try { String ssid = null; if (wifi == Wifi.PCAN_WIRELESS_GATEWAY) { ssid = AesPrefs.get(AesConst.PCAN_WIRELESS_SSID, context.getString(R.string.pcan_wireless_ssid_default)); } else if (wifi == Wifi.KJ_WIFI) { ssid = context.getString(R.string.remote_wifi_ssid_default); } WifiManager wifiManager = (WifiManager) context.getApplicationContext() .getSystemService(Context.WIFI_SERVICE); List wifiConfigurations = wifiManager.getConfiguredNetworks(); for (WifiConfiguration wifiConfiguration : wifiConfigurations) { if (wifiConfiguration.SSID.equals("\"" + ssid + "\"")) { wifiManager.enableNetwork(wifiConfiguration.networkId, true); Log.i(TAG, "connectToWifi: will enable " + wifiConfiguration.SSID); wifiManager.reconnect(); return null; // return! (sometimes logcat showed me network-entries twice, // which may will end in bugs) } } } catch (NullPointerException | IllegalStateException e) { Log.e(TAG, "connectToWifi: Missing network configuration."); } return null; 

    Me rompí la cabeza para entender por qué tus respuestas para WPA / WPA2 no funcionan … después de horas de bashs encontré lo que te estás perdiendo:

     conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); 

    ¡SE REQUIERE para redes WPA!

    Ahora funciona 🙂

    Prueba este método Es muy fácil:

     public static boolean setSsidAndPassword(Context context, String ssid, String ssidPassword) { try { WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE); Method getConfigMethod = wifiManager.getClass().getMethod("getWifiApConfiguration"); WifiConfiguration wifiConfig = (WifiConfiguration) getConfigMethod.invoke(wifiManager); wifiConfig.SSID = ssid; wifiConfig.preSharedKey = ssidPassword; Method setConfigMethod = wifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class); setConfigMethod.invoke(wifiManager, wifiConfig); return true; } catch (Exception e) { e.printStackTrace(); return false; } } 
      /** * @param context Context * @return true if device is connected to Internet */ public static boolean isNetworkConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); assert cm != null; NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); }