AsyncTask aborted during execution does not call any of the post-doInBackground () methods

1

When I cancel my AsyncTask running, it does not update the mAsyncTaskEstaFinalizada flag. Does anyone know what can it be? When I put breakpoints in methods onCancelled() , onCancelled(resultado) and onPostExecute(resultado) , the debugger does not stop at any of them. I expect asynctask to update the flag in a while() loop and the application goes into infinite loop. This can happen? I've noticed in LogCat that no exception is being thrown by the async task.

I'm testing on Android 4.0.3. And before anyone asks why I'm not checking the status of the async task via getStatus() , it's because the states provided by this method do not meet my needs in that case.

class MinhaTask extends
        AsyncTask<Void, Integer, Void> {

    private boolean mAsyncTaskEstaFinalizada = false;

    @Override
    protected Void doInBackground(Void... params) {
        int progresso;
        ...
        publishProgress(progresso);

        while (false == isCancelled()) {
            ...
            publishProgress(progresso);
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... progresso) {
        exibeProgresso(progresso[0]);
    }

    @Override
    protected void onCancelled(Void resultado) { // Chamado após cancel(boolean) quando o API level é 11 ou superior.
        onAsyncTaskCancelada();
    }

    @Override
    protected void onCancelled() { // Chamado após cancel(boolean) quando o API level é 10 ou inferior.
        onAsyncTaskCancelada();
    }

    private void onAsyncTaskCancelada() {
        ...
        mAsyncTaskEstaFinalizada = true;
    }

    @Override
    protected void onPostExecute(Void resultado) {
        ...
        mAsyncTaskEstaFinalizada = true;
    }

    boolean asyncTaskEstaFinalizada() {
        return mAsyncTaskEstaFinalizada;
    }
}

Canceling execution:

MinhaTask minhaTask = new MinhaTask();
minhaTask.execute();

...

if (minhaTask != null && minhaTask.getStatus() == AsyncTask.Status.RUNNING) {
    minhaTask.cancel(false);
    while (false == minhaTask.asyncTaskEstaFinalizada()) {
        // Aguarda a asynctask terminar, porém está entrando em loop infinito!
    }
}
    
asked by anonymous 22.05.2014 / 20:52

1 answer

2
The big problem here is that the onCancelled method, as well as the onPostExecute method, runs on Thread responsible for handling the UI, as it says to documentation .

That way, when you do:

  

while (false == myTask.asyncTaskStatus ())

In Thread of UI, shortly after minhaTask.cancel(false); , you do not let the method finish, preventing onCancelled from running.

To resolve this quickly, remove this

  

while (false == myTask.asyncTaskStatus ())

method, and do, whatever you would like to do, or within the onAsyncTaskCancelada method or within the onPostExecute method.

    
22.05.2014 / 21:53