[Android] Context란? getContext(), getApplicationContext(), getBaseContext()의 차이점



Context란?

먼저 공식문서에 의하면 다음과 같다.

Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.


애플리케이션 환경에 대한 인터페이스 이자, 추상 클래스 이다. 즉, 애플리케이션의 현재 상태 를 뜻한다. Context를 통해 애플리케이션에 접근할 수 있고, 애플리케이션 수준 작업을 호출할 수 있다.

안드로이드 개발 중 Context에 자주 접근하게 되므로 Context를 잘못 사용하면 메모리 누수 가 발생할 수 있다. 따라서 Context에 관한 내용을 확실히 정리하고 넘어가려 한다.

Context에는 두 가지 유형이 존재한다. Application ContextActivity Context 이다. Application Context는 Application 전용 인스턴스이고, Activity Context는 Activity 전용 인스턴스이다.


Application Context

싱글톤 패턴으로, getApplicationContext()를 통해 액티비티 내에서 접근 가능한 인스턴스이다. 애플리케이션 라이프사이클 과 연결되어 있으며 현재 Context와 분리된 Context가 필요한 경우 사용한다.

EX) MVVM 패턴 적용 시 Activity의 Context가 아닌 Application Context 접근을 통해 Database에 접근하려는 경우


Activity Context

액티비티 라이프사이클 과 연결되어 있으며 액티비티 수준의 Context가 필요한 경우 사용한다.

EX) Toast 메시지를 띄우는 것과 같은 UI 작업 시


context_image

액티비티는 자신의 Context 와 애플리케이션 Context를 모두 가지고 있으며 getContext() 혹은 this를 사용할 경우 액티비티 Context 가 return된다.


정리

  • View.getContext()
    • 현재 실행되고 있는 View의 Context를 return
    • 보통은 현재 활성화된 Activity의 Context가 됨
  • Activity.getApplicationContext()
    • Applcation Lifecycle에 해당하는 Context를 return
  • ContextWrapper.getBaseContext()
    • 자신의 Context가 아닌 다른 Context에 접근할 때 사용



:bookmark: REFERENCE
Android Developers | Context
안드로이드에서 getContext(), getApplicationContext(), getBaseContext(), this의 차이가 뭔가요?
[Android] 안드로이드 Context란?
Understanding Context In Android Application