@Override protected Void doInBackground(String... params) { answer = "Вернулся " + params[0]; do { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.gc(); try { WeakCallback.get().getResult(answer); } catch (Exception e) { e.printStackTrace(); Log.d(LOG_TAG,"активити пересоздан"); break; } } while (x > 1); return null; } 

Experimenting. I launched Activity, and through it I switch to the second activation, in it I launch AsyncTask . He turns in an endless loop. I keep the link to the WeakReference in WeakReference I WeakReference activation, for the first activation. AsyncTask continues to work until I start to load the picture and by this I awaken the GC . My activity is removed from memory, I catch an exception and if it is not processed by exiting AsyncTask , AsynckTask will never die (well, until the GC priority reaches it, and until that moment it will consume the charge and memory). And the question itself is whether it is right to use the break statement. Return can not be applied, because the dead activit will turn. Will the break AsyncTask ? From the cycle it goes unequivocally.

  • It seems to have to exit the cycle and get on return, probably this is what happens, but it is strange that the application does not crash, because there is nowhere to return null - Turalllb
  • one
    The object returned by the doInBackground method doInBackground passed to the OnPostExecute method. With the correct implementation of the second method, nothing should fall. And note: in doInBackground do not need to contact callbacks, you need to give data for the UI in the OnPostExecute method. - post_zeew

1 answer 1

AsyncTask can be canceled at any time by calling cancel (boolean). After isCancelled (), will return true. Then onCancelled (Object) will be called, instead of onPostExecute (Object). To ensure that the task is canceled as quickly as possible, you should check the return value of isCancelled () in doInBackground (Object []), for example, inside a loop like in your example.

  • I'm a little confused. I pass true in a catch block in cancel. Break operator removed. As I understand it, this means that the thread should stop and exceptions should be thrown like InterruptedException. But this does not happen, I did not wait for the completion of the cycle. Is this the case when cancel (true) could not complete the task itself? If so, then another question is brewing. And how bad is this: in cancel, we pass true and check isCancelled? Why pass false and check isCancelled? because with true chances are even higher. - Turalllb