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();
}
答案 0 :(得分: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.