How to check internet access on Android? InetAddress never times out

后端 未结 30 3317
猫巷女王i
猫巷女王i 2020-11-21 04:45

I got a AsyncTask that is supposed to check the network access to a host name. But the doInBackground() is never timed out. Anyone have a clue?

30条回答
  •  北海茫月
    2020-11-21 05:12

    I made this code, it is the simplest and it is just a boolean. by asking if(isOnline()){

    You get if there is a connection and if it can connect to a page the status code 200 (stable connection).

    Make sure to add the correct INTERNET and ACCESS_NETWORK_STATE permissions.

    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) 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(3000);
                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;
    }
    

提交回复
热议问题