본문 바로가기
Android/Basic

Context

by jaesungLeee 2021. 8. 26.

Android 개발을 하다 보면 Context라는 용어를 정말 자주 접하게 된다. 예를 들어, 화면 전환을 위해 Intent를 사용하려 하면 첫 번째 Parameter로 packageContext를 받고 Toast 메시지를 사용하려 해도 첫 번째 Parameter로 context를 받는다. 또, 이 Context를 사용하려고 하면 상황에 따라 다양하게 표현할 수 있다는 것도 알 수 있다. 이번 포스팅은 Context가 정확히 무엇인지, 어떻게 사용하는 건지, 언제 사용하는 건지에 대해 내가 헷갈려서 정리해보는 포스팅이다.

 

1. Context

아래는 Android 공식 문서에 나와있는 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.

[번역]
어플리케이션 환경에 대한 전역적 정보의 인터페이스. Android 시스템에 의해 제공되어 구현된 추상 클래스이다. 어플리케이션의 특정 리소스 혹은 클래스에 접근이 가능하며 Activity 실행, 브로드캐스팅, Intent 수신과 같은 어플리케이션 레벨에서의 작업을 허용한다.

 

공식 문서의 설명만으로는 이해가 부족해 여러 검색을 하던 중 Context에 대해 정말 자세히 설명해 놓은 외국 블로그가 있어 아래에 링크를 남긴다.

https://blog.mindorks.com/understanding-context-in-android-application-330913e32514

 

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

위 포스팅에서는 컨텍스트의 특징을 다음과 같이 설명하고 있다.

 

1. 어플리케이션의 현재 상태를 나타낸다.

2. Activity와 Application의 정보를 얻기 위해 사용한다.

3. Resource, DB, SharedPreference 등에 접근하기 위해 사용한다.

4. Activity와 Appliacation Class는 Context Class를 확장한다.

 

또한, 잘못된 Context의 사용은 메모리 누수를 일으킨다고 설명하고 있다. 이러한 말 때문이라도 Context의 정확한 사용법을 알아볼 필요가 있을 것 같다. 

 


2. Context의 종류

Context는 크게 2종류로 나뉜다.

 

1. Application Context

Application Context는 어플리케이션 그 자체이며, 현재 어플리케이션의 상태를 표현하고 있다. 또한, Application Context는 어플리케이션 자체의 생명주기에 큰 영향을 받는다. 따라서 Activity 범위보다 큰 Context를 전달할 때 사용하는 Context이다. Application의 생명 주기는 당연히 Activity의 생명 주기 범위보다 크다. 결국, Application 내에서 Context를 사용하기 위해서는 Activity가 아닌 Application Context를 사용하는 것이 메모리의 누수를 방지하는 방법일 것이다.

실제로 많은 라이브러리들의 초기화가 Application단에서 이루어지며 Context를 요구한다. 이때, Context는 Activity가 아니라 Application Context를 사용한다. 

Application Context는 getApplicationContext( )로 접근할 수 있다. 

Application Context는 함부로 사용하면 안 된다..

 

2. Activity Context

Activity Context는 Activity 내에서만 유효한 Context이다. 따라서, A라는 Activity의 Context를 B에서 사용할 수 없다는 의미이다. 또한, Activity Context는 Activity 생명 주기에 영향을 받는다. 따라서 Activity에서 onDestroy( )가 호출되면 Activity Context도 함께 소멸된다.

Activity Context는 getBaseContext( )로 접근할 수 있다.

 

출처 : 안드로이드의 Context를 이해하고, 메모리 누수를 방지하기 / Charlezz

위의 그림은 어플리케이션의 계층 구조를 보이고 있다. 위의 계층 구조에서 Application Context나 Activity Context나 모두 다 같은 Context이지만 Scope가 상이한 것을 볼 수 있다. 지금까지 다룬 내용들로 확인할 수 있듯이, Application Context는 MyApplication, Activity 모두 사용이 가능하다. (단, Activity에서 사용하는 일은 주의할 필요가 있을 것이다.) 또한, MainActivity의 Context는 MainActivity만 사용 가능하고 SubActivity도 마찬가지이다. 

 


3. 어떻게 사용하는가?

StackOverflow에 올라온 질문 중 'Context의 다양한 접근법 중 언제 어떻게 사용하는지와 이 들의 차이점이 무엇인가'라는 질문이 있었다. 아래에 링크를 남긴다.

https://stackoverflow.com/questions/10347184/difference-and-when-to-use-getapplication-getapplicationcontext-getbasecon

 

difference and when to use getApplication(), getApplicationContext(), getBaseContext() and someClass.this

I'm new to android and I'm trying to understand the difference between getApplication(), getApplicationContext(), getBaseContext(), getContext() and someClass.this and especially when to use the th...

stackoverflow.com

 

Activity에서 Toast메시지와 Intent로 Activity 전환을 하는 경우를 비교하고 있다. 아래 코드를 확인해보자.

 

