5

I need to make my app wait until a wifi connection is fully established and only then continue to run. I have this code for now:

wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 
    if(!wifiManager.isWifiEnabled())
    {
        Toast.makeText(this, "Connecting to wifi network", Toast.LENGTH_SHORT).show();
        wifiManager.setWifiEnabled(true);
        //wait for connection to be establisihed and only then proceed


    }
Ricky
  • 258
  • 2
  • 11
  • Possible duplicate of [How to detect when WIFI Connection has been established in Android?](http://stackoverflow.com/questions/5888502/how-to-detect-when-wifi-connection-has-been-established-in-android) – naXa stands with Ukraine Jul 10 '16 at 20:27

2 Answers2

6

You can use a broadcast receiver registered for:

android.net.conn.CONNECTIVITY_CHANGE

listen the status changes and keep a variable with the current status

More information here


<receiver android:name="your.package.WifiReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
 </receiver>

And the Receiver:

public class WifiReceiver extends BroadcastReceiver {

    public static boolean connected = false;

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager mgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = mgr
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        connected = networkInfo != null && networkInfo.isConnected();
    }
}

public boolean isConnected(){
    return connected; 
}
Guillermo Merino
  • 3,197
  • 2
  • 17
  • 34
2

Instead of blocking the main thread, you could introduce a screen to the users with a connection notification to let them know what's happening.

While showing a screen with the notification you could check for a connection using the

ConnectivityManager

Note that checking only a WIFI connection will not guarantee a data service. Network issues, server downtime, authorization, etc. could always occur.

Example of usage:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Also, don't forget to add the right permission:

  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

You can find more about this on the Android Developer website: Determining and Monitoring the Connectivity Status

Good luck.

YakupKalin
  • 61
  • 4