COELHO G. C.
COELHO G. C.

Reputation: 41

Verify if device is connected with internet, not only with network

I need some method to verify if my network is conected to interne, and during my researchs I found some method describe below:

public static boolean hasInternetAccess(Context context) {
    if (isNetworkAvailable(context)) {
        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) {
            Log.e(TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(TAG, "No network available!");
    }
    return false;
}

...but my programs will be distributed on China, and Google is blocked on China.

I have on mind to create a method like this selecting first my localization to get a Baidoo web site - like Google on China - but make this is very expansive method to check if device is connected on some network and verify if than connected on Internet.

Upvotes: 1

Views: 1604

Answers (2)

Pomagranite
Pomagranite

Reputation: 696

China does have sites to host android apps. China has proxy servers you could use to see what is blocked and could be used to thwart whatever firewall China has. I strongly encourage you to consider legal ramifications. TCP/IP utilities or even a browser can be used to test a connection. I am not sure I fully understand your question. You have Android apps that will be used in devices located in China and a server located somewhere you want to test a connection. China has web hosting if you want to go that route. Do you need access to Google API's?

Upvotes: 0

ishmaelMakitla
ishmaelMakitla

Reputation: 3812

You could try something like this using ConnectivityManager :

public static boolean  isConnectedToInternet(Context context){
        boolean isConnected= false;
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mobile = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);        
        isConnected= (wifi.isAvailable() && wifi.isConnectedOrConnecting() || (mobile.isAvailable() && mobile.isConnectedOrConnecting()));
        return isConnected;
    }

You can also check the selected answers here and here

Upvotes: 1

Related Questions