Raw Hasan
Raw Hasan

Reputation: 1396

How to get the current Activity from a Composable function?

I need to call this function to show an interstitial ad from a button click inside a composable function, which expects an activity for the show() method:

fun showInterstitial() {
    if (mInterstitialAd != null) {
        mInterstitialAd?.show(this)
    } else {
        Log.d("MainActivity", "The interstitial ad wasn't ready yet.")
    }
}

How can I get the current activity and replace the this part?

Thanks for your answer!

Upvotes: 8

Views: 5962

Answers (1)

Phil Dukhov
Phil Dukhov

Reputation: 88212

You can get current context using LocalContext. With Compose usually it's gonna be your activity already, but to be sure you can unwrap it like this:

fun showInterstitial(context: Context) {
    val activity = context.findActivity()
}

@Composable
fun View() {
    val context = LocalContext.current
    Button(onClick = {
        val activity = context.findActivity()
    }) {

    }
}

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

If you need to use context inside your view model, or in an other place where your handler function is located, you can pass context to your handler function.

fun showInterstitial(context: Context) {
    val activity = context.findActivity()
}

@Composable
fun View() {
    val context = LocalContext.current
    Button(onClick = {
        showInterstitial(context)
    }) {

    }
}

Upvotes: 18

Related Questions