如何在Android中ping到Google

时间:2015-07-28 13:22:04

标签: android

我正试图找到了解用户何时有Internet连接的方法,因为现在我已经有了这种方法:

public boolean isNetworkOnline() {
    boolean status=false;
    try{
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getNetworkInfo(1);
        if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
            status= true;
        }
    }catch(Exception e){
        e.printStackTrace();
        return false;
    }
    return status;
}

如果用户为CONNECTED,则此方法返回true,但如果用户有INTERNET CONNECTION,则返回true,因此我想如果此方法返回true,则调用另一种方法来检查用户是否已连接到Internet。例如,有人可以连接到路由器,但没有互联网连接,所以我想知道用户何时有互联网连接。

我已经阅读了这个answerother,但当我false时,所有人都回复了我Internet connection ....我认为这样做对www.google.com进行ping操作的方法是一种很好的方法,可以知道某人是否有互联网连接,所以我试着这样做,但这对我不起作用......

任何想法或好的方法(如果它比我的想法更好)会知道用户何时有互联网连接?

4 个答案:

答案 0 :(得分:2)

你能尝试这种方法吗?

public boolean checkInternectConnection() {
        try {
            InetAddress inAddress= InetAddress.getByName("http://google.com");
            if (inAddress.equals("")) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
    }

答案 1 :(得分:2)

检查Internet连接的简单方法

public boolean isConnectingToInternet() {
        if (networkConnectivity()) {
            try {
                Process p1 = Runtime.getRuntime().exec(
                        "ping -c 1 www.google.com");
                int returnVal = p1.waitFor();
                boolean reachable = (returnVal == 0);
                if (reachable) {
                    System.out.println("Internet access");
                    return reachable;
                } else {
                    return false;
                }
            } catch (Exception e) {
                return false;
            }
        } else
            return false;

    }

    private boolean networkConnectivity() {
        ConnectivityManager cm = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }

如何调用

  if (isConnectingToInternet()) {

       // internet is connected and work properly...
    }
else {

    // something  went wrong internet not working properly...
}

答案 2 :(得分:1)

请检查this的答案,看看它是否有用

您可以试用此代码

try {
    URL url = new URL("http://"+params[0]);

    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
    urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
    urlc.setRequestProperty("Connection", "close");
    urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
    urlc.connect();

    if (urlc.getResponseCode() == 200) {
        Main.Log("getResponseCode == 200");
        return new Boolean(true);
    }
} catch (MalformedURLException e1) {
    e1.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

答案 3 :(得分:1)

这是我修复此问题并将其用作实用程序方法的方法,可以从任何活动/片段等中调用该方法:

public static boolean isNetworkAvailable(Context context) {
            ConnectivityManager connectivityManager
                    = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }//check if Wifi or Mobile data is enabled


private static class NetworkAsync extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected Boolean doInBackground(Void... voids) {
        try {
            HttpURLConnection urlConnection = (HttpURLConnection)
                    (new URL("http://clients3.google.com/generate_204")
                            .openConnection());
            urlConnection.setRequestProperty("User-Agent", "Android");
            urlConnection.setRequestProperty("Connection", "close");
            urlConnection.setConnectTimeout(1500);
            urlConnection.connect();
            return (urlConnection.getResponseCode() == 204 &&
                    urlConnection.getContentLength() == 0);
        } catch (IOException e) {
            // Error checking internet connection
        }
        return false;
    }
}//network calls shouldn't be called from main thread otherwise it will throw //NetworkOnMainThreadException

现在您只需要在所需的任何地方调用此方法:

public static boolean checkInternetConnection(Context context) {
        if (isNetworkAvailable(context)) {
            try {
                //used execute().get(); so that it gets awaited and returns the result 
                //after i receive a response
                return new NetworkAsync().execute().get();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return false;
    }