본문 바로가기
ANDROID/Android 앱 프로그래밍

[Android] Context란?

by 주 녕 2022. 1. 11.
728x90

안드로이드 개발을 하다보면 Context를 자주 사용하게 된다. 하지만 정확한 개념에 대해 알지 못하고 사용하고 있었고,

이번 포스팅을 통해 확실하게 이해하기 위해 Context에 대해 알아보고자 한다.

 

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.
  • Application 환경에 대한 전역 정보를 접근하기 위한 인터페이스이다.
  • 추상 클래스이며 실제 구현은 Android 시스템에 의해 제공된다.
  • 이를 통해 application 특화 리소스나 클래스 뿐만 아니라 Activity 런칭, 브로드캐스팅, intent 수신 등과 같은 application-level operation을 위한 up-call에 접근할 수 있다.

 

Context의 중요한 POINT

 

Understanding Context In Android Application

What is Context? As there are different types of context in Android, we as an Android Developer often get confused about which context to use at which place. So let’s understand what are those, how to use those and when to use which one.

blog.mindorks.com

  • 애플리케이션의 현재 상태를 나타냄
  • 액티비티와 어플리케이션의 정보를 얻기 위해 사용할 수 있음
  • resource, database, shared preference 등에 접근하기 위해 사용할 수 있음
  • Activity와 Application 클래스는 Context 클래스를 확장한 클래스

잘못된 Context 사용은 메모리 누수를 쉽게 일으킬 수 있기 때문에 이 개념에 대해 잘 이해해야 한다고 말하고 있다.

 

2가지 타입의 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를 사용할 수 있음

 

👍Rule of Thumb

대부분의 경우, 가장 가까운 scope에 해당하는 context를 사용하는 것이 좋다.

참조가 해당 컴포넌트의 life-cycle을 넘어가지 않는 이상 메모리 누수 걱정 없이 컴포넌트를 유지할 수 있다.

 


reference >

728x90

댓글