Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How static inner class with a WeakReference to the outer class can Avoid Android Memory Leaks? Need an example

I was studying this article, Avoid Memory Leaks. There are few suggestions to avoid memory leaks, one of them is below:

Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. The solution to this issue is to use a static inner class with a WeakReference to the outer class, as done in ViewRoot and its W inner class for instance

1- Can some one elaborate this by giving an example?

2- How to use to static inner classes with Weak-reference to the inner classes?

3- what are the best practices to use that static class in your application to Avoid Memory leaks.

Great thanks.

like image 670
Yaqub Ahmad Avatar asked Nov 14 '22 12:11

Yaqub Ahmad


1 Answers

In this post, an answer shows a simple example of what you are looking for: How to instantiate interface in fragment?

BUT, one problem is that sometimes a Fragment lives longer than its Activity, for example, if the Activity has a config change (e.g. rotated) then the Activity is destroyed, but the Fragment can be kept alive and then reattached to the new (rotated) Activity. See this post: Android Fragment lifecycle over orientation changes

So you might have a problem with the proposed solution using the WeakReference, because after a rotation you would have a reference to the old Activity (or maybe nothing).

What seems to work for me:

1) When I need a ref to the Activity, call getActivity(). Can do this right in onPostExecute() of a member AsyncTask class, for example.

2) Check the result for null (this can happen: Fragments can live longer than their Activities)

3) Check if activity isFinishing() – you don’t want to do certain UI things in that state.

4) Cast activity to your interface type.

5) Call callback in interface type.

like image 103
Lucy Avatar answered Nov 16 '22 04:11

Lucy