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

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

    Following is the code from my Utils class:

    public static boolean isNetworkAvailable(Context context) {
            ConnectivityManager connectivityManager 
                  = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    
    0 讨论(0)
  • 2020-11-21 05:09

    check this code... it worked for me :)

    public static void isNetworkAvailable(final Handler handler, final int timeout) {
        // ask fo message '0' (not connected) or '1' (connected) on 'handler'
        // the answer must be send before before within the 'timeout' (in milliseconds)
    
        new Thread() {
            private boolean responded = false;   
            @Override
            public void run() { 
                // set 'responded' to TRUE if is able to connect with google mobile (responds fast) 
                new Thread() {      
                    @Override
                    public void run() {
                        HttpGet requestForTest = new HttpGet("http://m.google.com");
                        try {
                            new DefaultHttpClient().execute(requestForTest); // can last...
                            responded = true;
                        } 
                        catch (Exception e) {
                        }
                    } 
                }.start();
    
                try {
                    int waited = 0;
                    while(!responded && (waited < timeout)) {
                        sleep(100);
                        if(!responded ) { 
                            waited += 100;
                        }
                    }
                } 
                catch(InterruptedException e) {} // do nothing 
                finally { 
                    if (!responded) { handler.sendEmptyMessage(0); } 
                    else { handler.sendEmptyMessage(1); }
                }
            }
        }.start();
    }
    

    Then, I define the handler:

    Handler h = new Handler() {
        @Override
        public void handleMessage(Message msg) {
    
            if (msg.what != 1) { // code if not connected
    
            } else { // code if connected
    
            }   
        }
    };
    

    ...and launch the test:

    isNetworkAvailable(h,2000); // get the answser within 2000 ms
    
    0 讨论(0)
  • 2020-11-21 05:09

    Found at and modified (!) from this link :

    In your manifest file add at least:

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    

    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;
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:12

    I made this code, it is the simplest and it is just a boolean. by asking if(isOnline()){

    You get if there is a connection and if it can connect to a page the status code 200 (stable connection).

    Make sure to add the correct INTERNET and ACCESS_NETWORK_STATE permissions.

    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            try {
                URL url = new URL("http://www.google.com");
                HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                urlc.setConnectTimeout(3000);
                urlc.connect();
                if (urlc.getResponseCode() == 200) {
                    return new Boolean(true);
                }
            } catch (MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return false;
    }
    
    0 讨论(0)
  • 2020-11-21 05:13

    It is not complex to check Android network / internet connectivity status. The below DetectConnection class will help you to check this status:

    import android.content.Context;
    import android.net.ConnectivityManager;
    
    public class DetectConnection {
        public static boolean checkInternetConnection(Context context) {
            ConnectivityManager con_manager = (ConnectivityManager) context
                                    .getSystemService(Context.CONNECTIVITY_SERVICE);
    
            if (con_manager.getActiveNetworkInfo() != null
                && con_manager.getActiveNetworkInfo().isAvailable()
                && con_manager.getActiveNetworkInfo().isConnected()) {
                    return true;
            } else {
                return false;
            }
        }
    }
    

    For more details visit How to Check Android Network / Internet Connectivity Status

    0 讨论(0)
  • 2020-11-21 05:13

    I have gone through all the answers and i come up with my own answer which first check whether Internet is available and if Internet is available then it check whether it is active or not.

    I have included all necessary method and classes to check for active Internet connection.

    NetworkUtils.class

    public class NetworkUtils {
    
        public static final int STATUS_CONNECTED = 0 ;
    
        public static boolean isInternetAvailable(Context ctx){
            ConnectivityManager cm = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        }
    
        public static int isInternetActiveWithPing() {
            try {
                Runtime runtime = Runtime.getRuntime();
                Process process = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
                int exitValue = process.waitFor();
                return exitValue;
            } catch (Exception ex) {
                return -1;
            }
        }
    
        public static boolean isInternetActiveWithInetAddress() {
            try {
                InetAddress inetAddress = InetAddress.getByName("www.google.com");
                return inetAddress != null && !inetAddress.toString().equals("");
            } catch (Exception ex) {
                return false;
            }
        }
    
        public static void displayInternetConnectionMessage(Context ctx){
            Toast.makeText(ctx, "Check Internet Connection", Toast.LENGTH_SHORT).show();
        }
    }
    

    You can check whether Internet is active using below code:

     private void checkInternetConnection() {
            if (NetworkUtils.isInternetAvailable(this)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (NetworkUtils.isInternetActiveWithPing() == NetworkUtils.STATUS_CONNECTED) {
                            performNetworkingOperations();
                        } else {
                            if (NetworkUtils.isInternetActiveWithInetAddress()) {
                                performNetworkingOperations();
                            } else {
                                displayConnectionMessage();
                            }
                        }
                    }
                }).start();
    
            } else {
                displayConnectionMessage();
            }
        }
    
        private void performNetworkingOperations() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "Internet is Available", Toast.LENGTH_SHORT).show();
                }
            });
        }
    
        private void displayConnectionMessage() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    NetworkUtils.displayInternetConnectionMessage(MainActivity.this);
                }
            });
        }
    
    0 讨论(0)
提交回复
热议问题