How can I check if there is Internet access on my device?

    2 answers 2

    Function

    public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnectedOrConnecting(); } 

    And in the manifesto:

     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

    Took from here

    • if true returns, is there an internet connection? - java
    • Yes, see the function name - isOnline - blits
    • thanks helped - java

    I would like to add something.

    If you need to check the presence of any compound, then the method proposed by Andrei will definitely work.

    However, if it is necessary to check the availability of the Internet on the device, the method may not work as we expect. As an example I will give the following situation:

    There is a WLAN without access to the Internet, and a device that is connected to this network. What do you think, what will the isOnline() method return? isOnline() answer is true.

    If such a situation is unacceptable, then I will give a code to check the real Internet connection, honestly borrowed here .

     public boolean isReallyOnline() { 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; } 
    • understood, thanks))) - java
    • @ ermak0ff If it concerns a mobile device on android, what to write in runtime.exec("/system/bin/ping -c 1 8.8.8.8"); ? - Vyacheslav Chernyshov
    • one
      @ VyacheslavChernyshov yes, in fact, this is the code for a mobile device on android ... it should work just like that - ermak0ff