Is it possible to set a reference to AsyncTask to null in onPostExecute ()?

I have an Activity class that has an attribute that refers to an AsyncTask instance, and this AsyncTask also has a reference to that activity.

From AsyncTask onPostExecute()

I want to set a link from Activity to AsyncTask to null
(via a link that has an AsyncTask instance for the Activity). Is this good practice?

I am doing this in the last line of the method code because I am actually telling the garbage collector that it can delete this instance as it no longer references any other object (Activity). Is this correct or am I wrong?

Edit: My answer below is the final solution I used.

Thank!

+3


source to share


2 answers


Why do you need to keep the link to AsyncTask in the first place?

When is the link no longer needed? What happens before the completion of a task that requires you to link to an activity?

I am saying that you can start an asynchronous task without referencing it to make your problem go away. But if for some reason you need a link, then by explaining your specific case more, we can offer a better solution.



EDIT

Your main concern isn't activity leaks, not the other way around. If you really want to clean up all references properly, I would provide an attach / detach method in the async task so that the activities can attach and detach from the async task if needed, and also provide an activity method that negates the async refence task and call this is from your async task if the activity is still on. Don't do it directly. The async task should not directly modify the activity. If possible, even move the async task to a new file, don't make it an inner activity class that screams leaks.

+1


source


After great discussion with @SavvasDalkitsis see his answer and comments , I came up with an answer that suits my requirements. I wanted to set the AsyncTask to null after it completes for two reasons:

  • To see if it's over
  • In order not to recycle it anymore as it is not needed once it has been done once

In fact, it is not necessary to set the AsyncTask to null after it completes (as long as you use the correct approach to bind the new action to the rotation change to avoid memory leaks) to know that it has completed. Instead, we can check its status. Thus, we know whether it is over or not. Then in onCreate()

after calling the method, getLastNonConfigurationChange()

we can also check for that and set it to null if finished so that we don't recycle it anymore:



if (mTask == null || mTask.getStatus().equals(AsyncTask.Status.FINISHED)) {
    mTask = null;
} else {
    mTask.attach(this);
}

      

Hope this helps someone else! :)

+4


source







All Articles