Toast.makeText(this@LoginActivity, "Login Successful", Toast.LENGTH_SHORT).show()
Toast.makeText(getApplication(), "Login Successful", Toast.LENGTH_SHORT).show()
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show()
Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show()

 

val intent = Intent(this@MainActivity, LoginActivity::class.java)
val intent = Intent(getApplication(), LoginActivity::class.java)
val intent = Intent(getApplicationContext(), LoginActivity::class.java)
val intent = Intent(getBaseContext(), LoginActivity::class.java)

 

코드에서 Context로 사용되는 표현들은 this, getApplication( ), getApplicationContext( ), getBaseContext( )이다. 결론부터 말하자면 thisgetBaseContext( )는 Activity Context이고 나머지는 Application Context이다. 결과적으로, Toast메시지와 Intent와 같이 View를 조작하는 경우에는 Activity Context를 사용하고 그 외의 경우에는 Application Context를 사용해야 한다. 따라서, 위의 예시 코드에서 두 번째와 세 번째 코드는 잘못된 코드라고 생각한다.

 

Context를 사용하는 구체적인 예시가 있다. 아래의 코드를 통해 설명한다.

 

val myString = applicationContext.resources.getString(R.string.myString)

var preference = applicationContext.getSharedPreferences("MY_PREFERENCES", Context.MODE_PRIVATE)

val textView = TextView(this)

 

첫 번째 코드는 Application Context를 이용하여 어플리케이션 Resource에 접근해 String을 가져오는 경우이다.

두 번째 코드도 Application Context를 이용하여 SharePreferences에 접근하는 경우이다.

마지막 코드는 Activity Context를 이용해 TextView를 초기화하는 경우이다.

 


4. 언제 사용하는가?

지금까지 Application Context와 Activity Context가 무엇인지, 어떻게 사용하는지에 대해 알아보았다. 또, Application Context는 특정 경우를 제외하고는 함부로 사용하면 안 될 것 같다는 느낌도 받게 되었다. 정확히 언제 사용하는지에 대해 알아보자.

위에서 간단히 언급했듯이 Toast 메시지, Dialog 등과 같이 UI의 조작이 필요한 경우에는 Activity Context를 사용해야 한다. 만약 이때, 불필요하게 Application Context를 사용한다면 메모리 누수가 발생할 것이다. 즉, 충분히 Activity에서 바로 사용 가능한 Context이면 Activity Context를 사용하는 것이 맞는 방법일 것이다.

Application Context는 사용할 객체가 Application에서 초기화되거나 Singleton인 경우에 사용한다. 여기서 Singleton 객체는 인스턴스 자체가 어플리케이션에서 딱 하나 생성되도록 하고 어디서든 접근 가능한 객체를 말한다.

 


5. 결론

Context에 대해 정리해보았다. Application Context를 함부로 사용하면 메모리 누수가 일어날 수 있다는 것은 알고 있었지만 지금까지 개발을 하면서 Context를 사용할 때는 상황 고려는 하지도 않고 무작정 사용했던 것 같다. 기초가 튼튼해야 할 것 같다.

 

(여러 블로그와 StackOverflow의 글을 읽어보고 제가 이해한 대로 쓴 포스트입니다. 잘못된 표현이나 개념들이 있다면 댓글로 첨언 부탁드립니다.)

 

 

References

https://roomedia.tistory.com/entry/Android-Context%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%BC%EA%B9%8C

 

Android Context란 무엇일까?

안드로이드 프로그래밍을 하며 제일 흔하게 인자로 사용되는 타입이 Context인 것 같습니다. Context를 잘못 사용하면 앱이 비정상 종료되거나 메모리 누수가 발생하기도 하죠. 그렇다면 Context는 정

roomedia.tistory.com

https://shinjekim.github.io/android/2019/11/01/Android-context%EB%9E%80/

 

[Android] 안드로이드 Context란? · Challengist

[Android] 안드로이드 Context란? 01 Nov 2019 | Android 이 글은 MindOrks의 Understanding Context In Android Application을 (나름대로) 번역한 글입니다. 잘못된 부분이 있으면 언제든지 알려주세요. 안드로이드에서 컨

shinjekim.github.io

https://arabiannight.tistory.com/284

 

안드로이드/Android Context 란?

안드로이드/Android Context 란? <안드로이드 Context 는 수수께기가 많은 클래스입니다> Android Context Story  저에게 안드로이드 Context 는 참 어려운 녀석입니다. 안드로이드 어플리케이션을 개발하며서.

arabiannight.tistory.com

https://gdbagooni.tistory.com/14

 

[Android Studio] Context란? Context의 정의, 종류와 사용 방법

안드로이드 개발을 하다 보면 자주 사용되는 context란 것이 있습니다. 지금까지 정확한 기능을 모르고 사용했지만 이번 기회에 context의 기능과 역할을 알아보겠습니다. 개념에 대해 알아볼 때는

gdbagooni.tistory.com

 

'Android > Basic' 카테고리의 다른 글

Android Component : 2. Service 개요  (0) 2021.11.08
Permissions  (0) 2021.09.04
Android Component : 1. Activity와 생명 주기  (0) 2021.08.24