Detect if Android device has Internet connection

后端 未结 15 2743
野性不改
野性不改 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:29

    try this one

    public class ConnectionDetector {
        private Context _context;
    
        public ConnectionDetector(Context context) {
            this._context = context;
        }
    
        public boolean isConnectingToInternet() {
            if (networkConnectivity()) {
                try {
                    HttpURLConnection urlc = (HttpURLConnection) (new URL(
                            "http://www.google.com").openConnection());
                    urlc.setRequestProperty("User-Agent", "Test");
                    urlc.setRequestProperty("Connection", "close");
                    urlc.setConnectTimeout(3000);
                    urlc.setReadTimeout(4000);
                    urlc.connect();
                    // networkcode2 = urlc.getResponseCode();
                    return (urlc.getResponseCode() == 200);
                } catch (IOException e) {
                    return (false);
                }
            } else
                return false;
    
        }
    
        private boolean networkConnectivity() {
            ConnectivityManager cm = (ConnectivityManager) _context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()) {
                return true;
            }
            return false;
        }
    }
    

    you'll have to add the following permission to your manifest file:

    
    
    

    Then call like that:

    if((new ConnectionDetector(MyService.this)).isConnectingToInternet()){
        Log.d("internet status","Internet Access");
    }else{
        Log.d("internet status","no Internet Access");
    }
    

提交回复
热议问题