Android : How To Integrate Google AdMob in your android application using Firebase

How To Integrate Google AdMob in your android application using Firebase



AdMob by Google is an easy way to monetize mobile apps with targeted, in-app advertising. It can be used to integrate ads in multiple platforms like android, ios, etc. 

AdMob by Google is a mobile advertising platform that you can use to generate revenue from your app. Using AdMob with Firebase Analytics provides you with additional app usage data and analytics capabilities.

AdMob is now a part of Firebase. Hence method of integrating the ads into your application is changed a bit. But Google has made it even simpler. 

Following are the prerequisites for integrating ads

  •  Android Studio 1.0 or higher
  •  Android API level 9 or above
  •  An Android Studio project

There are two types of ads : Banner and Interstitial

Banner ads appear on a portion of a screen while interstitial ads covers the whole screen. We will be discussing how to add banner ads. 

How to start ?

1. First of all you need to create a AdMob account. If you already have one, then Login to your account. 


Note : It is not necessary to own a website to integrate ads in your app. 

In this step, it will also ask you to create an AdSense account. Click on yes and go to next step.

2. Once you are logged in, click on Monetize tab 

3. Select the app if it's already published on the Play Store or Click on Add Your App Manually and then fill the details of your app.

4. Select ad format and name the unit. (Banner in this case).

5. Finish all the steps present there. 

6. Once above steps are done, you get an Ad unit ID. AdMob ad unit IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN.

Please note down this ID since it will be used in the later stages of development.


Most important step after this is to create an app in Firebase. This can be done in following way :


  • Go to Firebase console and create a new application. Enter the name of the application and the country.
  • Once the app is created, click on the Add Firebase to your Android app option
  • Enter the package name and click on add app.
  • Get the configuration file. (google-services.json file)
  • Download and move the configuration file to app/ folder of the project

How to integrate with your existing app code :

1. Create a new android studio project or open an existing project. Decide where to display the banner. Usually it's displayed at the bottom of your screen. 

2. Open app level build.gradle and add Firebase dependencies and click on Sync Now.

dependencies {
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.firebase:firebase-ads:9.0.0'
}

apply plugin: 'com.google.gms.google-services'

3. Go to strings.xml file and paste the following code.

<string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>

This is the place where you store the Ad Unit Id. Don't forget to replace your Ad Unit Id here.

4. Edit your AndroidManifest.xml and add the below code

Add permission to access the internet connection of the device which is necessary to load the advertise. Also, we add google services meta-data here and declare the ad activity. So, the final version of Manifest will look like below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.google.android.gms.example.bannerexample" >
    <!-- Include required permissions for Google Mobile Ads to run-->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <!--This meta-data tag is required to use Google Play Services.-->
        <meta-data android:name="com.google.android.gms.version" 
        android:value="@integer/google_play_services_version"/>
        <activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!--Include the AdActivity configChanges and theme. -->
        <activity android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|
            screenLayout|uiMode|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent" />
    </application>

</manifest>


5. Edit your activity_main.xml (Layout File) and add the below code.You can add the AdView anywhere your want. But make sure it's not affecting your existing views.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="@dimen/activity_vertical_margin"
    tools:context=".MyActivity"
    tools:ignore="MergeRootFrame">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:text="@string/hello_world" />

    <com.google.android.gms.ads.AdView
        android:id="@+id/ad_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id" />

</RelativeLayout>

6. Open MainAcitivity.java and modify the code as below. 

To initialize the Google Mobile Ads SDK at app launch, call MobileAds.initialize() in the onCreate() method of the MainActivity class.

The next change needed is for you to add to your app's main activity class some Java code that loads an ad into the AdView, as follows.


mAdView = (AdView) findViewById(R.id.ad_view);
AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .build();

    // Start loading the ad in the background.
    mAdView.loadAd(adRequest);

So, your MainAcitivity should look something like this:


private AdView mAdView;

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

    // Initialize the Mobile Ads SDK.
    MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");

    // Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
    // values/strings.xml.
    mAdView = (AdView) findViewById(R.id.ad_view);

    // Create an ad request. Check your logcat output for the hashed device ID to
    // get test ads on a physical device. e.g.
    // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .build();

    // Start loading the ad in the background.
    mAdView.loadAd(adRequest);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.my, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/** Called when leaving the activity */
@Override
public void onPause() {
    if (mAdView != null) {
        mAdView.pause();
    }
    super.onPause();
}

/** Called when returning to the activity */
@Override
public void onResume() {
    super.onResume();
    if (mAdView != null) {
        mAdView.resume();
    }
}

/** Called before the activity is destroyed */
@Override
public void onDestroy() {
    if (mAdView != null) {
        mAdView.destroy();
    }
    super.onDestroy();
}



7. Now Run your application and you will be able to see the ads in your app.  Make sure that you remove addTestDevice from AdRequest instance before you publish your app. 

8. Once you have implemented everything mentioned above, you need to connect your app from AdMob to Firebase app. To do this go to Analyze tab on your AdMob console and link your app to Firebase app.

Note:

As per AdMob Policies you are not allowed to click on your own live ads. In order to protect your AdMob account from getting suspended, use test ads during development as you might click the ads accidentally. 


When you run the project, if you monitor the LogCat, you can find a similar line 
AdRequest.Builder.addTestDevice(“C04B1BFFB0774708339BC273F8A43708”) to get test ads on this device. Copy the device id and add it to AdRequest as shown below. Note that this ID varies from device to device, By doing this, the test ads will be loaded instead of live ads. 

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


In production you need to make sure that you removed addTestDevice() methods in order to render the live ads and start monetization. 

So test ads looks something like this and will appear at the bottom of the page:


You can download the sample code from here.  

Comments

Popular posts from this blog

Android Firebase: Integrate Google Login in Your App

5 best Photo Editing Apps for Android

How to Add Menu Tabs in Blogger