0

I have a function for check internet state:

  public static 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;
      }

But the problem is that when I use this in OnClickListener, UI freeze for a few seconds. so I decided to use Thread, but I don't know How can I return variable in thread.
I mean:

public static boolean isOnline() {
      Thread thread = new Thread() {
        @Override
        public void run() {
          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;
        }
      };

    thread.start();
}
  • Welcome to StackOverflow. Think carefully about what return (exitValue == 0) is doing. This line is within the scope of your run method, so it is not doing what you think it's doing. If you want to do some work on a background thread and then let the main thread know about it, there are mechanisms to do this. A few are AsyncTask and Loader. – Michael Krause Oct 18 '18 at 22:44
  • maybe this helps: https://developer.android.com/guide/components/processes-and-threads – leonardkraemer Oct 18 '18 at 22:52
  • The `run()` method is a `void` return type. Seeing as all android devices show connectivity state in the app bar I'm not sure how useful this is anyway. Secondly if this is defensive check before doing a network request then it is also somewhat useless as connectivity can be lost at anytime. If your use case is the latter then it is better to assume connectivity and gracefully handle unsuccessful network attempts rather than defensive checking. – Mark Oct 18 '18 at 23:03

1 Answers1

0

Why not use ConnectivityManager to get Network info ?

            ConnectivityManager connMgr = (ConnectivityManager) 
            getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if ((networkInfo == null) || (!networkInfo.isConnected())) {
                Log.e(TAG,"onCreate():- !!! Error !!! No Net Connection Available");
            }
RKYoung
  • 43
  • 4