Search code examples
androidandroid-wifi

Checking if programm has the internet over wifi


After reading some answers and trying to use them I still can not make my code return a correct state, if there is internet over wifi or not.

I must "ping" over WIFI, because we may be connected to the Access Point with no further internet connection. Here is a complete code.

ConnectivityManager CM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo NI = CM.getActiveNetworkInfo();
boolean IC = false;             
IC = CM.requestRouteToHost(ConnectivityManager.TYPE_WIFI, FlavaGr.lookupHost(pingyIp));
System.out.println("##### IC=" + IC + "  TYPE = " + NI.getTypeName());

is here lookupHost, suggested by another user :

public static int lookupHost(String hostname) {
InetAddress inetAddress;
try {
    inetAddress = InetAddress.getByName(hostname);
} catch (UnknownHostException e) {
    return -1;
}
byte[] addrBytes;
int addr;
addrBytes = inetAddress.getAddress();
addr = ((addrBytes[3] & 0xff) << 24)
        | ((addrBytes[2] & 0xff) << 16)
        | ((addrBytes[1] & 0xff) << 8)
        |  (addrBytes[0] & 0xff);
return addr;
}   

IC is always false. I feel like the answer is in one step, but still don't know, what to do.

PS Sorry for my English.


Solution

  • My answer is :

        ConnectivityManager CM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo NI = CM.getActiveNetworkInfo();
        if (NI!=null) {
            if (NI.isAvailable()) { 
                boolean IC = false;
                if (NI.getTypeName()=="WIFI") {
                    int response = 0;
                    try {
                        URL url = new URL("http://www.google.com/");    
                        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                        response = in.read();
                        in.close();
    
                        IC = (response != -1) ? true : false;
                        System.out.println("##### IC=" + IC + "  TYPE = " + NI.getTypeName() + "  response = " + response);
                        if (true){
                                                    ;
                        };
                    } catch (Exception e) {
                    }}}}}
    

    Just to check, if the current connection is WIFI and then request a page, checking first character.