개발/안드로이드

안드로이드에서 'Context'를 정적으로 가져오는 방법

맨날치킨 2022. 11. 29. 09:05
반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Static way to get 'Context' in Android?

안드로이드에서 'Context'를 정적으로 가져오는 방법

 문제 내용 

Is there a way to get the current Context instance inside a static method?

현재 컨텍스트 인스턴스를 정적 메서드 내부로 가져올 수 있는 방법이 있습니까?

 

I'm looking for that way because I hate saving the 'Context' instance each time it changes.

나는 'Context' 인스턴스가 변경될 때마다 저장하는 것을 싫어하기 때문에 그 방법을 찾고 있다.

 

 

 

 높은 점수를 받은 Solution 

Do this:

수행:

 

In the Android Manifest file, declare the following.

Android 매니페스트 파일에서 다음을 선언합니다.

 

<application android:name="com.xyz.MyApplication">

</application>

Then write the class:

그런 다음 클래스를 작성합니다.

 

public class MyApplication extends Application {

    private static Context context;

    public void onCreate() {
        super.onCreate();
        MyApplication.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MyApplication.context;
    }
}

Now everywhere call MyApplication.getAppContext() to get your application context statically.

이제 어디서나 MyApplication.getAppContext()를 호출하여 응용 프로그램 컨텍스트를 정적으로 가져옵니다.

 

 

 

 가장 최근 달린 Solution 

in Kotlin, putting Context/App Context in companion object still produce warning Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)

Kotlin에서 Context/App Context를 동반 객체에 배치하면 여전히 경고가 생성됩니다. Android 컨텍스트 클래스를 정적 필드에 배치하지 마십시오. 이는 메모리 누수입니다(또한 Instant Run을 중단함).

 

or if you use something like this:

또는 다음과 같은 것을 사용할 경우:

 

    companion object {
        lateinit var instance: MyApp
    }

It's simply fooling the lint to not discover the memory leak, the App instance still can produce memory leak, since Application class and its descendant is a Context.

애플리케이션 클래스와 그 하위 클래스가 컨텍스트이기 때문에 메모리 누수를 발견하지 못하도록 단순히 보풀을 속이는 것입니다.

 

Alternatively, you can use functional interface or Functional properties to help you get your app context.

또는 기능 인터페이스 또는 기능 속성을 사용하여 앱 컨텍스트를 가져올 수 있습니다.

 

Simply create an object class:

객체 클래스를 만들기만 하면 됩니다.

 

object CoreHelper {
    lateinit var contextGetter: () -> Context
}

or you could use it more safely using nullable type:

또는 nullable type을 사용하여 보다 안전하게 사용할 수 있습니다.

 

object CoreHelper {
    var contextGetter: (() -> Context)? = null
}

and in your App class add this line:

App 클래스에 다음 행을 추가합니다.

 


class MyApp: Application() {

    override fun onCreate() {
        super.onCreate()
        CoreHelper.contextGetter = {
            this
        }
    }
}

and in your manifest declare the app name to . MyApp

그리고 매니페스트에서 앱 이름을 에 선언합니다. MyApp

 


    <application
            android:name=".MyApp"

When you wanna get the context simply call:

상황을 파악하고 싶을 때는 다음 전화를 걸기만 하면 됩니다.

 

CoreHelper.contextGetter()

// or if you use the nullable version
CoreHelper.contextGetter?.invoke()

Hope it will help.

도움이 되길 바래요.

 

 

 

출처 : https://stackoverflow.com/questions/2002288/static-way-to-get-context-in-android

반응형