ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • What is Context in Android
    Android 2021. 9. 27. 15:42

    What is 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.

     

    앱 환경과 관련된 글로벌 정보의 인터페이스이며 안드로이드 시스템에서 구현을 제공하는 추상클래스다. Context는 앱의 특정한 리소스, 클래스, 그리고 액티비티, 브로드캐스팅, 받는 인텐트 등에 접근할 수 있게 한다.

     

     

    안드로이드 앱은 컴포넌트들의 묶음(bundle)인데, 이 컴포넌트들은 Manifest에 정의해야 한다. 개발자들은 이메일을 보내는 것, 사진을 공유 하는 것 같이 intent-filter를 사용하여 어떤 컴포넌트를 시스템에 보여줄지 선택한다.

     

    비슷하게, 안드로이드 OS는 와이파이 매니저, 패키지 매니저 같은 컴포넌트를 보여주도록 설계되었다.

    Context는 컴포넌트들간의 다리역할을 하고 각 컴포넌트들이 통신할 수 있도록 한다.

     

    1. own Components

    • 우리는 Activity, Content Provider, BroadCast Receiver 등 과 같은 컴포넌트를 인스턴스화 하기 위해 Context를 사용한다. Context 사용하여 리소스와 파일 시스템에 접근할 수 있다.

     

    2. own Component and a system Component

    • 같은 방식으로 Context를 사용하여 앱에서 사용하는 파일시스템에 접근할 수 있다. Context는 안드로이드 시스템의 진입점같이 행동한다. 잘 사용되는 시스템 컴포넌트들은 와이파이 매니저, 패키지 매니저 등이 있다. 와이파이 매니저에 접근하기 위해선 context.getSystemService(Context.WIFI_SERVICE)처럼 사용한다.

     

    3. own Component and some other app's Component

    • own Component와 other app's Component 사이의 통신은 거의 intent-filter를 사용한다여 접근한다. 예를 들어, 이메일을 보내기 위해 인텐트를 아래와 같이 사용한다.

    Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

     

    Context Types

    • Application Context

    Application Context 는 Singleton Instance(Singelton 에 대해서는 다음을 참조하자 https://jun-android.tistory.com/4)이며 액티비티에서 getApplication()을 통하여 접근한다.

     

    이 Context는 Application Lifecycle과 연결되어 있다. 따라서 Application Context는 현재 Context와 분리된 Lifecycle을 가진 Context가 필요할 때나 Activity의 범위를 넘어서 Context를 전달할 때 사용된다.

    예를 들어, 만약 Application에서 Singleton 객체를 생성하였는데 그 객체에 컨텍스트가 필요하다면, Application Context를 사용하면 된다.

     

    만약 이런 상황에서 Activity Context를 전달한다면 Activity는 Garbage Collector에 의해 수집되지 않는데 Activity Context는 Activity에 대한 참조를 계속 유지하기 때문에 메모리 누수가 발생한다.

     

    • Activity Context

    Activity Context는 Activity에서 사용 하며 이 Context는 Activity의 Lifecycle과 연결되어 있다. Activity 범위 내에서 Context를 전달하거나, Lifecycle이 현재의 Context에 붙은 Context가 필요할 때 Activity Context를 사용한다.

     

    • Application Context와 Activity Context간 계층

    MyApplication이나 MainActivity나 다 같은 Context지만 Scope가 상이하고, Activity의 경우 Application Context를 참조할 수 있다.

     

    Context 선택하기

    Application을 확장한 MyApplication과 여러 Activity클래스들이 있다고 가정하자. 또한 앱에서 데이터베이스를 관장하는 AppDatabase라는 클래스가 Singleton으로 존재한다고 가정하자. AppDatabase는 아마 초기화시 Context를 필요로 할 것이다. 이 때 어떤 Context를 선택해야 할까

    정답은 Application Context이다. Activity Context를 전달한다면, Activity는 Activity의 Lifecycle에 따라 어느시점에 소멸하지만, AppDatabase는 Singleton이므로 해당 Activity를 지속적으로 참조하게 되어 메모리 누수를 발생 시킨다.

     

    하지만 Application Context는 Activity Context가 지원하는 것을 모두 지원하지는 않기 때문에 무조건 적으로 Application Context를 선택하는 것은 옳지 않다.

     

    Lifecycle에 따른 범위를 생각하고 조심해서 Context를 선택 할 필요가 있다.

     

    Context Related Class Structure

    Context는 위와 같이 Proxy패턴으로 구성되어있다. (proxy패턴에 대해서는 다음 글을 참조하자.https://jun-android.tistory.com/3) ContextWrapper 생성자는 실제 Context 참조를 포함해야한다. ContextWrapper 는 attachBaseContext()를 제공하는데 실제 Context를 객체화 한다.

     

    ContextThemeWrapper 클래스는 Theme 과 관련된 인터페이스를 포함한다. Theme은 Manifest에서 android:theme을 사용하여 앱의 element와 Activity의 element에 정의된 Theme을 나타낸다.

    액티비티와 다르게 Service는 Theme가 필요하지 않다. (Serivce는 인터페이스가 없는 background 작업이기 때문에) 따라서 Service는 ContextWrapper를 즉시 상속받는다.

     

    ContextImpl클래스는 Context의 모든 함수들을 실제로 구현하고, 앱에서 호출하는 Context 클래스의 많은 함수들은 이 클래스에서 부터 나온다.

     

     

     

     

     

    Reference:

    https://developer.android.com/reference/android/content/Context

    https://www.freecodecamp.org/news/mastering-android-context-7055c8478a22/

    https://www.programmersought.com/article/26385443246/

    https://shinjekim.github.io/android/2019/11/01/Android-context란/

    https://charlezz.medium.com/안드로이드의-context를-이해하고-메모리-누수를-방지하기-b092a09ef4ef

     

    'Android' 카테고리의 다른 글

    Firebase Realtime DB Rules  (0) 2021.09.29
Designed by Tistory.