android - Check connectivity to internet, hangs UI with bad signal -
i'm trying check connectivity(wifi or cellular) internetwith method called 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 net signal low method hangs ui , ui becomes black. i've configured timeouts low value , problem still happening. it's recommende task in async task?
thanks
looks trying ping google check network connectivity. unnecessary , doing network operations on main thread disrupt ui. use following method instead:
public boolean isconnectingtointernet(context context) { connectivitymanager connectivity = (connectivitymanager) context.getsystemservice(context.connectivity_service); if (connectivity != null) { networkinfo[] info = connectivity.getallnetworkinfo(); if (info != null) (int = 0; < info.length; i++) if (info[i].getstate() == networkinfo.state.connected) { return true; } } return false; } remember add access_network_state , internet permissions in manifest
edit : check quality of network, use this library created facebook. categorizes connection quality poor (below 150 kbps), moderate (between 150 , 550 kbps), (between 550 , 2000 kbps) , excellant (over 2000 kbps).
Comments
Post a Comment