Search code examples
androidandroid-internet

ask user to connect to internet or quit app (android)


i am working on an image gallery app, in which application is retrieving images from internet.

so i want to prompt a dialog-box to ask user to connect to internet or quit application.

show user both WiFi and Carrier network option.


Solution

  • this checks for both wifi and mobile data..run tis code on splash or your main activity to check network connection.popup the dialog if the net is not connected and finish the activity.It's that simple

    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;
    }