How to check if I have enabled WIFI before downloading a file?

216 Views Asked by At

I have a Button that downoad a File, and works fine. If I dont have Internet conection, the file doesnt download (obviously). The problem is that the app continues trying to download, instead of stop it.

I want to show a Toast saying "The device its not connected" or some stuff like that and NOT begin the download process then. I want a function that returns true or false if I have WIFI connection avaiable AT THE MOMENT or not

I try with the answers of these post: How to check currently internet connection is available or not in android , but the function retuns always true, even with Airplane mode.

I download the File with a DownloadManager and continues after download with a BroadcastReceiver.

3

There are 3 best solutions below

1
Ashish On BEST ANSWER

Add this permission in Manifest file

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

Following condition will help you

ConnectivityManager connManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (wifi.isConnected()){
    // If Wi-Fi connected
}else{
    Toast.makeText(getApplicationContext() /*Context field*/,"Please Connect to Wifi",Toast.LENGTH_SHORT).show();
}
0
Mahmoud Waked On

Add this permission in Manifest file

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

Use this condition to check if Wifi Connected or not

ConnectivityManager connManager = (ConnectivityManager);getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// Do whatever
}
0
Sanjay Bhalani On

Here's Network connectivity checking code

public class NetworUtil {
  private static NetworkInfo activeNetwork;
  public static boolean isInternetConnected(Context context) {
      if (context == null)
         return false;
      else {
          ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
          return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }
 }
}

Below permission must be required in the AndroidManifest file.

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