7

I use option menu button to go to second activity. When user click on that menu button interstitial Ad show after launching second activity. But I want to show interstitial Ad before launching second activity and when user click on close button of interstitial Ad, second activity should launch.

I'm using the code below to show interstitial Ad.

case R.id.button_id:
   startActivity(new Intent(this, secondactivity.class ));               

                    interstitial = new InterstitialAd(getApplicationContext());
                    interstitial.setAdUnitId(getString(R.string.admob_interstetial_ad));
                    AdRequest adRequest9 = new AdRequest.Builder()
                            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)


                            .build();
                    interstitial.loadAd(adRequest9);
                    interstitial.setAdListener(new AdListener() {
                        public void onAdLoaded() {
                            if (interstitial.isLoaded()) {
                                interstitial.show();
                            }
                        }
                    });


                    return true;
P. Mohanta
  • 130
  • 2
  • 15
user3137451
  • 181
  • 1
  • 2
  • 16

6 Answers6

25

The answer suggested by @user8240773 is correct but there is a more efficient way of handling your problem. Here is my code:

// Has the interstitial loaded successfully?
// If it has loaded, perform these actions
if(mInterstitialAd.isLoaded()) {
    // Step 1: Display the interstitial
    mInterstitialAd.show();
    // Step 2: Attach an AdListener
    mInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdClosed() {
            // Step 2.1: Load another ad
            AdRequest adRequest = new AdRequest.Builder()
                                    .addTestDevice(AdRequest.DEVICE_EMULATOR_ID)
                                    .build();
            mInterstitialAd.loadAd(adRequest);

            // Step 2.2: Start the new activity
            startActivity(new Intent(Activity1.this, Activity2.class));
        }
    });
}
// If it has not loaded due to any reason simply load the next activity
else {
    startActivity(new Intent(Activity1.this, Activity2.class));
}

That way you will also do not have to worry about the ad not loading due to no internet connection or anything else. Everything would be handled by this code in the way you described your problem.

Aayush Goyal
  • 391
  • 1
  • 8
  • 21
4

Maybe something Like this? Use the onAdClosed function to start activity

interstitial.setAdListener(new AdListener() {
 public void onAdLoaded() {
  if (interstitial.isLoaded()) {
      interstitial.show();
   }
 }
     @Override
        public void onAdClosed() {
             startActivity(new Intent(this, secondactivity.class ));    
            // Code to be executed when when the interstitial ad is closed.
            Log.i("Ads", "onAdClosed");
        } 
 });

Read more about this here: https://developers.google.com/admob/android/interstitial

  • 1
    It's working. Thank you very much and I'm very much grateful to you. it worked after editing this `startActivity(new Intent(MainActivity.this, secondactivity.class ));;` – user3137451 Jul 01 '17 at 11:02
  • 1
    But there is a problem. If ads don't show or user has no internet connection then nothing is happening. second activity should launch if ads don't show or user has no internet connection, how to do that? – user3137451 Jul 01 '17 at 11:20
  • Maybe check for an internet connection & if there is none launch the activity, if there is a connection show the add? https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html#DetermineType –  Jul 01 '17 at 11:24
  • 1
    Now It's ok. `@Override public void onAdFailedToLoad(int errorCode) { startActivity(new Intent(MainActivity.this, secondactivity.class )); // Code to be executed when an ad request fails. Log.i("Ads", "onAdFailedToLoad"); }` https://developers.google.com/admob/android/interstitial – user3137451 Jul 01 '17 at 11:52
  • One caveat to @Foodeveloper's otherwise great answer: you should not be showing the interstitial inside onAdLoaded. It's best to do that in response to a button click or some other UI event. That way the ad waits for the user to be ready, not the other way around. – RedBrogdon Jul 01 '17 at 19:40
1

This is for latest SDK.

Load the ad at app start.

To show ads before user go to another activity use this code. You can use counter if you wish to show ads after number of clicks.

Like this

Load ad on app start

   public InterstitialAd mInterstitialAd;
  private int counter = 0;

 AdRequest adRequest = new AdRequest.Builder().build();

    InterstitialAd.load(this, AD_UNIT_ID, adRequest, new InterstitialAdLoadCallback() {
        @Override
        public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
            // The mInterstitialAd reference will be null until
            // an ad is loaded.
            super.onAdLoaded(interstitialAd);
            mInterstitialAd = interstitialAd;

        }

        @Override
        public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
            // Handle the error

            mInterstitialAd = null;
        }
    });

Use this to show

case R.id.button_id:

