0

我有一个检查互联网状态的功能:

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

但问题是当我在 OnClickListener 中使用它时,UI 会冻结几秒钟。所以我决定使用线程,但我不知道如何在线程中返回变量。
我是说:

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();
}
4

1 回答 1

0

为什么不使用 ConnectivityManager 来获取网络信息?

            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");
            }
于 2018-10-18T22:58:35.047 回答