안드로이드에서 Context란 무엇일까

안드로이드를 자습하고 있는 중이다. 메서드에 매개변수로 context를 넘겨야 하는 경우가 잦은데, context가 무엇인지 그리고 어떻게 refer할 수 있는지 알아보았다.

Android Developers: “[Context is the] Interface to global information about an application environment.”

지금은 “현재 사용되고 있는 어플리케이션(또는 액티비티)에 대한 포괄적인 정보를 지니고 있는 객체”로 이해하고 넘어가려고 한다. 참고하고 있는 학습서에서 getBaseContext(), getApplicationContext(), ActivityName.this 이 세가지의 방법을 통해 context를 참조하는데, 찾아보니 차이가 있었다.

1. http://stackoverflow.com/questions/10347184/difference-and-when-to-use-getapplication-getapplicationcontext-getbasecon [“wonderfully clarifying answer”]

안드로이드 프레임워크에서 Context는 Application Context와 Activity Context로 구분지을 수 있는데, Application Context는 application life-cycle에 접목되는 개념이고 Activity Context는 activity life-cycle에 접목되는 개념이다. 즉 전자는 하나의 애플리케이션이 실행되어 종료될 때까지 동일한 객체인 반면, 후자는 액티비티가 onDestroy() 된 경우 사라질 수 있는 객체이다. 이를 참고하여 목적에 맞도록 알맞은 종류의 context를 참조해야 한다.

Application Context를 참조하기 위해 getApplicationContext(), getApplication()을 사용할 수 있고, Activity Context를 참조하기 위해서는 getBaseContext()나 ActivityName.this를 사용할 수 있다 (필자가 웹 프로그래밍 입문 교육을 받을 땐 거의 대부분의 경우 this를 사용하였다… 왜 그랬을까?). 참조한 포스트 해답의 저자는 View를 “manipulate”할 경우에는 activity context 를 참조하고 기타 경우 application context를 참조하면 무난하다고 하다.

2. https://possiblemobile.com/2013/06/context/

Application Context 대신 Activity Context를 왜 구별해서 선택적으로 사용해야 하는지, 특히 전자를 후자 대신 사용해서는 안되는 케이스에 대해 설명해주었다.

There are a number of functions the application context is not properly suited to handle; all of them related to working with the UI [e.g. show a dialog, start an activity, layout inflation]. Activity is the only Context on which the themes defined in your manifest are actually attached.  Any other instance will use the system default theme to inflate your views, leading to a display output you probably didn’t expect. In most cases, use the Context directly available to you from the enclosing component you’re working within. You can safely hold a reference to it as long as that reference does not extend beyond the lifecycle of that component.

3. http://stackoverflow.com/questions/10641144/difference-between-getcontext-getapplicationcontext-getbasecontext-and/10641257#10641257

  • Activity.getApplicationContext(): 현재 활성화된 액티비티만이 아닌 어플리케이션 전체에 대한 [incl. all of its activities?] context가 필요한 경우에 사용
  • View.getContext(): 현재 활성화된 activity에 대한 context 참조 시 사용. this를 사용하는 것과 같은 맥락.
  • ContextWrapper.getBaseContext(): 어느 context에서 다른 context를 참조해야 하는 경우 ContextWrapper 객체를 사용하는데, 그 ContextWrapper 안에 있는 context를 참조하는 경우에 사용.

안드로이드에서 Context란 무엇일까”에 대한 답글 1개

댓글 남기기