안드로이드 개발을 하다 보면 Context를 자주 사용하게 된다.
Context에 대해 정확히 알아보지도 않고 당연스레 사용하다가 이번에 찾아보았다.
Context
- Application 환경에 대한 전역 정보를 접근하기 위한 인터페이스
- 추상 클래스이며 실제 구현은 Android 시스템에 의해 제공
- 이를 통해 application 특화 리소스나 클래스 뿐만 아니라 Activity 런칭, 브로드캐스팅, intent 수신 등과 같은 application-level operation을 위한 up-call에 접근이 가능
Context의 중요 핵심
- 애플리케이션의 현재 상태를 나타냄
- Activity와 Application의 정보를 얻기 위해 사용할 수 있음
- Resource, Database, Shared Preference 등에 접근하기 위해 사용할 수 있음
- Activity와 Application 클래스는 Context 클래스를 확장한 클래스
잘못된 Context 사용은 메모리 누수를 쉽게 일으킬 수 있기 때문에 이 개념에 대해 잘 이해해야 한다고 한다.
Application Context
- Singleton 인스턴스 이며, Activity에서 getApplicationContext()를 통해 액세스 할 수 있음
- Application의 life-cycle과 연결됨
- Application Context의 적합한 사용
- 현재 context의 life-cycle과 분리된 context가 필요한 경우 (현재 context가 종료된 이후에도 사용)
- Activity의 scope를 벗어난 context가 필요한 경우
ex) Application 전체에서 사용할 라이브러리를 특정 activity에서 초기화한다면 application context를 사용
ex) Application에 singleton object를 생성하고, 해당 object가 context가 필요하다면 항상 application context를 사용
→ Activity context를 사용한다면 singleton object가 사용될 때마다 Activity를 참조하게 되고 garbage collection이 제대로 이루어지지 않으므로 메모리 누수가 일어나게 된다.
- ContentProvider의 getContext()
앱이 다른 앱과 데이터를 공유하는 것을 도와주는 ContentProvide의 getContext()로 불러올 수 있는 context는
Application Context이다.
Activity Context
- Activity 내에서 유효한 context
- Activity의 life-cycle과 연결됨 → Activity의 onDestroy()와 함께 context도 사라짐
❇️ Activity Context의 적합한 사용
- Activity와 life-cycle이 같은 object를 생성해야 할 때
ex) Activity 내에서 Toast, Dialog 등 UI operation에서 context가 필요하다면 activity context를 사용해야 함
App의 계층구조
- MyApplication은 가장 가까운 Context인 Application Context만 사용할 수 있음
- MainActivity1
- 가장 가까운 Context는 Activity Context
- Activity Context(MainActivity1)와 Application Context를 사용할 수 있음
- MainActivity2
- 가장 가까운 Context는 Activity Context
- Activity Context(MainActivity2)와 Application Context를 사용할 수 있음
대부분의 경우, 가장 가까운 scope에 해당하는 context를 사용하는 것이 좋다.
참조가 해당 컴포넌트의 life-cycle을 넘어가지 않는 이상 메모리 누수 걱정 없이 컴포넌트를 유지할 수 있다.
Context 참조
LoginActivity.this
- Acitivity를 상속받은 자신의 클래스를 참조하지만 Activity 또한 Context class를 상속받으므로 activity context를 제공하는 데 사용될 수 있다.
getApplication()
- Application 객체를 참조하지만 Application 클래스는 Context 클래스를 상속받으므로 application context를 제공하는데 사용될 수 있다.
getApplicationContext()
- application context를 제공한다.
getBaseContext()
- activity context를 제공한다.
Reference
https://amitshekhar.me/blog/context-in-android-application
https://shnoble.tistory.com/57
https://arabiannight.tistory.com/entry/272
https://roomedia.tistory.com/entry/Android-Context란-무엇일까
'Android > Reference' 카테고리의 다른 글
LayoutParam Programmatically (0) | 2022.04.06 |
---|---|
OutLineTextView 글자 외곽선 (0) | 2022.04.03 |
ClipboardManager 클립보드에 복사 후 붙여넣기 (0) | 2022.03.16 |
ViewPager Infinite, Auto Scroll (7) | 2022.03.08 |
권한 체크 Permission Check (0) | 2022.02.23 |