androidkotlinandroid-jetpack-compose

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!


Solution

  • You can get current activity using LocalActivity.current inside any composable, and then use it inside your action

    val activity = LocalActivity.current
    
    fun showInterstitial() {
        if (activity != null) {
            // do some action
        }
    }