Android how to stop AsyncTask -
this question has answer here:
- android - cancel asynctask forcefully 6 answers
i working on asynctask
. trying stop asynctask
.
authenticationarrows mtask = new authenticationarrows(); mtask.execute();
i trying stop by
mtask.cancel(true);
but not stop.
my asynctask
code below.
class authenticationarrows extends asynctask<void, void, boolean> { @override protected void oncancelled() { super.oncancelled(); cancel(true); // ask if user wants try again } @override protected boolean doinbackground(void... params) { return null; } protected void onpostexecute() { } @override protected void onpreexecute() { if (!iscancelled()){ handler.post(new runnable() { @override public void run() { centerimage.setvisibility(view.invisible); tiltmotion1.setvisibility(view.visible); progressstatus = 60; mprogressbar.setprogress(progressstatus); vibrator v= (vibrator) getsystemservice(context.vibrator_service); v.vibrate(200); progressstatus += 10; mprogressbar.setprogress(progressstatus); } }); } if (!iscancelled()){ handler.postdelayed(new runnable() { @override public void run() { motion1.setvisibility(view.invisible); motion2.setvisibility(view.visible); vibrator v= (vibrator) getsystemservice(context.vibrator_service); v.vibrate(200); progressstatus += 10; mprogressbar.setprogress(progressstatus); starthandler(); } }, 1000); } } public void starthandler(){ if (!iscancelled()){ handler.postdelayed(new runnable() { @override public void run() { motion2.setvisibility(view.invisible); motion3.setvisibility(view.visible); vibrator v= (vibrator) getsystemservice(context.vibrator_service); v.vibrate(200); progressstatus += 10; mprogressbar.setprogress(progressstatus); } }, 1000); } } }
how can stop or cancel when navigate other activity or when app goes background?
the cancel(...)
method prevents call of onpostexecute() after doinbackground() finishes. instead oncancelled() invoked. furthermore iscancelled()
return true call cancel(). should check in doinbackground(), able let finish asap.
so, useless code:
@override protected void oncancelled() { super.oncancelled(); cancel(true); }
cancel(true) has no effect here, because oncancelled() invoked if call cancel() before. can leave empty or deal situation here if asynctask canceled.
here should check iscancelled():
@override protected boolean doinbackground(void... params) { return null; }
because nothing here asynctask useless, because no background threading @ all.
this wrong place call iscancelled():
@override protected void onpreexecute() { if (!iscancelled()){ ... }
again, iscancelled() should checked in doinbackground() let finish asap.
to cancel task switching activities or activity goes background, use onpause()
callback , call mtask.cancel(true);
read docs asynctask again basics.
Comments
Post a Comment