if (counter == 1) {
                if (mInterstitialAd != null) {
                    mInterstitialAd.show(MainActivity.this);
                    mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
                        @Override
                        public void onAdDismissedFullScreenContent() {
                            // Called when fullscreen content is dismissed.

                            startActivity(new Intent(Activity1.this, Activity2.class));
                        
                       }

                        @Override
                        public void onAdFailedToShowFullScreenContent(AdError adError) {
                            // Called when fullscreen content failed to show.
                            Log.d("TAG", "The ad failed to show.");
                        }

                    });

                } else {
            //load add again as above and visit second activity
         `startActivity(new Intent(Activity1.this, Activity2.class));`
          counter=0;
                   
              
                }

            } else { 

      startActivity(new Intent(Activity1.this, Activity2.class));`
              }
Nehemiah Narzary
  • 336
  • 4
  • 11
0

This code works for me

Intent intent = new Intent(getApplicationContext(),  MainActivity.class); 
startActivity(intent); 
    if (mInterstitialAd.isLoaded()) {
        mInterstitialAd.show();
    }
finish();
0
package com.androidx.sharebd.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.androidx.sharebd.R;
import com.androidx.sharebd.activity.ConnectionManagerActivity;
import com.androidx.sharebd.activity.ContentSharingActivity;
import com.androidx.sharebd.model.TitleSupport;
import com.genonbeta.android.framework.ui.callback.SnackbarSupport;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

public class HomeFragment
extends com.genonbeta.android.framework.app.Fragment
implements TitleSupport,
SnackbarSupport,
com.genonbeta.android.framework.app.FragmentImpl {

  @Nullable@Override
  public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.fragment_home, container, false);

    Button actionReceive = (Button) view.findViewById(R.id.receive);

    actionReceive.setOnClickListener(new View.OnClickListener() {@Override
      public void onClick(View view) {

        /// Interstitial ads Start

        InterstitialAd mInterstitial = new InterstitialAd(getActivity());
        mInterstitial.setAdUnitId(getString(R.string.interstitial_ad_unit));
        mInterstitial.loadAd(new AdRequest.Builder().build());
        mInterstitial.setAdListener(new AdListener() {@Override
          public void onAdLoaded() {
            // TODO Auto-generated method stub
            super.onAdLoaded();
            if (mInterstitial.isLoaded()) {
              mInterstitial.show();
            }
          }

          @Override
          public void onAdClosed() {

            /// Your main code start ( where you want to go )

            startActivity(new Intent(getContext(), ConnectionManagerActivity.class).putExtra(ConnectionManagerActivity.EXTRA_ACTIVITY_SUBTITLE, getString(R.string.text_receive)).putExtra(ConnectionManagerActivity.EXTRA_REQUEST_TYPE, ConnectionManagerActivity.RequestType.MAKE_ACQUAINTANCE.toString()));

            /// Your main code end ( where you want to go )

            Log.i("Ads", "onAdClosed");
          }

          @Override
          public void onAdFailedToLoad(int errorCode) {

            /// Your main code start ( where you want to go )

            startActivity(new Intent(getContext(), ConnectionManagerActivity.class).putExtra(ConnectionManagerActivity.EXTRA_ACTIVITY_SUBTITLE, getString(R.string.text_receive)).putExtra(ConnectionManagerActivity.EXTRA_REQUEST_TYPE, ConnectionManagerActivity.RequestType.MAKE_ACQUAINTANCE.toString()));

            /// Your main code end ( where you want to go )

            Log.i("Ads", "onAdFailedToLoad");
          }

        });

        /// Interstitial ads end

      }
    });

    Button actionSend = (Button) view.findViewById(R.id.send);
    actionSend.setOnClickListener(new View.OnClickListener() {@Override
      public void onClick(View view) {

        /// Interstitial ads Start

        InterstitialAd mInterstitial = new InterstitialAd(getActivity());
        mInterstitial.setAdUnitId(getString(R.string.interstitial_ad_unit));
        mInterstitial.loadAd(new AdRequest.Builder().build());
        mInterstitial.setAdListener(new AdListener() {@Override
          public void onAdLoaded() {
            // TODO Auto-generated method stub
            super.onAdLoaded();
            if (mInterstitial.isLoaded()) {
              mInterstitial.show();
            }
          }

          @Override
          public void onAdClosed() {

            /// Your main code start ( where you want to go )
            startActivity(new Intent(getContext(), ContentSharingActivity.class));

            /// Your main code End ( where you want to go )

            Log.i("Ads", "onAdClosed");
          }

          @Override
          public void onAdFailedToLoad(int errorCode) {
            startActivity(new Intent(getContext(), ContentSharingActivity.class));
            Log.i("Ads", "onAdFailedToLoad");
          }

        });

        /// Interstitial ads End

      }
    });

    return view;
  }

  @Override
  public CharSequence getTitle(Context context) {
    return context.getString(R.string.text_home);
  }

}
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 02 '21 at 17:46
0

add this dependency in your gradle file

implementation 'com.facebook.android:audience-network-sdk:6.12.0'

paste this code in your button listner

 Button theme = findViewById(R.id.button);
        theme.setOnClickListener(v -> {
            if (interstitialAd == null || !interstitialAd.isAdLoaded()) {
                interstitialAd.loadAd();
                startActivity();
                return;
            } else {
                interstitialAd.show();
                InterstitialAdListener interstitialAdListener = new InterstitialAdListener() {
                    @Override
                    public void onInterstitialDisplayed(Ad ad) {

                    }

                    @Override
                    public void onInterstitialDismissed(Ad ad) {
                        startActivity();
                        interstitialAd.loadAd();

                    }

                    @Override
                    public void onError(Ad ad, AdError adError) {
                        Log.e(TAG, "Fb failed :: " + adError.toString());
                    }

                    @Override
                    public void onAdLoaded(Ad ad) {
                        Log.e(TAG, "onAdLoaded: ");
                    }

                    @Override
                    public void onAdClicked(Ad ad) {

                    }

                    @Override
                    public void onLoggingImpression(Ad ad) {

                    }
                };
                interstitialAd.loadAd(interstitialAd.buildLoadAdConfig()
                        .withAdListener(interstitialAdListener)
                        .withCacheFlags(ALL)
                        .build());
            }
            
        });

Then implement startActivity function

private void startThemeActivity() {
            Intent i = new Intent(MainActivity.this, YourActivity.class);
            startActivity(i);         
    }
Abdul Basit
  • 131
  • 7