Detect if Android device has Internet connection

后端 未结 15 2472
野性不改
野性不改 2020-11-22 08:54

I need to tell if my device has Internet connection or not. I found many answers like:

private boolean isNetworkAvailable() {
    ConnectivityManager connect         


        
15条回答
  •  渐次进展
    2020-11-22 09:48

    Based on the accepted answers, I have built this class with a listener so you can use it in the main thread:

    First: InterntCheck class which checks for internet connection in the background then call a listener method with the result.

    public class InternetCheck extends AsyncTask {
    
    
        private Activity activity;
        private InternetCheckListener listener;
    
        public InternetCheck(Activity x){
    
            activity= x;
    
        }
    
        @Override
        protected Void doInBackground(Void... params) {
    
    
            boolean b = hasInternetAccess();
            listener.onComplete(b);
    
            return null;
        }
    
    
        public void isInternetConnectionAvailable(InternetCheckListener x){
            listener=x;
            execute();
        }
    
        private boolean isNetworkAvailable() {
            ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null;
        }
        private boolean hasInternetAccess() {
            if (isNetworkAvailable()) {
                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();
                    return (urlc.getResponseCode() == 204 &&
                            urlc.getContentLength() == 0);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Log.d("TAG", "No network available!");
            }
            return false;
        }
    
        public interface InternetCheckListener{
            void onComplete(boolean connected);
        }
    
    }
    

    Second: instantiate an instance of the class in the main thread and wait for the response (if you have worked with Firebase api for android before this should be familiar to you!).

    new InternetCheck(activity).isInternetConnectionAvailable(new InternetCheck.InternetCheckListener() {
    
            @Override
            public void onComplete(boolean connected) {
               //proceed!
            }
        });
    

    Now inside onComplete method you will get whether the device is connected to the internet or not.

提交回复
热议问题