AsyncTask is not cancelling the long running operation in android -
i have download huge amount of info server. taking minimum 10 seconds download. here code download using asyntask class. , want cancel downloading operation unconditionally if user clicks on home button while downloading operation going on. problem is... i'am executing cancel() method not cancelling downloading operation. i'am seeing operation running in background in logcat view came out of application. want stop execution of doinbackground() method. please guide/help me.
on click of download button :
dwnldtask = new downloadtask (); dwnldtask.execute(server_url);
and here asynctask class :
class downloadtask extends asynctask<string, void, object>{ private object response = null; @override protected void onpreexecute() { super.onpreexecute(); displaying progress dialog on ui } @override protected object doinbackground(string... params) { try{ dataconnection dc = new dataconnection(); this.response = dc.connecttoserver(params[0]); if(iscancelled()){ homecoming null; } }catch (exception e) { if(iscancelled()){ homecoming null; } e.printstacktrace(); showtoastmsg(e.getmessage()); } homecoming this.response ; } @override protected void onpostexecute(object response) { super.onpostexecute(response); if(response != null ){ downloaded... go next activity } cancel progress dialog here } }
inside onpause()..
@override protected void onpause() { super.onpause(); if(dwnldtask != null && dwnldtask.getstatus() == asynctask.status.running){ dwnldtask.cancel(true); } cancel progress dialog if showing }
here method located in class named dataconnection...
public object connecttoserver(string url) throws exception{ httpget request = new httpget(url); request.addheader("accept","application/json"); httpresponse response = httpclient.execute(request); httpentity httpentity = response.getentity(); inputstream responseinputstream = httpentity.getcontent(); homecoming myutilobject.convertinputstreamtostring(responseinputstream); }
i agree ran - didn't write code of: myutilobject.convertinputstreamtostring
im guessing loop there on inputstream buffer predefined size (maybe bufferedreader?) - in loop should check stop status of async thread - iscancelled() example.
the loop should stop if thread canceled, i.e.:
string line = ""; stringbuilder total = new stringbuilder(); bufferedreader rd = new bufferedreader(new inputstreamreader(is), 1024); while ((line = rd.readline()) != null && !iscancelled()) { total.append(line); }
android android-asynctask cancellation
No comments:
Post a Comment