java - How to force stoping AsyncTask in Android -



java - How to force stoping AsyncTask in Android -

this question has reply here:

how stop asynctask thread in android? 6 answers

in application have asynctask , i've created list, add together task list. in asynctask downloading information, , works fine, but, when close activity using finish(), forcefulness close because asynctask wasn't closed , when reaches onpostexecute , wants interact ui, crashes caused activity has been destroyed!

this i've tried didn't work:

(int = 0; i<tasks.size(); i++){ tasks.get(i).cancel(true); } finish();

so there way forcefulness stop asynctasks ?

you intereset in asynctask.cancel(true), passing true in parameter, in docs stay:

mayinterruptifrunning true if thread executing task should interrupted; otherwise, in-progress tasks allowed complete.

then within asynctask.doinbackground can have try/catch below - requires have blocking calls throw interruptedexception, otherwise need check iscancelled() time time:

@override protected void doinbackground(void... params) { seek { /// work, } grab (interruptedexception e) { if ( iscancelled() ) { // cancel(true) called, dont touch ui! } } homecoming null; }

also, safe check iscancelled() @ start of onpostexecute().

when reaches onpostexecute , wants interact ui, crashes

thats other problem, if interact within asynctask gui, suggest first: create asynctask static class, pass reference activity or fragment asynctask constructor , store weakreference<myactivity> actref. when need utilize if ( actref.get() != null ) { // utilize it. }. way want leak references activity/fragment or utilize dead ui object.

java android android-asynctask android-studio

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -