Kishan Singh
Kishan Singh

Reputation: 33

Is it necessary for a AsyncTask to be an inner class?

I heard that an AsyncTask is not quite useful in the sense that the activity that is the parent of AsyncTask cannot be destroyed to free the memory in case of changing of the orientation of the mobile phone until the AsyncTask completes its functions(as it is an inner class and it contains references of the parent class). So what if we do not declare the AsyncTask as an inner class and define it as an independent class all together....will this memory leak issue be resolved then?

Upvotes: 0

Views: 43

Answers (1)

Ananta Raha
Ananta Raha

Reputation: 1071

If you want nested class, always create a static nested class that extends AsyncTask. Because instance of a static nested class does not keep reference to its enclosing class. You can use WeakReference to keep reference of enclosing members (if necessary).

So what if we do not declare the AsyncTask as an inner class and define it as an independent class all together....will this memory leak issue be resolved then?

It depends, if you keep strong reference to some Activity/Fragment/UI classes, leak may occur. Using singleton pattern might help cope with memory leaks.

Upvotes: 1

Related Questions