Below is the piece of Android code which works fine to check if network is connected or not.
public static boolean isNetworkAvailable(Context context)
{
ConnectivityManager mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
return (mConnectivityManager != null && mConnectivityManager.getActiveNetworkInfo().isConnectedOrConnecting()) ? true : false;
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
But having an active network interface doesn't guarantee that a particular networked service is available.
A lot of time happens that we are connected to network but still not reachable to common internet network services, e.g. Google
Common scenario:
- Android device connected to a Wi-Fi, which turns out to be a private
network. So isNetworkAvailable will return that network is connected, but could
not be connected to any other service
- Some times the phone signal shows it is connected to service provider data plan. so network connectivity is true , but still cannot access Google/Yahoo.
One way is to check if "isNetworkAvailable" function returns TRUE, then run following code
HttpGet request = new HttpGet(url));
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 60000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 60000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
request.addHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
{
result = EntityUtils.toString(entity);
}
}
catch (SocketException e)
{
return "Socket Exceptiopn:" + e.toString();
}
catch (Exception e)
{
return "General Execption:" + e.toString();
}
But I think this is not an good way because it may consume lot of time
So is there any alternative efficient (in terms of time taken,speed) way ensure that we are connected to network as well as reachable to most common internet services ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…