Android - Programmatically check internet connection and display dialog if notConnected

后端 未结 14 2485
予麋鹿
予麋鹿 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:57

    This is simple function that check your Internet connection. If Connected return true otherwise false.

     public boolean isInternetOn() {
    
            // get Connectivity Manager object to check connection
            ConnectivityManager connec =
                    (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
            // Check for network connections
            if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                    connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                    connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                    connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {
    
    
                return true;
    
            } else if (
                    connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                            connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {
    
    
                return false;
            }
            return false;
        }
    }
    

    Here's a project that check internet connection and also check url that valid or contain in sever this.

    0 讨论(0)
  • 2020-12-15 04:58

    NetworkInfo class is deprecated in API 29 (Android 10.0) for more detail see here:

    This class was deprecated in API level 29. Use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties to get information synchronously

    Updated Code (with Kotlin)

    var isConnected = false
    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val networkCapabilities = connectivityManager.activeNetwork ?: return false
        val activeNetwork = connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
        isConnected = when {
            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
            else -> false
        }
    } else {
        connectivityManager.run {
            activeNetworkInfo?.run {
                isConnected = when (type) {
                    ConnectivityManager.TYPE_WIFI -> true
                    ConnectivityManager.TYPE_MOBILE -> true
                    ConnectivityManager.TYPE_ETHERNET -> true
                    else -> false
                }
            }
        }
    }
    
    0 讨论(0)
  • 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.
       }
    
    0 讨论(0)
  • 2020-12-15 05:04

    An Updated Kotlin and Android 29 Version (getNetworkInfo is deprecated in SDK 29) on how to check for internet connection, works for minSDK >= 23 :

    fun hasInternet(): Boolean {
        val connectivityManager = appContainer.contextProvider.currentAppContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val network = connectivityManager.activeNetwork
    
        val capabilities = connectivityManager.getNetworkCapabilities(network)
        var hasInternet = false
        capabilities?.let {
            hasInternet = it.hasCapability(NET_CAPABILITY_INTERNET)
        }
        return hasInternet
    }
    
    0 讨论(0)
  • 2020-12-15 05:07

    You could checkout this library:

    https://github.com/novoda/merlin

    You just implement Connectable and you will get a callback when the network goes down or comes up.

    Therefore you can show your dialog in this scenario.

    You can also query the library for the current state and choose not to do your network task

    example

    Create Merlin (using Merlin.Builder())

    merlin = new Merlin.Builder().withConnectableCallbacks().build(context);
    

    Bind and unbind the service in your activity

    @Override
    protected void onResume() {
        super.onResume();
        merlin.bind();
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        merlin.unbind();
    }
    

    Register for callbacks

    merlin.registerConnectable(new Connectable() {
            @Override
            public void onConnect() {
                // Do something!
            }
    });
    

    The MerlinActivity within the demo shows a simple way to declutter Merlin from your main application code.

    0 讨论(0)
  • 2020-12-15 05:08

    Finally, I got the answer.

    ConnectivityManager conMgr =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
    if (netInfo == null){
        Description.setVisibility(View.INVISIBLE);
        new AlertDialog.Builder(WelcomePage.this)
            .setTitle(getResources().getString(R.string.app_name))
            .setMessage(getResources().getString(R.string.internet_error))
            .setPositiveButton("OK", null).show();
    }else{
        dialog = ProgressDialog.show(WelcomePage.this, "", "Loading...", true,false);
        new Welcome_Page().execute();
    }
    
    0 讨论(0)
提交回复
热议问题