Search code examples
androidwebviewwifitoast

How to alert pop up if no wifi or Internet 3G connected?


I am creating the application that using

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

And I am using WebView to launch URL. But when mobile didn't connected to WIFI and Internet 3G, in WebView appear exactly URL link.

I don't want user can see the URL link in WebView if no internet connection, how can i do it?

Best Regards, Virak


Solution

  • Check the return of the following function (true for online, false for not) and modify the output depending on what you're after.

    private boolean haveNetworkConnection() {
            boolean haveConnectedWifi = false;
            boolean haveConnectedMobile = false;
    
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();
            for (NetworkInfo ni : netInfo) {
                if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                    if (ni.isConnected())
                        haveConnectedWifi = true;
                if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                    if (ni.isConnected())
                        haveConnectedMobile = true;
            }
            return haveConnectedWifi || haveConnectedMobile;
        }
    

    If what you want is to show a popup or a toast if there is no connectivity, then having that function in your activity will allow you to do the following, which will show the Toast.

    if(!haveNetworkConnection()){
        Toast.makeText(this,"No internet connection",Toast.LENGTH_LONG).show();
    }else{
        //Do whatever you need if there IS connectivity
    }
    

    I like using the function I'm giving you (have no idea where I copied it from, months ago) because it allows me to easily modify it if I need it to only return true if I have wifi or mobile internet, allowing me for instance to download a high definition video only if the wifi connection is available.