How to get activity in compose

While the previous answer (which is ContextWrapper-aware) is indeed the correct one,
I’d like to provide a more idiomatic implementation to copy-paste.

fun Context.getActivity(): AppCompatActivity? = when (this) {
    is AppCompatActivity -> this
    is ContextWrapper -> baseContext.getActivity()
    else -> null
}

As ContextWrappers can’t possibly wrap each other significant number of times, recursion is fine here.

Leave a Comment