Context

김종주·2023년 7월 24일

About Context

생성된 개체가 현재 어떤일이 일어나는지 알 수 있도록 해줌
-> 어플리케이션에 관해 시스템이 관리하고 있는 정보에 접근할 수 있는 추상 클래스


Context 종류

1. Application Context

  • 어플리케이션에서 현재의 Context 와 분리된 lifecyle 을 가진 Context가 필요할 떄나 액티비티의 범위를 넘어서 Context를 필요로 할 때 사용
  • Activity 에서 라이브러리를 초기화해야 하는 경우 사용

2. Activity Context

  • Activity 생명 주기 범위내에서 Context 가 필요한 객체를 생성할 때나 현재의 Context에 얀걀된 context 가 필요할 때 Activity Context 를 사용
  • Toast 와 Intent 같이 View를 조작하는 경우 Activity Context 사용

Application Context 사용법

  1. Application 을 상속 받는 클래스 생성
  2. Manifest 에 해당 클래스 등록
  3. Application 을 상속 받는 클래스에 아래 코드 삽입
     init{
            instance = this@클래스 이름
        }
        companion object{
            private var instance:GlobalApplication? = null
            fun applicationContext() : Context {
                return instance!!.applicationContext
            }
        }

사용법
Application 을 상속받는 클래스 이름.applicationContext()

profile
Wanna be developer

0개의 댓글