ContextActivityProvider

A singleton object that helps to maintain a weak reference to the current Activity. This is useful to avoid memory leaks by preventing strong references to an Activity.

The weak reference ensures that the Activity can be garbage collected when no longer in use, preventing holding onto the Activity object longer than necessary.

Related docu here

Sample

Initialize it in your MainActivity.kt class

class MainActivity : ComponentActivity() {

    /**
     * {@inheritDoc}
     *
     * If your ComponentActivity is annotated with [ContentView], this will
     * call [setContentView] for you.
     */
    @CallSuper
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        ...

        // attach the activity
        ContextActivityProvider.setCurrentActivity(this)

        ...

    }

Use it in composable methods

@Composable
fun SomeComposable() {
    val activity = ContextActivityProvider.getCurrentActivity()
}

Author

N7ghtm4r3 - Tecknobit

Properties

Link copied to clipboard

A WeakReference to the current Activity. This reference is weak to avoid memory leaks.

Functions

Link copied to clipboard

Returns the current Activity if it is still available, otherwise returns null. This method helps retrieve the activity without holding a strong reference to it.

Link copied to clipboard

Sets the current Activity by holding a weak reference to it. This method is called to update the reference when the current Activity changes.