How to get android context for starting an intent? #124
-
I am currently developing a simple application with Decompose and Compose MPP. For this application, I try to implement user authentication with OAuth 2.0 and the device token flow. This requires to open a URL in the browser of the device. For that I have provided a platform specific function. I could figure out the implementation for Where can I get that context from? And is the store provider the right location to call that function if following the structure of the Todo App? Here is the current implementation so far: // commonMain
expect fun openUrlInBrowser(url: String)
// desktopMain
import java.awt.Desktop
import java.net.URI
actual fun openUrlInBrowser(url: String) {
Desktop.getDesktop().browse(URI(url))
}
// jsMain
import kotlinx.browser.window
actual fun openUrlInBrowser(url: String) = window.open(url = url)
// androidMain
import android.content.Intent
import android.net.Uri
actual fun openUrlInBrowser(url: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
`missing-context`.startActivity(intent)
} P.S. Your work is fantastic Arkadii, I could learn a lot about abstraction and structuring projects and I can finally test my components properly. Thank you very much for that. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
If you just need to abstract the Android context, then instead of using the function directly, you can pass an interface into the component. Then implement this interface for each platform, on Android the implementing class should receive the context via constructor. Another way would be to just pass a callback into the component - e.g. |
Beta Was this translation helpful? Give feedback.
If you just need to abstract the Android context, then instead of using the function directly, you can pass an interface into the component. Then implement this interface for each platform, on Android the implementing class should receive the context via constructor.
Another way would be to just pass a callback into the component - e.g.
startOauth: () -> Unit
. Then implement the callback in the activity.