3

According to the post below: http://techtej.blogspot.com.es/2011/03/android-thread-constructspart-4.html. It says that:

In such cases, where your application is not shutdown, but any foreground tasks have been closed or changed, all the background tasks need to know of this and try to exit gracefully

To achieve this, I am calling the cancel function on all the AsyncTask instances. Is this the right way? Also sometimes in image lazy loading, I don't keep track of all the AsyncTasks alive (and fetching images), so how to say the Android OS to cancel them too?

nikis
  • 11,166
  • 2
  • 35
  • 45
user2436032
  • 365
  • 1
  • 4
  • 13
  • 1
    Use [Android Universal Image Loader (UIL)](https://github.com/nostra13/Android-Universal-Image-Loader) or [Picasso](http://square.github.io/picasso/) for lazy loading. Personally I use UIL and it's a great library. – Sufian May 12 '15 at 10:36
  • 1
    There are a lot of questions on how to cancel `AsyncTask` and the answer is that you have to check periodically (inside your `doInBackground()`) if the task was cancelled (if `isCancelled()` is true, cancel/abort what you're doing). – Sufian May 12 '15 at 10:39
  • possible duplicate of [Android - Cancel AsyncTask Forcefully](http://stackoverflow.com/questions/4748964/android-cancel-asynctask-forcefully) – Sufian May 12 '15 at 11:00

2 Answers2

2

You can cancel AsyncTask by checking thread(AsyncTask) object's status.

private Example ex = new Example();

class Example AsyncTask<Object, Void, Void> {
    @Override
    protected Void doInBackground(Object... params) {
        String result = null;
        if(!isCancelled())
            result = getHttpRestManager().send();
        if(!isCancelled())  {
            // some codes
        }
        ...
        return null;
    }
}

public boolean cancel() {
    switch(ex.getStatus())  {
    case RUNNING:
    case PENDING:
        return ex.cancel(true);
    case FINISHED:
        return false;
    }
    return false;
}



After you cancel a thread, it's status always returns RUNNING or FINISHED. If status is not PENDING, you cannot execute thread. So you have to initialize new thread object like ex = new Example() before every .execute().

Taeng
  • 21
  • 1
1

if you don't want to go back in another activity then you can use

System.exit(0);

But if there are other activities in stack,then you have to check // AsyncTask private Example ex = new Example();

in onDestroy method you can check it if it is running

if(ex.getStatus() == AsyncTask.Status.PENDING){

}

if(ex.getStatus() == AsyncTask.Status.RUNNING){

}

if(ex.getStatus() == AsyncTask.Status.FINISHED){

}

Lakhwinder Singh
  • 6,799
  • 4
  • 25
  • 42