How to programmatically determine if android is connected to Wi-Fi?

I am trying to set up a test for automation on a new Android application that I am developing, but have few problems with one of the apis

The problem I am facing is that I want to start the test. AFTER Wi-Fi has a connection, not when it is in a connected state. I tried two solutions, but no luck, and the test seems to start before my Android device is fully connected (no x on vinyl tablets)

wifiManager.setWifiEnabled(state); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); while (wifiInfo.getSSID() == null) { Log.i("WifiStatus", "Here I am"); Thread.sleep(Time.ONE_SECOND); wifiInfo = wifiManager.getConnectionInfo(); 

This is my first implementation trying to get an SSID to determine if a connection has been established. but the test still starts before the full connection is complete and the setup is not completed.

 ConnectivityManager connManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); wifiManager.setWifiEnabled(state); while (!networkInfo.isConnected()) { Log.i("WifiStatus", "Here I am"); Thread.sleep(Time.ONE_SECOND); networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); } 

Second implementation: Instead, I use the connection manager and using isConnected() .

Does anyone have another method that I can check to determine if Wi-Fi is fully connected?

+4
source share
2 answers

Send "ping" if you want to name it. If the connection is completed, you know that you are still connected. If you get an IOException or NullPointerException , then you probably expired and are no longer connecting.

 try { URL url = new URL("http://www.google.com"); HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection(); urlConnect.setConnectTimeout(1000); urlConnect.getContent(); System.out.println("Connection established."); } catch (NullPointerException np) { np.printStackTrace(); } catch (IOException io) { io.printStackTrace(); } 
+3
source

Instead of manually downloading networkinfo ... try to get an "active" network and check if it is Wi-Fi. Note. If this value is null, it means the network is not connected ... therefore, it replaces the isConnected call.

 ConnectivityManager connManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo current = connManager.getActiveNetworkInfo(); boolean isWifi = current != null && current.getType() == ConnectivityManager.TYPE_WIFI; 
+4
source

All Articles