SingleTon Class처럼 오래사는 인스턴스에게 가끔 context를 넘겨줘야할 상황이 있을수도있다.

그러나 엄청난 주의가 필요하다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
public class SingletonLeakActivity extends AppCompatActivity {
    
    private SingleTonClass stc;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_static_ref_leak);
 
        stc = SingleTonClass.getInstance(this);
    }
}
 
class SingleTonClass {
    private Context mContext;
    private static SingleTonClass instance;
    private SingleTonClass (Context context) {
        mContext = context;
    }
    static synchronized public SingleTonClass getInstance(Context context) {
        if (instance == null)
            instance = new SingleTonClass(context);
        return instance;
    }
 
}
 
cs

 

위의같은경우라면 SignleTonClass 인스턴스가 SigleTonLeakActivtiy의 context를 계속 쥐고있는 상황이생겨

액티비티가 종료되어도 GC가 수거를 못할수도 있게된다.

 

이럴땐 2가지 솔루션이있다.

1.this대신 getApplicatoinContext()를 넘겨주는것이다. Applicatoin이 살아있는동안의 context이고 액티비티들의 라이프사이클과 관련이없기때문이다.

use the Application context. This context will live as long as your application is alive and does not depend on the activities life cycle. 

결론=> 오래살아야하는 인스턴스중 context가 필요하다면 application-context를 넘겨주는게 좋다.  (activity-context를 넘겨주지마라)

 

 

2.하지만 액티비티의 라이프사이클이 필요해서 this / activity-context 넘겼다면 어떻게해야할까?

명시적으로 null처리를 잘해야한다. 위의예제같은경우는 액티비티(컴포넌트)가 onDestroy될때 싱글톤객체에게 context를 null로 만들도록 명시적으로 처리를 해줘야 할 것이다.

 

 

 

 

참고

https://m.blog.naver.com/PostView.nhn?blogId=rjs5730&logNo=221304797233&categoryNo=0&proxyReferer=https%3A%2F%2Fwww.google.com%2F

 

(Android) ActivityContext? ApplicationContext?

안녕하세요. 안드로이드 스튜디오 툴을 해보신 분이면 Context를 한번 쯤 보셨을 거예요. 이렇게 친숙한 ...

blog.naver.com

http://sunphiz.me/wp/archives/tag/applicationcontext

 

applicationcontext – Dog발자

컨텍스트(Context)란? 컨텍스트란 작게는 어플리케이션 자신이 가지고 있는 이미지, 문자열, 레이아웃 같은 리소스 참조를, 크게는 안드로이드 시스템 서비스에 접속하기 위한 관문 역할을 하는 객체다. 이에 대해서는 이미 좋은 글이 있다. 컨텍스트(Context)를 얻는 방법에는 무엇이 있나? 액티비티나 서비스에서 getApplicationContext() 호출 : Application 객체가 Context 형으로 반환된다. 액티비티나 서비스에서 getA

sunphiz.me

https://android-developers.googleblog.com/2009/01/avoiding-memory-leaks.html

 

context에 대한설명과 메모리 leak

 

Avoiding memory leaks

The latest Android and Google Play news and tips for app and game developers.

android-developers.googleblog.com

 

+ Recent posts