Domain/Android

[Android] Context란?

by Donghwan 2020. 9. 8.

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.

애플리케이션 환경에 대한 글로벌 정보에 대한 인터페이스입니다. 이것은 Android 시스템에서 구현하는 추상 클래스입니다. 이를 통해 애플리케이션 별 리소스 및 클래스에 액세스 할 수있을뿐만 아니라 활동 시작, 인텐트 브로드 캐스트 및 수신 등과 같은 애플리케이션 수준 작업에 대한 상향 호출도 가능합니다.

Context | Android Developers

Context란?

  • Application 환경에 대한 전역 정보 인터페이스
  • Android 시스템에서 구현하는 추상 클래스
  • Application Resource와 Class에 접근할 수 있도록 하고, Activity나 Broadcasting, Intent를 받는 등의 기능을 수행할 수 있습니다.
  • Application이나 Object의 현재 상태를 나타냅니다.
  • 새롭게 생성된 객체들이 어떤 상황에 있는지를 이해할 수 있도록 하는 역할입니다.
  • Context는 시스템의 핸들과도 같다. Resource,Database,Preference 등에 대한 접근을 제공합니다.
  • Android에는 Activity라는 것이 있는데, Activity는 Application이 현재 실행중인 환경에 대한 핸들과도 같다. Activity 객체는 Context 객체를 상속 받는다. Activity는 Application의 특정 리소스와 클래스, 그리고 Application 환경에 대한 정보에 접근할 수 있게 됩니다.
  • 잘못된 Context의 사용은 메모리 누수를 일으킬 수 있습니다.

 

Application Context

  • Application Context는 싱글톤이고, activity에서 getApplicationContext()로 접근할 수 있습니다.
  • Application Context는 Application의 생명주기와 연관이 있습니다.
  • Application Context는 Application 실행되어 종료할때까지 동일한 객체를 참조합니다.
  • Application의 수명주기와 관련된 Context가 필요한 경우 Activity Context대신 이 값을 사용하면 됩니다.
  • 싱글톤으로 생성한 Object에 Context를 전달한다고 할때, 만약 Activity의 context를 전달하면 Activity에 Context를 계속해서 참조하고 있으므로 해당 Activity가 GC에서 정리 되지 않아서 메모리 누수가 발생할 수 있습니다.

 

Activity Context

  • Activity Context는 Activity에서 사용 가능합니다.
  • Acitivty Context는 Activity의 생명주기와 연결되어 있습니다.
  • 액티비티의 범위 내에서 Context를 전달할 때 사용합니다.

 

ContentProvider에 있는 getContext()

  • Application의 Context이고, Application Context와 유사하게 사용될 수 있습니다.
  • getContext()를 통해서 사용할 수 있습니다.

 

View.getContext()

  • 현재 뷰가 가지고 있는 Context를 반환합니다.
  • 일반적으로는 Activity에서 View를 띄우기 때문에 Activity의 Context가 됩니다.

 

ContextWrapper.getBaseContext()

  • 다른 컨텍스트로부터 어떤 컨텍스트에 접근해야하는경우에 ContextWrapper를 씁니다.
  • ContextWrapper 내부에서 참조 된 Context는 getBaseContext ()를 통해 액세스됩니다.

 

주의사항

Application Context가 Activity가 하는 모든 것을 지원하는 Context는 아닙니다. 특히, Application Context로는 대부분 GUI 작업은 할 수 없습니다. 만약 Application Context로 UI 작업을 할 경우 IllegalStateException가 발생한다. 예외적으로 Toast는 Application Context를 이용해도 아무 문제가 없이 잘 뜹니다.Toast의 경우 특정 액티비티에 연관된 윈도우에 속하지 않고, 자신만의 윈도우를 생성하기 때문입니다.

728x90
반응형

댓글