I am using following method to check if device has access to internet.
In this code i am trying to ping/request to www.google.com
try
{
HttpGet request = new HttpGet(new URI(WEB_SIT_TO_PING));
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 500);
HttpConnectionParams.setSoTimeout(httpParameters, 500);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK)
{
result = true;
}
}
catch(Exception e)
{
e.printStackTrace();
result = false;
}
Above code works but, when my activity gets launched it displays one blank black screen for 1-2 seconds and then it displays the main screen of the activity.
I am doing this check in the onCreate of the activity.
Is there another why of doing this check.
UPDATE:
I don’t want to check if Network is connected or not, I want to check if Device has Access to Internet. It may be the case that Device has Network connection but that network connection does not have Internet Access.
Thanks.
You can check if the device is connected to a network easily enough or if you really want to see if the device can connect to Google specifically without the delay wrap that code in an ASync task.
Information on ASync task: http://developer.android.com/reference/android/os/AsyncTask.html
An AsyncTask will allow you to run the code on a thread seperate than the UI thread. Currently it’s freezing for 1 – 2 seconds for that reason.
EDIT I haven’t provided code for checking wireless connectivity as others have already provided other alternatives but I did think it was important to explain why you’re experencing the freeze you are.