Welcome to ahex technologies

Google AdMob integration for Android apps

Google AdMob integration for Android apps
  • July 31, 2018
  • Chakri Reddy
  • 0

AdMob is a multi platform mobile ad network that allows you to monetize your android app. By integrating AdMob you can start earning right away. It is very useful particularly when you are publishing a free app and want to earn some money from it.

In this article we’ll build a simple app to show the Banner Ad that AdMob supports.

1. Types of AdMob Ads

AdMob currently offers below types of ad units. You can choose the ad format depending on your app criteria.

Banner Ad

Banner Ads occupies only portion of the screen depending on the ad size that is created. It comes in multiple sizes Standard, Medium, Large, Full-Size, Leaderboard and Smart Banner. Smart banners are very useful when you target multiple device sizes and fit the same ad depending on the screen size.

Interstitial Ad

Interstitial ads occupies full screen of the app. Basically they will shown on a timely basis, between screen transition or when the user is done with a task. Usually we can see these ads in games displaying Ad when a level is completed.

Rewarded Video Ad

Rewarded Video Ads are fullscreen video ads which offers some reward points if the user watches the ad video. These ads are very useful to offer some reward points / coins in video games.

Native Ad

Native Ads offers flexibility to configure the ad appearance like color, text color and buttons to make them appear as native component of the app.

In this blog,we are going to implement a simple Banner ad and Interstitial ad which are most widely integrated in android apps

2. Creating Ad Units

  • Sign into your Admob account
  • Click on “Get Started” and Choose an option whether the app is live in market or not.

YES – provide the valid google play URL of the app

NO  – provide the  app information and choose the platform as “Android” and click on “ADD” button

  • Hurray! Your app has been added to admob after the above step.Please make a note of APP-ID somewhere as we need to use that in our source code in future

             Next,click on CREATE AD UNIT to move into further process

  • Choose the AD Format to integrate in the app.For now we are moving on with Banner Ad
  • Tap on SELECT button in the Banner Ad Format card to provide the ad unit details
  • Provide the Ad unit details in the form provided and click on CREATE AD UNIT
  • Congrats! with the above step your AD unit has been successfully created.Click on DONE button and proceed to with the integration process using the instructions given in the below screenshot.

3. Creating New Project

  • Create a new project in Android Studio from File ⇒ New Project. When it prompts you to select the default activity, select Empty Activity and proceed.
  • Open build.gradle and add play services dependency as AdMob requires it.
    compile ‘com.google.android.gms:play-services-ads:15.0.0

Build.gradle

   dependencies {
       compile fileTree(dir: 'libs', include: ['*.jar'])
       testCompile 'junit:junit:4.12'
       compile 'com.android.support:appcompat-v7:26.1.0'
       compile 'com.android.support:design:26.1.0'
       compile 'com.google.android.gms:play-services-ads:11.8.0'
     }


3
. Add the App ID and Ad unit IDs to your strings.xml. Open strings.xml located under res ⇒ values and add the IDs of all the ad units.

strings.xml

<resources>
  <!-- AdMob ad unit IDs -->
  <string name="admob_app_id">ca-app-pub-XXXXXXXX~XXXXXXXXXXX</string>
  <string name="banner_home_footer">ca-app-pub-XXXXXXXX~XXXXXXXXXXX</string>
  <string 
</resources>

4. Create a class named java and extend the class from Application. In this application class we have to globally initialize the AdMob App Id. Here we use MobileAds.initialize() method to initialize the AdMob.

(Note: App ID is different from Ad Unit ID. Place the App ID carefully)

MyApplication.java

import android.app.Application;
import com.google.android.gms.ads.MobileAds;

public class MyApplication extends Application {
 
    @Override
    public void onCreate() {
        super.onCreate();
 
        // initialize the AdMob app
        MobileAds.initialize(this, getString(R.string.admob_app_id));
    }
}

5. Open AndroidManifest.xml and add MyApplication to <application> tag to execute the class on app launch.

AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.ahextech.ahexadmobapp">
 
   <application
       android:name=".MyApplication"
       ...>
       <activity android:name=".MainActivity">
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
   </application>
</manifest>

Adding Banner AD

Banner ads occupies only a portion of the screen. I am adding a banner ad in my main activity aligning to bottom of the screen. In order to add the banner ad, you need to add com.google.android.gms.ads.AdView element to your xml layout.

<com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_home_footer">
</com.google.android.gms.ads.AdView>

6. Open the layout file of your main activity (activity_main.xml) and add the AdView widget.

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_home_footer" />
</RelativeLayout>

7. Open java and modify the code as shown.

  • Create an instance of AdRequest and load the ad into AdView.
  • Ad the AdView life cycle methods in onResume(), onPause() and in onDestroy() methods.

MainActivity.java

package com.example.ahextech.ahexadmobapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

public class MainActivity extends AppCompatActivity {

    private AdView mAdView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // TODO - remove this if condition
        // it's for demo purpose
        if (TextUtils.isEmpty(getString(R.string.banner_home_footer))) {
            Toast.makeText(getApplicationContext(), "Please mention your Banner Ad ID in strings.xml", Toast.LENGTH_LONG).show();
            return;
        }

        mAdView = (AdView) findViewById(R.id.adView);
        //mAdView.setAdUnitId(getString(R.string.banner_home_footer));

        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                // Check the LogCat to get your test device ID
                .build();

        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
            }

            @Override
            public void onAdClosed() {
                Toast.makeText(getApplicationContext(), "Ad is closed!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdLeftApplication() {
                Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdOpened() {
                super.onAdOpened();
            }
        });

        mAdView.loadAd(adRequest);
    }

    @Override
    public void onPause() {
        if (mAdView != null) {
            mAdView.pause();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAdView != null) {
            mAdView.resume();
        }
    }

    @Override
    public void onDestroy() {
        if (mAdView != null) {
            mAdView.destroy();
        }
        super.onDestroy();
    }
}

Now if you run the app, you should see a banner ad at the bottom of your screen.NOTE : While running the app, the Ads might not display and the below errors can be seen in LogCat.

There was a problem getting an ad response. ErrorCode: 1
  Failed to load ad: 1

If you happen find the above errors in your LogCat, there is no need worry. The newly created Ad Units takes few hours to display the actual ad. Until then you will see these errors. The best way to resolve this problem is to wait for few hours and test the app again.Cheers!