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

后端 未结 30 3329
猫巷女王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:09

    Found at and modified (!) from this link :

    In your manifest file add at least:

    
    

    You probably already have the INTERNET permission if you are accessing it. Then a boolean function that allows to test for connectivity is:

    private boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        // test for connection
        if (cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            Log.v(TAG, "Internet Connection Not Present");
            return false;
        }
    }
    

提交回复
热议问题