java - How can I stop asynctask in android when back button is pressed? -


i running asynctask , taking little time load. in period of time, if pressing button not respond. responds after few seconds. how can kill or pause or override asynctask go back? or there other way similar?

if (maincontent != null) {     maincontent.post(new runnable() {          @override          public void run() {              bitmap bmp = utilities.getbitmapfromview(maincontent);              blurfilter blurfilter = new blurfilter();              bitmap blurredbitmap = blurfilter.fastblur(bmp,1,65);              asynctask = new convertviews(blurredbitmap);              asynctask.execute();          }     }); 

my asynctask:

class convertviews extends asynctask<void,void,void> {         private bitmap bmp;          public convertviews(bitmap bmp){             this.bmp = bmp;         }          @override         protected void doinbackground(void... params) {             try {                 //thread.sleep(200);                 if(mainviewdrawable == null) {                     mainviewdrawable = new bitmapdrawable(getresources(), bmp);                 }              } catch (exception e) {                 e.printstacktrace();             }             return null;         }     } 

my onbackpressed():

public void onbackpressed() {     super.onbackpressed();     asynctask.cancel(true);     finish(); } 

there no way can stop asynch task instantly.every asynchtask has boolean flag property associated if cancel_flag =true mean task has been canceled , there cancel() function can called on aasynchtask object this

logintask.cancel(true);

but cancel() function ,it set cancel boolean(flag ) property of asynch task true , can check property iscancelled() function inside doinbackground , ,like

protected object doinbackground(object... x) {     while (/* condition */) {       // work...       if (iscancelled()) break;     }     return null;  } 

and if true can use break loops(if doing long task) or return go out of doinbackground , calling cancel() on asynchtask skip execution of onpostexecute().

and other option ,if want stop multiple running asynch task in background calling cancel on each 1 can tedious in case can have boolean flag in container class(of asynchtask) , skip working inside asynchtask if flag has been set true ,like

protected object doinbackground(object... x) {     while (/* condition */) {       // work...       if (container_asynch_running_flag) break;     }     return null;  } 

but make sure put check in onpostexecute in case because won't stop execution of onpost.


Comments