Adding AdMob Ads in Android Studio is simple and only takes a few clicks. Here’s how:
1. First, open Android Studio and create a new project. Give your project a name and select “Add No Activity”.
2. Next, open the project’s build.gradle file and add the following line under dependencies: compile ‘com.google.android.gms:play-services-ads:10.0.1’
3. Now open the MainActivity.java file and import the following packages: import com.google.android.gms.ads.*;
import android.os.*;
4. In the onCreate() method, add the following code to initialize the MobileAds SDK: MobileAds.initialize(this, “ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN”); //Replace XXXXX with your App ID and NNNNN with your Ad Unit ID
5. Now, create an instance of the AdView class and add it to the layout:
AdView mAdView = (AdView) findViewById(R.id.
6.
7.
8.
Creating a new Activity for displayingInterstitial Ads:
1. Right click on your package name in the project explorer -> New -> Activity -> Empty Activity
Name it as SecondActivity
2.. Open Your SecondActivity java File and write down this code import com .google .android .gms .ads .AdListener ; import com .google .android .gms .ads .AdRequest ; import com .google .android .gms .ads .InterstitialAd ; public class SecondActivity extends AppCompatActivity { private InterstitialAd mInterstitialAd ; @Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ); setContentView ( R . layout . activity_second ); mInterstitialAd = new InterstitialAd ( this ); mInterstitialAd . setAdUnitId ( “ca – app – pub – XXXXXXXXXXXX / NNN” ); mInterstitialAd . setAdListener ( new AdListener () { @Override public void onError ( Ad ad , AdError error ) { // Code to be executed when an ad request fails } @Override public void onLoaded ( Ad ad ) { // Code to be executed when an ad finishes loading } @Override public void onOpened ( Ad ad ) { // Code to be executed when an interstitial ad opens an overlay that covers the screen } @Override public void onLeftApplication ( Ad ad ) { // Code to be executed when the user has left the app } @Override public void onClosed ( Ad ad ) { // Code to be executed when when the user is about to return // to the app after tapping on an ad } }); requestNewInterstitial (); } private void requestNewInterstitial () { AdRequest adRequest = new AdRequest (). addTestDevice (” seeYourLogcatForTheHash “); mInterstitialAd …. loadAd (adRequest); } public void displayInterstitial (){ if (!mInterstitialAd .. isLoaded ()){ requestNewInterstitial (); }else{ mInterstitialAdd … show (); }} @Override protected void onResume () { super ….onResume(); displayInterstitial(); }}
Connecting both activities: 1.. Open Your MainActivity java File 2.. In OnCreate method write down this code : Button button = findViewById(R id … button); button….setOnClickListener(new View……..OnClickListener() { @Override public void OnClick(View v) { startActivity(new Intent………SecondActivity……class)); finish(); }});