java - Using class extending asynctask to check internet connection in android activity -
by checking questions on here have managed create below class in order check whether user has active internet connection. want use in android activities check connection before load data internet. ask if suitable way of checking user's internet connection , provide example of how called within activity (how pass context , how obtain true/false
response in android activity.
public class connectionstatus { private context context; public connectionstatus(context context){ this.context=context; } public static boolean isnetworkavailable(context c) { networkinfo netinfo = null; try { connectivitymanager cm = (connectivitymanager) c .getsystemservice(context.connectivity_service); netinfo = cm.getactivenetworkinfo(); } catch (securityexception e) { e.printstacktrace(); } return netinfo != null && netinfo.isconnectedorconnecting(); } public boolean checkconnection() { if (isnetworkavailable(context)) { try { httpurlconnection urlc = (httpurlconnection) (new url("http://clients3.google.com/generate_204") .openconnection()); urlc.setrequestproperty("user-agent", "android"); urlc.setrequestproperty("connection", "close"); urlc.setconnecttimeout(1500); urlc.connect(); return (urlc.getresponsecode() == 204 && urlc.getcontentlength() == 0); } catch (ioexception e) { log.e("tag", "error checking internet connection", e); } } else { log.d("tag", "no network available!"); } return false; } }
i network info outside async task since easier handle how react on given network status.
for async task, make inner class of activity, , check network status before calling execute method of async task.
public class myactivity extends activity{ ... ... private static boolean isnetworkavailable(context c) { networkinfo netinfo = null; try { connectivitymanager cm = (connectivitymanager) c .getsystemservice(context.connectivity_service); netinfo = cm.getactivenetworkinfo(); } catch (securityexception e) { e.printstacktrace(); // bad happen, better return false. return false; } return netinfo != null && netinfo.isconnectedorconnecting(); } //let's assume call data internet private void getdatafromtheinternet(){ if (isnetworkavailable){ connectionstatus cstatus = new connectionstatus(getapplicationcontext()); cstatus.execute(); }else{ //prevent user there not network connection } }
now, remove isnetworkavailable methof asynk task , there go.
additionally use broadcast receiver check everytime connection status changes application can react when it's offline or online following tutorial
Comments
Post a Comment