3. memory leak 회피방법: Inner Class Reference를 주의하라
최악의 상황을 가정해보자
1. static변수가 Inner class의 인스턴스를 저장하고있다.
2. inner class가 outer class의 context 정보를 가지고 있다.
해결방법
1. static변수에 context를 담지말고 일반변수로 담아라
2. inner class 를 -> static inner class로 변경해라. => static inner class는 hidden으로 outer class instance의 reference를 가지지 않는다.
3. WeakReference를 이용해서 context를 받고 필요할때 get으로 꺼내서 지역변수 수준으로 사용해라.
static inner class 생성자 {
private final WeakReference<Activity> activityRef = new WeakReference<>(activtiy);
}
...
public void someMethod() {
Activtiy activity = activityRef.get();
if (activtiy != null) {
....
}
}
참고
https://android.jlelse.eu/9-ways-to-avoid-memory-leaks-in-android-b6d81648e35e
9 ways to avoid memory leaks in Android
I have been an android developer for quite some time now. And I realised that most of that time, I tend to spend on adding new features to…
android.jlelse.eu