Useful to develop a standalone library
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.kibotu:ApplicationProvider:(lastest version)'
}
//from anywhere
val application = ApplicationProvider.application
//from anywhere
val currentActivity : Activity? = ActivityProvider.currentActivity()
Or safety from a kotlin coroutine context :
launch {
val currentActivity = ActivityProvider.activity() //cannot be null
Log.d(TAG, "activity : $currentActivity")
}
launch {
ActivityProvider.listenCurrentActivity().collect {
Log.d(TAG, "activity : $currentActivity")
}
}
If you need to execute a code automatically when the application starts, without adding it into your application's class code
Create a class that extends Provider
class StethoProvider : Provider() {
override fun provide() {
val application = ApplicationProvider.application //if you need the application context
Stetho.initializeWithDefaults(application)
}
}
Add it into your manifest
<provider
android:name=".StethoProvider"
android:authorities="${applicationId}.StethoInitializer" />
You do not need to override the Application now
class MyApplication : Application() {
override fun onCreate(){
Stetho.initializeWithDefaults(application)
}
}
Note that you can include it directly on your library's aar
class StethoInitializer : ProviderInitializer() {
override fun initialize(): (Application) -> Unit = {
Stetho.initializeWithDefaults(application)
}
}
<provider
android:name=".timber.TimberInitializer"
android:authorities="${applicationId}.StethoInitializer" />
Another way using Initializer
val InitializeStetho by lazy {
ApplicationProvider.listen { application ->
Stetho.initializeWithDefaults(application)
}
}
class MainActivity : AppCompatActivity() {
init {
InitializeStetho
}
override fun onCreate(savedInstanceState: Bundle?) {
...
}
}
Let me know what you think: jan.rabe@kibotu.net
Contributions welcome!