javaandroidandroid-internet

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


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.


Solution

  • 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();
    }