1

When wifi is off and mobile network is off i can detect it , but when on of both is on even is there is no network my validation does not work . now i need to know how i can validate the absence of INTERNET when mobile data and WIFI are on or off.

my code:

NetworkInfo nf;


 ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    nf=cn.getActiveNetworkInfo();

             if(nf != null && nf.isConnected()==true )  
             {

        //    switch to new activity
             }
user3518835
  • 107
  • 1
  • 3
  • 10
  • Well I don't know if your application is sort of a "connection-check-app" or something else, but for a normal application, I suggest that it is not the "job" of the app to test if there is an internet connection. Just time out and handle this case accordingly, because you have to handle it anyhow. – JacksOnF1re Feb 21 '17 at 15:34
  • @ JacksOnF1re what will be in charge of checking existing internet – user3518835 Feb 21 '17 at 16:44

2 Answers2

0

You could try pinging google.com to verify your connection. You have Stack Overflow topic here: How to Ping External IP from Java Android

Community
  • 1
  • 1
0

I am using this and it works fine so far

   public static boolean isOnline() {
        InetAddress inetAddress = null;
        try {
            Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
                @Override
                public InetAddress call() {
                    try {
                        return InetAddress.getByName("google.com");
                    } catch (UnknownHostException e) {
                        return null;
                    }
                }
            });
            inetAddress = future.get(2000, TimeUnit.MILLISECONDS);
            future.cancel(true);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return inetAddress != null && !inetAddress.equals("");
    }

You can put that in a NetworkUtil class and use the static method to check for connectivity.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
  • It is the same issue , when i switch off mobile data or wifi ,it works fine, but code is unable to detect if INTERNET is absent even if wifi or Mobile data is on – user3518835 Feb 21 '17 at 16:20
  • @user3518835 How do you check if the internet is absent besides the code here? – Murat Karagöz Feb 21 '17 at 16:22
  • `if (isOnline) { //go to activity two} else {//Toast .. "Internet is required" } public static boolean isOnline() { .... }` For wifi is now super, but i don't know why for mobile network is trying to switch to activity two when mobile data is on even if no internet i have. – user3518835 Feb 21 '17 at 21:14