I'm trying to check connectivity(WIFI or cellular)
to internet
with this method called from OnStart
method:
public static Boolean isInternetConn(Context ctx){
ConnectivityManager connec = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean connected= false;
if((wifi != null && wifi.isConnectedOrConnecting()) || (mobile != null && mobile.isConnectedOrConnecting())){
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL myurl = new URL("http://www.google.com");
URLConnection connection;
connection = myurl.openConnection();
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = -1;
responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
connected = true;
httpConnection.disconnect();
}
else {
httpConnection.disconnect();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return connected;
}
If the net signal is low the method hangs the UI and sometimes the UI becomes to black. I've configured the timeouts to a low value and the problem still happening. It's recommende to do this task in Async Task?
Thanks
Looks like you are trying to ping google to check your network connectivity. This is unnecessary and doing network operations on main thread will disrupt your UI. Use the following method instead:
Remember to add
ACCESS_NETWORK_STATE
andINTERNET
permissions in your manifestEDIT : To check the quality of network, use this library created by facebook. It categorizes connection quality into poor (below 150 kbps), moderate (between 150 and 550 kbps), good (between 550 and 2000 kbps) and excellant (over 2000 kbps).