我有一个检查互联网状态的功能:
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冻结了几秒钟。所以我决定使用Thread,但是我不知道如何在线程中返回变量。
我的意思是:
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();
}
答案 0 :(得分: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");
}