Check for Active internet connection Android

2019-01-05 03:03发布

I am trying to write a part in my app that will differentiate between an Active Wifi connection and an actual connection to the internet. Finding out if there is an active Wifi connection is pretty simple using the connection manager however every time I try to test if I can connect to a website when the Wifi is connected but there is no internet connection I end up in an infinite loop.
I have tried to ping google however this ends up the same way:

Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = 5;
try {
    returnVal = p1.waitFor();
} catch (InterruptedException e) {
    e.printStackTrace();
}
boolean reachable = (returnVal==0);
return reachable;

I also tried this code:

if (InetAddress.getByName("www.xy.com").isReachable(timeout))
{    }
else
{    }

but I could not get isReachable to work.

6条回答
太酷不给撩
2楼-- · 2019-01-05 03:07

Here is some modern code that uses an AsynTask to get around an issue where android crashes when you try and connect on the main thread and introduces an alert with a rinse and repeat option for the user.

class TestInternet extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            URL url = new URL("http://www.google.com");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(3000);
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            }
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (!result) { // code if not connected
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("An internet connection is required.");
            builder.setCancelable(false);

            builder.setPositiveButton(
                    "TRY AGAIN",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                            new TestInternet().execute();
                        }
                    });


            AlertDialog alert11 = builder.create();
            alert11.show();
        } else { // code if connected
            doMyStuff();
        }
    }
}

...

new TestInternet().execute();
查看更多
聊天终结者
3楼-- · 2019-01-05 03:07

I did use this method. It worked for me! For people who want to get the real Internet!

public boolean isOnline() {
    try {
        HttpURLConnection httpURLConnection = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
        httpURLConnection.setRequestProperty("User-Agent", "Test");
        httpURLConnection.setRequestProperty("Connection", "close");
        httpURLConnection.setConnectTimeout(10000);
        httpURLConnection.connect();
        return (httpURLConnection.getResponseCode() == 200);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

For doing this method every time! Just use a receiver and =>

httpURLConnection.getResponseCode() == 200 

This means the Internet is connected!

查看更多
不美不萌又怎样
4楼-- · 2019-01-05 03:09

Query a website like this:

Make your class implement AsyncTaskCompleteListenere<Boolean> by adding the following method to your class:

@Override
public void onTaskComplete(Boolean result) {
    Toast.makeText(getApplicationContext(), "URL Exist:" + result, Toast.LENGTH_LONG).show();
   // continue your job
}

Add a simple testConnection method to your class to be called when you want to check for your connectivity:

public void testConnection() {
        URLExistAsyncTask task = new URLExistAsyncTask(this);
        String URL = "http://www.google.com";
        task.execute(new String[]{URL});
    }

And finally the URLExistAsyncTask class which perform the connectivity test as an asynchronous (background) task and calls back your onTaskComplete method once done:

  public class URLExistAsyncTask extends AsyncTask<String, Void, Boolean> {
        AsyncTaskCompleteListenere<Boolean> callback;

        public URLExistAsyncTask(AsyncTaskCompleteListenere<Boolean> callback) {
            this.callback = callback;
        }

        protected Boolean doInBackground(String... params) {
            int code = 0;
            try {
                URL u = new URL(params[0]);
                HttpURLConnection huc = (HttpURLConnection) u.openConnection();
                huc.setRequestMethod("GET");
                huc.connect();
                code = huc.getResponseCode();
            } catch (IOException e) {
                return false;
            } catch (Exception e) {
                return false;
            }

            return code == 200;
        }

        protected void onPostExecute(Boolean result){
              callback.onTaskComplete(result);
        }
    }
查看更多
仙女界的扛把子
5楼-- · 2019-01-05 03:21

It does works for me:

To verify network availability:

private Boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}

To verify internet access:

public Boolean isOnline() {
    try {
        Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
        int returnVal = p1.waitFor();
        boolean reachable = (returnVal==0);
        return reachable;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}
查看更多
萌系小妹纸
6楼-- · 2019-01-05 03:24

I use this:

public static void isNetworkAvailable(Context context){
    HttpGet httpGet = new HttpGet("http://www.google.com");
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    try{
        Log.d(TAG, "Checking network connection...");
        httpClient.execute(httpGet);
        Log.d(TAG, "Connection OK");
        return;
    }
    catch(ClientProtocolException e){
        e.printStackTrace();
    }
    catch(IOException e){
        e.printStackTrace();
    }

    Log.d(TAG, "Connection unavailable");
}

It comes from an other stackoverflow answer but I can't find it.

EDIT:

Finally I found it: https://stackoverflow.com/a/1565243/2198638

查看更多
\"骚年 ilove
7楼-- · 2019-01-05 03:24

To check if the android device is having an active connection, I use this hasActiveInternetConnection() method below that (1) tries to detect if network is available and (2) then connect to google.com to determine whether the network is active.

public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        if (connectGoogle()) {
            return true;
        } else { //one more try
            return connectGoogle();
        }   
    } else {
        log("No network available! (in hasActiveInternetConnection())");
        return false;
    }
}


public static boolean isNetworkAvailable(Context ct) {
    ConnectivityManager connectivityManager = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}


public static boolean connectGoogle() {
    try {
        HttpURLConnection urlc = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(10000); 
        urlc.connect();
        return (urlc.getResponseCode() == 200);     
    } catch (IOException e) {
        log("IOException in connectGoogle())");
        return false;
    }
}
查看更多
登录 后发表回答