New answer:
Accompanist library uses internally the findActivity method to get the activity. I've tweaked it to follow a similar naming and behavior as other Kotlin methods:
fun Context.getActivityOrNull(): Activity? {
var context = this
while (context is ContextWrapper) {
if (context is Activity) return context
context = context.baseContext
}
return null
}
Old answer that may crash:
You can get the activity from your composables casting the context (I haven't found a single case where the context wasn't the activity). However, as Jim mentioned, is not a good practice to do so.
val activity = LocalContext.current as Activity
Personally, I use it when I'm just playing around some code that requires the activity (permissions is a good example) but once I've got it working, I simply move it to the activity and use parameters/callback.
Edit: As mentioned in the comments, using this in production code can be dangerous, as it can crash because current is a context wrapper, my suggestion is mostly for testing code.
tailrec
2. it might be written as aval
extension: private tailrec fun Context.getActivity(): AppCompatActivity? = when (this) { is AppCompatActivity -> this is ContextWrapper -> baseContext.getActivity() else -> null } val Context.activity: AppCompatActivity? get() = getActivity() – Laird