Android Check Internet Connection


Answer :

This method checks whether mobile is connected to internet and returns true if connected:

private boolean isNetworkConnected() {     ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);      return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected(); } 

in manifest,

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

Edit: This method actually checks if device is connected to internet(There is a possibility it's connected to a network but not to internet).

public boolean isInternetAvailable() {     try {         InetAddress ipAddr = InetAddress.getByName("google.com");          //You can replace it with your name             return !ipAddr.equals("");          } catch (Exception e) {             return false;     } } 

Check to make sure it is "connected" to a network:

public boolean isNetworkAvailable(Context context) {     ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));     return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected(); } 

Check to make sure it is "connected" to a internet:

public boolean isInternetAvailable() {     try {         InetAddress address = InetAddress.getByName("www.google.com");         return !address.equals("");     } catch (UnknownHostException e) {         // Log error     }     return false; } 

Permission needed:

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

https://stackoverflow.com/a/17583324/950427


You can simply ping an online website like google:

public boolean isConnected() throws InterruptedException, IOException {     String command = "ping -c 1 google.com";     return Runtime.getRuntime().exec(command).waitFor() == 0; } 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?