我已阅读以下有关在Android中获取Internet连接状态的答案:

https://stackoverflow.com/a/22256277/4225644

但这无法正常工作,例如,如果我有没有互联网访问权限的网络连接,则此方法将花费很长时间返回False:

public Boolean isOnline() {
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 false;
}


如何减少此时间以获得更快的答案?

最佳答案

使用此代码:

public static boolean isInternetConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ni = cm.getActiveNetworkInfo();

    if (ni == null)
        return false;
    else {
        if (ni.isConnected())
            if (isOnline(context))
                return true;
            else
                return false;
        return false;
    }
}


public static boolean isOnline(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {
            URL url = new URL("http://www.google.com");
            HttpURLConnection urlc = (HttpURLConnection) url
                    .openConnection();
            urlc.setConnectTimeout(2000);
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return new Boolean(true);
            }
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return false;
}

10-06 03:24