0

How can I put a timeout/(raise exception) on my if statement. I want to execute the if statement only if the isNetworkAvailable method responds with in 2000 milliseconds otherwise raise an exception. Otherwise, I just want to know if the 2000 milliseconds have passed and ignore the if statement.

I would appreciate the help, thanks.

This is my if statement

       if (networkUtils.isNetworkAvailable(context)) {
            getToken = new GetToken(context);
            getToken.getToken();
            token = Token.getInstance();
        }
Zaid Qureshi
  • 1,203
  • 1
  • 10
  • 15
Raphael MM
  • 103
  • 8
  • i guess you need a timeout. Look for this http://stackoverflow.com/questions/2799938/httpurlconnection-timeout-question? – Raghunandan Mar 04 '16 at 18:08
  • How can I do this?, What happens is that when there is an internet connection, but the server is down it is very time checking the connection, then I would put a limit on it. – Raphael MM Mar 04 '16 at 18:13
  • if the server does not respond check for exception and handle that properly. – Raghunandan Mar 04 '16 at 18:15

1 Answers1

2

I would recommend using this approach to check if your device is online:

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

Or if you do a Http connection, you can do a timeout.

Zaid Qureshi
  • 1,203
  • 1
  • 10
  • 15
  • my connection check with the internet is very similar to this but what happens is that when there is an internet connection, but the server is down it is very time checking the connection, then I would put a limit on it. – Raphael MM Mar 04 '16 at 18:16
  • If you have a connection, and the request you are making is too long, put a timeout on the request like @Ragunandan pointed out in the comments. It would work because it would only try to make a connection until your time out expires. Which you set by doing `con.setConnectTimeout(2000);` where is your HttpURLConnection – Zaid Qureshi Mar 04 '16 at 18:20
  • If you don't want to it that way, you can make the request in a Thread, and then you can see after 2000 millis if the Thread still hasnt responded close it. – Zaid Qureshi Mar 04 '16 at 18:22
  • [This answer](http://stackoverflow.com/questions/2275443/how-to-timeout-a-thread) shows how you can timeout a Thread – Zaid Qureshi Mar 04 '16 at 18:53