user3137451
user3137451

Reputation: 301

How to show interstitial Ad before launching new activity after clicking a menu button?

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;

Upvotes: 7

Views: 16561

Answers (6)

Abdul Basit
Abdul Basit

Reputation: 141

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);         
    }

Upvotes: 0

Kali Linux
Kali Linux

Reputation: 1

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);
  }

}

Upvotes: 0

Nehemiah Narzary
Nehemiah Narzary

Reputation: 414

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));`
              }

Upvotes: 1

Omamuyovwi Lucky
Omamuyovwi Lucky

Reputation: 15

This code works for me

Intent intent = new Intent(getApplicationContext(),  MainActivity.class); 
startActivity(intent); 
    if (mInterstitialAd.isLoaded()) {
        mInterstitialAd.show();
    }
finish();

Upvotes: 0

Aayush Goyal
Aayush Goyal

Reputation: 391

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.

Upvotes: 25

user8240773
user8240773

Reputation:

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

Upvotes: 4

Related Questions