Is it safe to keep a strong reference to a Fragment in an AsyncTask?

android, android-asynctask, android-fragments

Solution

It's generally bad methodology to keep references between threads, and an `AsyncTask` is something like a thread.

It's okay, as long as you make sure that you dereference it when you are done using it.

Otherwise, you could get memory leaks.

In this case, it's okay because your `Fragment` is in the context of `AsyncTask`. When the task is done, it will lose that reference.

If this were being done in a `Service`, it would be a very bad idea.

Problem

Since it's not recommended to keep a strong reference to a `Context` in a task (the context may get destroyed while the task is still running, but kept in memory by the task), I was wondering if the same applies to Fragments? Fragments manage their activity reference, and support being retained via `setRetainInstance`. Can I assume that e.g. creating a non-static inner AsyncTask in a Fragment is safe in terms of not risking to leak `$this`?

Original source

Related problems