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

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

    Here is the method I use:

    public boolean isNetworkAvailable(final Context context) {
        return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
    }
    

    Even better, check to make sure it is "connected":

    public boolean isNetworkAvailable(final Context context) {
        final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
        return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
    }
    

    Here is how to use the method:

    if (isNetworkAvailable(context)) {
        // code here
    } else {
        // code
    }
    

    Permission needed:

    
    

    https://stackoverflow.com/a/16124915/950427

提交回复
热议问题