Search code examples
androidandroid-intentadmobinterstitial

How to load interstitial after click, but before new intent?


My main page has about 10 buttons and each button loads a new intent.

@Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }

        switch(v.getId())
        {
            case R.id.troop_button:
                gotoTroopScreen();
                break;
        }
    }


public void gotoTroopScreen()
{
    Intent intent = new Intent(this, troop.class);
    startActivity(intent);
}

I want the user to click the button, view the interstitial, then view the Troop screen. Right now, it loads the Troop Screen first, then shows the interstitial after the user exits the Troop Screen. Is there a way to make the interstitial show first?


Solution

  • Load your add in onCreate, like this

     interstitial = new InterstitialAd(this);   
     interstitial.setAdUnitId("YOUR_AD_UNIT_IT");
    
     AdRequest adRequest = new AdRequest.Builder()
                    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                    .build();
    
     interstitial.loadAd(adRequest);
    

    And then on button click, call following function:

     public void displayInterstitial() {
            if (interstitial.isLoaded()) {
                interstitial.show();
            }
     }
    

    And when user close ad, move to next activity:

    // Set an AdListener.
     mInterstitialAd.setAdListener(new AdListener() {
                 @Override
                 public void onAdLoaded() {
                     //Here set a flag to know that your 
                 }
    
                 @Override
                 public void onAdClosed() {
                     // Proceed to the next activity.
                     goToNextActivity();
                 }
             });
    

    Note: There is a possibility that, user will click button before, interstitial ad has been loaded.