본문 바로가기

Android/Function

[안드로이드] application context 어디서나 쉽게 가져오기 ― companion object에서 context 사용

728x90
반응형
SMALL

 

 

 

Manifest 추가


 

android:name=".MyApplication"

 

application에 위의 코드를 추가합니다.

 

 <application
    android:name=".MyApplication"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:theme="@style/AppTheme">
    ...
 </application>

 


 

MyApplication class


 

 

Java

  • MyApplication.java

 

public class MyApplication extends Application {

   private static Context context;
   
   public void onCreate() {
      super.onCreate();
      MyApplication.context = getApplicationContext();
   }
   
   public static Context ApplicationContext(){
      return MyApplication.context;
   }
}

 

 

Kotlin

  • MyApplication.kt

 

class MyApplication : Application() {

    init{
        instance = this
    }

    companion object {
       lateinit var instance: MyApplication
        fun ApplicationContext() : Context {
            return instance.applicationContext
        }
    }

}

 

 

이후 밑의 코드로 사용하면 됩니다.

 

MyApplication.ApplicationContext()

 

 

 

 

 

 

728x90
반응형
LIST