I am making an application which is depending on a web service and in order for the app to work I need to check if the phone is able to connect to that web service. I first check if the phone has any internet connection and if it does, I attempt to connect to my web service. If it can connect to the website everything works fine, but if I for some reason can't access it, if I disable the connection on my PC for instance, the app still tries connect to the website causing a force close. Is there any way to let the application try to connect to the web service for like 15 secs and if it fails to connect during this time it will stop.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (httpzRequest() == true) {
Toast t = Toast.makeText(this, "Success!", Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
} else {
Toast t = Toast.makeText(this,
"There's a problem with your internet connection",
Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public boolean httpzRequest() {
if (isNetworkAvailable() == true) {
try {
HttpClient client = new DefaultHttpClient();
URI site = new URI("http://www.google.se/");
HttpGet request = new HttpGet();
request.setURI(site);
HttpResponse response = client.execute(request);
return true;
} catch (IOException e) {
e.printStackTrace();
System.out.println(e);
return false;
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
System.out.println(e);
return false;
}
} else {
return false;
}
}
}