Search code examples
javaandroidandroid-studiointernet-connection

How to find "no" internet data while user has internet access in android


how to find whether user(ANDROID) has both internet connection AND internet data. I knew that bellow code will check internet connectivity alone, but in my case internet access is there but the user had ran out of internet data....!

ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

how to identify whether the user has internet data balance or not...?


Solution

  • You can check internet access by following code. It will ping google and check internet access if internet is working then method will return true

    public boolean isConnectingToInternetAccess(){
            ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
              if (connectivity != null)
              {
                  NetworkInfo[] info = connectivity.getAllNetworkInfo();
                  if (info != null)
                      for (int i = 0; i < info.length; i++)
                          if (info[i].getState() == NetworkInfo.State.CONNECTED)
                          {
                        	  try {
                        	        Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
                        	        int returnVal = p1.waitFor();
                        	        boolean reachable = (returnVal==0);
                        	        return reachable;
                        	    } catch (Exception e) {
                        	        // TODO Auto-generated catch block
                        	        e.printStackTrace();
                        	    }
                        	  return true;
                          }
              }
              return false;
        }