How to programmatically check availibilty of internet connection in Android?

后端 未结 8 1916
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 04:02

I want to check programmatically whether there is an internet connection in Android phone/emulator. So that once I am sure that an internet connection is present then I\'ll

相关标签:
8条回答
  • 2020-12-09 04:23

    Try this:

    ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    
    if(connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING  ) {
       text.setText("hey your online!!!")     ;               
       //Do something in here when we are connected   
    } else if(connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED   ) {
       text.setText("Look your not online");           
    }
    
    0 讨论(0)
  • 2020-12-09 04:24

    as for the question title , you want to check the internet access ,

    so the fastest way and it is efficient at least for now ,

    thnx to levit based on his answer https://stackoverflow.com/a/27312494/3818437

    If you just want to check for a connection to any network - not caring if internet is available - then most of the answers here (including the accepted), implementing isConnectedOrConnecting() will work well. If you want to know if you have an internet connection (as the question title indicates) please read on Ping for the main name servers

     public boolean isOnline() {
    
         Runtime runtime = Runtime.getRuntime();
         try {
    
             Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
             int     exitValue = ipProcess.waitFor();
             return (exitValue == 0);
    
         } catch (IOException e)          { e.printStackTrace(); } 
           catch (InterruptedException e) { e.printStackTrace(); }
    
         return false; }
    

    That's it! Yes that short, yes it is fast, no it does not need to run in background, no you don't need root privileges.

    Possible Questions

    Is this really fast enough?

    Yes, very fast!

    Is there really no reliable way to check if internet is available, other than testing something on the internet?

    Not as far as I know, but let me know, and I will edit my answer.

    Couldn't I just ping my own page, which I want to request anyways?

    Sure! You could even check both, if you want to differentiate between "internet connection available" and your own servers beeing reachable

    What if the DNS is down?

    Google DNS (e.g. 8.8.8.8) is the largest public DNS service in the world. As of 2013 it serves 130 billion requests a day. Let 's just say, your app not responding would probably not be the talk of the day.

    Which permissions are required?

    Just internet access - what surprise ^^ (Btw have you ever thought about, how some of the methods suggested here could even have a remote glue about the availablility of internet, without this permission?)

    0 讨论(0)
  • 2020-12-09 04:29

    The method I implemented for myself:

    /*
     * isOnline - Check if there is a NetworkConnection
     * @return boolean
     */
    protected boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            return true;
        } else {
            return false;
        }
    }
    

    Be aware of that this is a NetworkConnection-Check. If there is a NetworkConnection it doesn't have to be a InternetConnection.

    0 讨论(0)
  • 2020-12-09 04:36

    this code must be run in background thread

    fun hasActiveInternetConnection(): Boolean {
        return try {
            val ipAddr: InetAddress = InetAddress.getByName("google.com")
            !ipAddr.equals("")
        } catch (e: java.lang.Exception) {
            false
        }
    }
    
    0 讨论(0)
  • 2020-12-09 04:42

    i have been using these two methods to check internet status sometimes https protocol doesn't work try http protocol

    // Check if network is available
    public static boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager)
                AppGlobals.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }
    
    // ping the google server to check if internet is really working or not
    public static boolean isInternetWorking() {
        boolean success = false;
        try {
            URL url = new URL("https://google.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(10000);
            connection.connect();
            success = connection.getResponseCode() == 200;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success;
    }
    

    if http does not work its because of the new android security they donot allow plain text communication now. for now just to by pass it.

    android:usesCleartextTraffic="true"

    0 讨论(0)
  • Because you are connected to a network does not guaruntee that you have internet, I have gone to just making my calls to the internet inside of a try catch block. Then catch the UnknownHostException to handle no internet.

    0 讨论(0)
提交回复
热议问题