Android Studio中Google AdMob插页广告:点击按钮1-20随机概率触发
Hey there! I’ve built this exact feature for a few projects, so let me walk you through it step by step. The goal is to show an interstitial ad only 1 out of 20 times when a button is clicked—no annoying every-click popups here.
Step 1: Set Up AdMob Dependencies & Manifest
First, get the AdMob SDK added to your module-level build.gradle:
dependencies { implementation 'com.google.android.gms:play-services-ads:22.6.0' // Use the latest version available }
Next, add your AdMob App ID to AndroidManifest.xml inside the <application> tag:
<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-XXXXXXXXXXXXXXXX~YYYYYYYYYY"/> <!-- Replace with your actual App ID -->
Don’t forget the internet permission (add this outside the <application> tag):
<uses-permission android:name="android.permission.INTERNET"/>
Step 2: Initialize & Preload the Interstitial Ad
In your Activity/Fragment, declare the interstitial ad instance and a random number generator. We’ll preload the ad so it’s ready when needed:
import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.interstitial.InterstitialAd import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback import com.google.android.gms.ads.FullScreenContentCallback import com.google.android.gms.ads.AdError import kotlin.random.Random class MainActivity : AppCompatActivity() { private var mInterstitialAd: InterstitialAd? = null private val random = Random(System.currentTimeMillis()) // Seed with time for better randomness override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Load ad when the activity starts loadInterstitialAd() // Hook up your button click listener findViewById<Button>(R.id.your_button_id).setOnClickListener { checkAndTriggerAd() } } private fun loadInterstitialAd() { val adRequest = AdRequest.Builder().build() InterstitialAd.load( this, "ca-app-pub-3940256099942544/1033173712", // Use this test ID for development adRequest, object : InterstitialAdLoadCallback() { override fun onAdLoaded(interstitialAd: InterstitialAd) { mInterstitialAd = interstitialAd // Set up callbacks for ad lifecycle mInterstitialAd?.fullScreenContentCallback = object : FullScreenContentCallback() { override fun onAdDismissedFullScreenContent() { // Reload ad after it's closed so it's ready next time mInterstitialAd = null loadInterstitialAd() } override fun onAdFailedToShowFullScreenContent(error: AdError) { mInterstitialAd = null loadInterstitialAd() } } } override fun onAdFailedToLoad(error: LoadAdError) { mInterstitialAd = null // Optional: Add a retry delay here if you want to try loading again } } ) }
Step 3: Implement the Random Trigger Logic
Add the function that checks the 1/20 probability and either shows the ad or runs your normal button action:
private fun checkAndTriggerAd() { // Generate a random number between 1 and 20 (inclusive) val randomChance = random.nextInt(20) + 1 // Only show ad if we hit the 1/20 chance if (randomChance == 1 && mInterstitialAd != null) { mInterstitialAd?.show(this) } else { // Run your regular button functionality here performButtonAction() } } private fun performButtonAction() { // Replace this with your actual button logic Toast.makeText(this, "Button clicked—no ad this time!", Toast.LENGTH_SHORT).show() } }
Key Best Practices
- Use Test IDs First: Always use Google’s test ad IDs during development to avoid policy strikes. The test interstitial ID used above is safe for testing.
- Preload Ads: Loading ads upfront ensures they’re ready when the random trigger hits—no waiting for ad loads mid-user interaction.
- Reload After Dismissal: Reloading the ad after it closes keeps a fresh ad ready for the next possible trigger.
- Avoid Overloading Users: The 1/20 strike rate is a good balance between monetization and user experience—stick to it to keep users happy.
内容的提问来源于stack exchange,提问作者codelovers

