Android - Programmatically check internet connection and display dialog if notConnected

后端 未结 14 2512
予麋鹿
予麋鹿 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 05:00

    The fact the your device has network connectivity doesn't mean that you can access internet. It can be a wifi without internet or a data SIM without data package. Starting from API 23 you can use below to check it. You can do it on the UI. Or within a broadcast receiver.

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    Network currentnetwork = cm.getActiveNetwork();
    if (currentnetwork != null) {
            if (cm.getNetworkCapabilities(currentnetwork).hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && cm.getNetworkCapabilities(currentnetwork).hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
                
                // do your stuff. We have internet.
        } else {
                // We have no internet connection.
            }
    
       } else {
           // We have no internet connection.
       }
    

提交回复
热议问题