Search code examples
javaandroidandroid-studioadmobads

Interstitial ads (admob) button to open second activity (page 2)


I have some doubts about whether it is correct how the Admob interstitial code is implemented in my application.

The objective is to show interstitial ad when pressing the button that is in MainActivity to open Activity 2.

Example MainActivity (button)

public void page1(View view)  
{

    Intent i = new Intent (this, activity2.class);
    startActivity(i);

 
    if (mInterstitialAd != null ) {
        mInterstitialAd.show(this);
    }

}

The code works fine, but would it be correct?.


Another question related to the show(...): I have seen these 2 versions

mInterstitialAd.show(this);
or
mInterstitialAd.show(MainActivity.this);

which would be the best?

Sorry I just started and I'm a bit lost.

Thanks for the answers.


Solution

  • As per Interstitial Ad implementation guide,

    You should not show interstitial ads after the activity has loaded. Interstitial ad should be shown at a natural transition point. You should not show ads after page/activity is loaded. You must first show the ad and start the activity when the ad is dismissed/failed_to_show.

    Disallowed process

    enter image description here

    Allowed process

    enter image description here

    • Images from the link to make the process easier to understand

    Here's an example:

    public void openNewActivity()  
    {
        // Create the Intent
        Intent i = new Intent (this, activity2.class);
    
        // Check mInterstitialAd 
        if (mInterstitialAd != null ) {
            // Create callback 
            mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
                @Override
                public void onAdDismissedFullScreenContent() {
                    // Don't forget to make mIntersttialAd null
                    mInterstitialAd = null;
    
                    // times to start the activity
                    startActivity(i);
                }
    
                @Override
                public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
                    // Don't forget to make mIntersttialAd null
                    mInterstitialAd = null;
    
                    // times to start the activity
                    startActivity(i);
                }
    
            });
            //  Now show the ad
            mInterstitialAd.show(MainActivity.this);
        } else {
            // we don't have an interstitial ad to show
            // start the activity
            startActivity(i);
        }
    }
    

    Hope this will help.

    Please note that AdMob has not forwared any code in any of its documents as a sample implementation guide which would be perfect according to its policy. But the code I've provided above, seems be a bit like the guidance given in the above link.