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

后端 未结 30 3522
猫巷女王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 04:53

    You can iterate over all network connections and chek whether there is at least one available connection:

    public boolean isConnected() {
        boolean connected = false;
    
        ConnectivityManager cm = 
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
        if (cm != null) {
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    
            for (NetworkInfo ni : netInfo) {
                if ((ni.getTypeName().equalsIgnoreCase("WIFI")
                        || ni.getTypeName().equalsIgnoreCase("MOBILE"))
                        && ni.isConnected() && ni.isAvailable()) {
                    connected = true;
                }
    
            }
        }
    
        return connected;
    }
    

提交回复
热议问题