Android - Programmatically check internet connection and display dialog if notConnected

后端 未结 14 2497
予麋鹿
予麋鹿 2020-12-15 04:04

I am working on a live project. and when user click on the app. the welcome screen appears(there is a webview on that screen). and if the internet is not connected then the

14条回答
  •  死守一世寂寞
    2020-12-15 04:52

    if (InternetConnection.checkConnection(context)) {
        // Internet Available...
    } else {
        // Internet Not Available...
    }
    

    just copy below class

    public class InternetConnection {
    
        /** CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT */
        public static boolean checkConnection(Context context) {
            final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    
            NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
    
            if (activeNetworkInfo != null) { // connected to the internet
                Toast.makeText(context, activeNetworkInfo.getTypeName(), Toast.LENGTH_SHORT).show();
    
                if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    // connected to wifi
                    return true;
                } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    // connected to the mobile provider's data plan
                    return true;
                }
            }
            return false;
        }
    }
    

    Give following permission to manifest

    
    
    
    

提交回复
热议问题