Monday, February 6, 2017

Android programming: Banner Ads


I managed to set up the banner ad in my little app. Here is the summary of the changes:
  • Set minSdkVersion to 9 or higher.
  • To use Firebase, add these dependencies and plugin to the app/build.gradle file:
dependencies {
...
    compile 'com.google.android.gms:play-services:10.0.1'
    compile 'com.google.firebase:firebase-ads:10.0.1'
    compile 'com.google.android.gms:play-services-ads:10.0.1'
}

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

  • Add this dependency to the project's build.gradle file:
dependencies {
        classpath 'com.google.gms:google-services:3.0.0'
        classpath 'com.android.tools.build:gradle:2.2.3'
}
  • Add permission to use INTERNET in app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
  • Add the Ad unit ID and app ID to the strings.xml file. The following shows the test IDs used in Google's example. To get the IDs for my real app, I went to the Admob web site and registered my app. Admob then generated the Ad unit ID and the app ID, and offered to send the IDs and setup instruction to my Email.
<string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>
<string name="banner_ad_app_id">ca-app-pub-3940256099942544~3347511713</string>

  •  Now the real stuff, add the AdView widget to the app:
...
          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"
...
<com.google.android.gms.ads.AdView
           android:id="@+id/adView"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_centerHorizontal="true"
           android:layout_alignParentBottom="true"
           ads:adSize="BANNER"
           ads:adUnitId="@string/banner_ad_unit_id" />

  • In the onCreate() method of the Activity, or the onCreateView() method of the Fragment, add the code to fetch the Ad:
MobileAds.initialize(getActivity().getApplicationContext(), 
                     getString(R.string.banner_ad_app_id));

AdView mAdView = (AdView) v.findViewById(R.id.adView);
AdRequest.Builder builder = new AdRequest.Builder();
AdRequest adRequest = builder.build();
mAdView.loadAd(adRequest);

  •  Note: I have tried to use builder.addKeyword() to retrieve targeting Ads. Unfortunately, this feature is not supported by Admob yet. And using builder.addKeyword() makes Ads rendering much slower.

No comments:

 
Get This <