0

I'm trying to find out if there is an active internet connection in my app. I need to know if I can access the network without any errors, sometimes I get "true" response even though I have not internet connection and that is because i'm still connected to the WiFi but there is no internet connectivity.

At the mean time, my internet check function is:

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

This function only check if i'm connected to a certain WiFi or mobile network without actually checking if I can access the network.

So I've added the next function:

public boolean isInternetAvailable() {
    try {
        InetAddress ipAddr = InetAddress.getByName("google.com");
        return !ipAddr.equals("");
    } catch (Exception e) {
        return false;
    }
}

I don't know why, but this function always thinks that my internet connection is okay even though my router is not connected (I have this little yellow triangle on the network bar that says connected but no internet connection).

I tried printing everytime I call this function if the connection is true/false, and I get true at the time that i'm connected, I get false for 5-10 seconds right after I unplug my router, and then i'm getting true again... (without conencting to other WiFi network)

I've tried to test this on the ADB emulator and also on actual device, both of them crashed because I tried to access the network even though I was "offline".

Seeking for help! Thank you very much.

OrrGorenn
  • 347
  • 1
  • 5
  • 15
  • Replace `return activeNetworkInfo != null && activeNetworkInfo.isConnected();` with `return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();` – Aditya Srivastava Aug 14 '17 at 05:16

3 Answers3

0

instead of isConnected() method

   return activeNetworkInfo != null && activeNetworkInfo.isConnected();

try this

return activeNetwork !=null && activeNetwork.isConnectedOrConnecting();

this is the utility class I usually use:

public class NetworkHelper {

    //method that checks for network status
    public static boolean hasNetworkAccess(Context context){

        ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        try {
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork !=null && activeNetwork.isConnectedOrConnecting();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

}

Make sure you have permissions

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

in your activity make a

private boolean networkOk;

then use it to see if your connection is ok ex

    networkOk = NetworkHelper.hasNetworkAccess(this);
    if (networkOk) {
        Intent intent = new Intent(MainActivity.this, Myservice.class);
        intent.setData(Uri.parse(jsonurl));
        startService(intent);
    }
Mohamoud Mohamed
  • 515
  • 7
  • 16
  • unfortunately no. – OrrGorenn Aug 15 '17 at 16:05
  • In your question you didn't ask about using httpUrl connection. You asked about checking networking. You should separate your HttpURLconnection into its own class so it is reusable. I believe I answered your question that you asked. in your answer you even used .isConnectedOrConnecting(); . – Mohamoud Mohamed Aug 16 '17 at 16:31
  • I used isConnectedOrConnected because of your advise, Thank you. – OrrGorenn Aug 17 '17 at 16:21
0

This is what worked for me:

public boolean hasNetworkAccess() {
    if (hasActiveInternetConnection()) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.screens.company").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            System.out.println("NETWORK CHECK");
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            Log.e("NETWORK", "Error checking internet connection.");
        }
    } else {
        Log.d("NETWORK", "No network available!");
    }
    return false;
}

public boolean hasActiveInternetConnection() {
    ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
    try {
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        System.out.println("Debug: [Network] Status: " + (activeNetwork != null && activeNetwork.isConnectedOrConnecting()));
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    } catch (Exception e) {
        System.out.println("Debug: [Network] Status: NOT CONNECTED.");
        e.printStackTrace();
        return false;
    }
}
OrrGorenn
  • 347
  • 1
  • 5
  • 15
0

this will actually check for internet

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;


public class NetStatus {

    private static NetStatus instance = new NetStatus();
    static Context context;
    ConnectivityManager connectivityManager;
    boolean connected = false;

    public static NetStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        boolean online = false;
        try {
            connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            connected = networkInfo != null && networkInfo.isAvailable() &&
                    networkInfo.isConnected();
            if (connected) {
                if (isInternetWorking()) online = true;
            }
        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return online;
    }

    public boolean isInternetWorking() {
        boolean success = false;
        try {
            URL url = new URL("http://www.google.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-Agent", "Android");
            connection.setRequestProperty("Connection", "close");
            connection.setConnectTimeout(1000);
            connection.setReadTimeout(1000);
            connection.connect();
            if (connection.getResponseCode() == 200) success = true;
            connection.disconnect();
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return success;
    }
}
Jaxx0rr
  • 507
  • 4
  • 7