android - How to get network status changes with BroadcastReceiver? -
when change wi-fi 3g or vice versa asynctask cause error. want trace , restart loading progress(or stop , proceed asynctask if possible) when happens. looked on google , find broadcastreceiver onreceive called when happens. problem still don't exact moment when happens.
oncreate
registerreceiver(mconnreceiver,new intentfilter(connectivitymanager.connectivity_action));
asynctask point of error(it's called on httpclient line):
@override protected string doinbackground(string... params) { httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost(params[0]); try { if(!iscancelled())//i have set after found error { httpresponse response = httpclient.execute(httppost); jsonresult = inputstreamtostring( response.getentity().getcontent()).tostring(); } }
the broadcastreceiver
private broadcastreceiver mconnreceiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { boolean noconnectivity = intent.getbooleanextra(connectivitymanager.extra_no_connectivity, false); networkinfo changes = intent.getparcelableextra(connectivitymanager.extra_network_info); log.w("current", "" + changes); if(noconnectivity) { task.cancel(true); task2.cancel(true); task3.cancel(true); } log.w("taskiscanceled","" + task.iscancelled()); } };
so have 2 problems tracing event of error , restarting or stopping , proceeding asynctaskes. have 3 asynctaskes take turns.
when switch 3g wi-fi noconnectivity boolean returns have connection. while when go wi-fi 3g first returns dont , shortly after have(so connected).
you can use reflections monitor mobile data changes.
public class networkstatereceiver extends broadcastreceiver { @override public void onreceive(context context, intent intent) { if(intent.getextras() != null){ final connectivitymanager mconnectivitymanager = (connectivitymanager)context.getsystemservice(context.connectivity_service); boolean mobiledataenabled = false; try{ class cmclass = class.forname(mconnectivitymanager.getclass().getname()); method method = cmclass.getdeclaredmethod("getmobiledataenabled"); method.setaccessible(true); // make method callable mobiledataenabled = (boolean)method.invoke(mconnectivitymanager); } catch(exception e){ return; } toast.maketext(backroundservice.this, "data state changed", toast.length_long).show(); } } }
Comments
Post a Comment