Tell me how to check the availability of Internet connections? Availability, there are situations when the Internet is turned on but does not give traffic (for example, with a zero balance on the account)

Or is it easier to do a check on the connection to the server, if the Internet is turned on and the server responds, everything is fine, but if the Internet is turned on but the server is silent, then there is no access to the Internet?

  • one
    A well-worded question is half the answer! That's right, if you care only about access to specific hosts, and check them. There can be selective blocking of anything. - D-side

1 answer 1

Create a method:

public boolean isOnline() { Runtime runtime = Runtime.getRuntime(); int exitValue = -1; try { Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); exitValue = ipProcess.waitFor(); } catch (IOException | InterruptedException ignored) {} ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo != null && exitValue == 0 && netInfo.isConnectedOrConnecting(); } 

Manifest resolution:

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

Example:

 if(isOnline) //если интернет есть else //если нет 
  • one
    This is a little something, in this case there is a check "Is the Internet turned on or not?" If it is active then the check will be successful but not the fact that the traffic will go - Heaven
  • @Heaven, updated the answer - Flippy