Forked from paraya3636/KotlinAndroidMainApplication
Last active
November 7, 2020 14:02
-
-
Save vyach-vasiliev/4668906bdce62d99cc5c24c953af6e58 to your computer and use it in GitHub Desktop.
Kotlin Android MainApplication class for global applicationContext.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Author Keisuke Miura | |
// Not object class. AndroidManifest.xml error happen. | |
class MainApplication : Application() { | |
init { | |
instance = this | |
} | |
companion object { | |
private var instance: MainApplication? = null | |
fun applicationContext() : Context { | |
return instance!!.applicationContext | |
} | |
} | |
override fun onCreate() { | |
super.onCreate() | |
// initialize for any | |
// Use ApplicationContext. | |
// example: SharedPreferences etc... | |
val context: Context = MainApplication.applicationContext() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// author Svetlozar Kostadinov (https://gist.github.com/sevar83) | |
class MyApp : Application() { | |
init { INSTANCE = this } | |
companion object { | |
lateinit var INSTANCE: MyApp | |
private set | |
val applicationContext: Context get() { return INSTANCE.applicationContext } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More:
https://blog.mindorks.com/how-to-create-a-singleton-class-in-kotlin