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

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

    There's more than one way

    First, shortest but Inefficient way

    Network State Permission only needed

    
    

    Then this method,

     public boolean activeNetwork () {
            ConnectivityManager cm =
                    (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null &&
                    activeNetwork.isConnected();
    
            return isConnected;
    
        }
    

    As seen in answers ConnectivityManager is a solution, I just added it within a method this is a simplified method all use
    ConnectivityManager returns true if there is a network access not Internet access, means if your WiFi is connected to a router but the router has no internet it returns true, it check connection availability

    Second, Efficient way

    Network State and Internet Permissions needed

    
    
    

    Then this class,

     public class CheckInternetAsyncTask extends AsyncTask {
    
            private Context context;
    
            public CheckInternetAsyncTask(Context context) {
                this.context = context;
            }
    
            @Override
            protected Boolean doInBackground(Void... params) {
    
                ConnectivityManager cm =
                        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    
                assert cm != null;
                NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
                boolean isConnected = activeNetwork != null &&
                        activeNetwork.isConnected();
    
    
                if (isConnected) {
                    try {
                        HttpURLConnection urlc = (HttpURLConnection)
                                (new URL("http://clients3.google.com/generate_204")
                                        .openConnection());
                        urlc.setRequestProperty("User-Agent", "Android");
                        urlc.setRequestProperty("Connection", "close");
                        urlc.setConnectTimeout(1500);
                        urlc.connect();
                        if (urlc.getResponseCode() == 204 &&
                                urlc.getContentLength() == 0)
                            return true;
    
                    } catch (IOException e) {
                        Log.e("TAG", "Error checking internet connection", e);
                        return false;
                    }
                } else {
                    Log.d("TAG", "No network available!");
                    return false;
                }
    
    
                return null;
            }
    
            @Override
            protected void onPostExecute(Boolean result) {
                super.onPostExecute(result);
                Log.d("TAG", "result" + result);
    
                if(result){
                    // do ur code
                }
    
            }
    
    
        }
    

    Call CheckInternetAsyncTask

    new CheckInternetAsyncTask(getApplicationContext()).execute();
    

    Some Explanations :-

    • you have to check Internet on AsyncTask, otherwise it can throw android.os.NetworkOnMainThreadException in some cases

    • ConnectivityManager used to check the network access if true sends request (Ping)

    • Request send to http://clients3.google.com/generate_204, This well-known URL is known to return an empty page with an HTTP status 204 this is faster and more efficient than http://www.google.com , read this. if you have website it's preferred to put you website instead of google, only if you use it within the app

    • Timeout can be changed range (20ms -> 2000ms), 1500ms is commonly used

提交回复
热议问题