Skip to content
This repository has been archived by the owner on Feb 8, 2022. It is now read-only.

Retrieve the android application and the current activity from anywhere

License

Notifications You must be signed in to change notification settings

florent37/ApplicationProvider

Repository files navigation

ApplicationProvider

Retrieve the android application from anywhere

Useful to develop a standalone library

//from anywhere
val application = ApplicationProvider.application

Retrieve the current activity from anywhere

//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")
}

Listen for current activity

launch {
    ActivityProvider.listenCurrentActivity().collect {
        Log.d(TAG, "activity : $currentActivity")
    }
}

Providers

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" />

Download

Buy Me a Coffee at ko-fi.com

Download

dependencies {
    implementation 'com.github.florent37:applicationprovider:(lastest version)'
}

Initializers

You do not need to override the Application now

Before

class MyApplication : Application() {
    override fun onCreate(){
        Stetho.initializeWithDefaults(application)
    }
}

After

Using a provider (for libraries)

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" />

Using an initializer

Another way using Initializer

val InitializeStetho by lazy {
    ApplicationProvider.listen { application ->
        Stetho.initializeWithDefaults(application)
    }
}

class MainActivity : AppCompatActivity() {

    init {
        InitializeStetho
    }

    override fun onCreate(savedInstanceState: Bundle?) {
    ...
    }
}

About

Retrieve the android application and the current activity from anywhere

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published