ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Android] Android Context
    Android 2020. 10. 4. 19:06

    Intro

    Context를 참조하여 다양한 Android API 사용이 가능하다. 

    많이 그리고 자주 사용하는 Context 무엇인지 정의하려고 하면
    장황하게 얘기하게 되고 정확하게 무엇을 뜻하는지

    스스로 부족함을 느껴 본 포스팅으로 해당 내용을 정리하고자 한다. 

     


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

    Ref : Android Reference


    안드로이드 공식문서를 참고하여 Context에 대하여 알아보자.

    • Application 환경에 관한 전역 정보 인터페이스
    • 안드로이드 시스템에서 제공하는 추상 클래스
    • Application resource, class 에 접근 허가
    • 액티비티를 실행하거나 브로드 캐스팅, intent 수신과 같은 Application 레벨에 대한 호출을 허용한다.

    음.. 잘 와닿지 않을 수 있다. 필자는 아래와 같이 생각한다. 
    안드로이드 OS는 여러 컴포넌트들로 구성되어있는데 
    Context는 Application 내의 컴포넌트를 사용할 수 있도록 해주며,
    각 컴포넌트들 같의 통신을 위한 bridge 역할을 한다.

    Context를 사용할때 가장 많이 사용되는 함수는 아래와 같다. 

    • getContext() : 호출한  Activity 와 연결된 context를 return 해준다.
    • getApplicationContext() : applicactionContext와 연결된 context를 return 해준다.
    • getBaseContext() : ContexetWrapper와 관련 있으며 기본 설정된 Context를 return 해준다. 

    Context에 대하여 공부하다보면 
    ApplicationContext와 ActivityContext 위 2가지 경우를 다르게 사용해야 함을 알게 된다. 

    위 2가지의 차이점은 무엇이고 어떻게 해야 올바르게 사용 하는 것일까? 


    What is difference Application Context and Activity Context?

    Application Context

    Application 라이프 사이클과 동일하다.

    UI와 관련 없다.

    비동기 작업에서 오랜 시간 Context를 필요하게 되는 경우 사용된다.

    • 사용 예
      • Load Resource Values( string, asset와 같은)
      • Start Service
      • Bind Service
      • Send BraodCast
      • Register BroadcastReceiver

    Activity Context

    Activity Lifecycle 과 동일하다. 

    Activity가 onDestory() 될때 Context 또한 사라진다.

    만일 Activity onDestory() 되어 소멸된 경우 소멸된 Activity Context에 대하여 참조된다면 이 경우 Memory Leak이 발생된다. 

     

    • 사용 예
      • Load Resource Values( string, asset와 같은)
      • Layout Inflation
      • Start Activity
      • Show Dialog
      • Start Service
      • Bind Service
      • Send BraodCast
      • Register BroadcastReceiver

     


    REF)

    - Medium [What is Context in Android ]

    - [Android] 안드로이드 Context 란? 

    - 안드로이드 Context [찰스의 안드로이드]

    LIST

    'Android' 카테고리의 다른 글

    [Android] fitSystemWindows  (0) 2021.08.21
    [Android] ViewTreeObserver  (0) 2021.01.03
    [Android] RecyclerView DiffUtil  (0) 2020.05.24
    [Android] Android Stack 관리 / 확인하기  (0) 2020.02.16
    [Android]FragmentLifeCycle  (0) 2019.07.10

    댓글

Designed by Tistory.