https://kotlinlang.org logo
Title
r

Rafiul Islam

11/07/2021, 2:12 PM
I had seen Jim once say about this
val activity = LocalContext.current as Activity
But I never found the answer.
a

Adam Powell

11/07/2021, 3:56 PM
If you're writing platform dependent code that needs an activity you can't exactly just not use it, and laundering platform specific usage through other abstractions is sometimes useful, sometimes YAGNI.
But it's worth noting that often the
LocalContext
is not an
Activity
, but instead it can be a chain of `ContextWrapper`s where the
.baseContext
leads to an
Activity
eventually
this can often happen if a
ContextThemeWrapper
has been used to change the theme mid-view hierarchy. If you use the
android:theme
attribute in layout xml, one of these is created for you. If a
ComposeView
is placed as a child of such a subtree,
LocalContext
will be one of these wrappers.
That said, depending on what you're doing with the activity you might find it more useful to pass a
() -> Unit
callback or similar to your composable and provide a lambda that makes the actual activity call. This can often aid in testability
👍🏻 1
👍 1
https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:activity[…]n/java/androidx/activity/compose/ActivityComposeUtils.kt;l=22 shows the unwrapping ContextWrappers approach and is used by the activity result API in the androidx.activity library
r

Rafiul Islam

11/07/2021, 4:44 PM
Actually, I have been using a onFinish: () -> Unit callback for my code to finish the activity from composable functions for a while.
👍 1
I am a little bit confused just if you make it clear. So LocalContext will eventually get the activity, it might go through multiple loops. But it will return the activity right? Or is there any possibility it won't return the activity?
a

Adam Powell

11/07/2021, 4:57 PM
If there is no activity to return then it won't return one. It's entirely possible to create a
ContextThemeWrapper
around a
Service
context,
getSystemService
to get the
WindowManager
, and add a
ComposeView
to it as a top-level window with the right lifecycle dependencies configured. At that point you have no activity, but you have a perfectly functional compose ui
👍 1
Android Auto projected mode operates more or less this way as well
r

Rafiul Islam

11/07/2021, 5:07 PM
Yep, I got it. Thanks @Adam.
👍 1