Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track Admob Event in Google Analytics

I want to track clicks on an AdMob banners with Google Analytics, but a problem occurs and I don't understand why.

Currently, my AdMob banner is implemented like this:
Layout:

<com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ads:adUnitId="YOUR_AD_UNIT_ID"
    ads:adSize="BANNER"/>

Java : AdView adView = (AdView)this.findViewById(R.id.adView);

However, the Google demonstration project which shows how to add an AdListener (project available here) does not specify anything in the layout and use the following code to add the banner:

LinearLayout layout = (LinearLayout) findViewById(R.id.leLinearLayoutDeMonChoix);
layout.addView(adView);

But if the implementation described at the beginning is used, the AdListener does not detect any event anymore. Why?

You can find this defective implementation in the following demonstration project: https://drive.google.com/file/d/0B8rE1pbtzNJ1UXg5QllubEFidGc/edit?usp=sharing

I thank you in advance for your time and help.

like image 473
LegZ Avatar asked Mar 04 '26 05:03

LegZ


1 Answers

In the provided implementation you are doing the following:

// Create an ad.
adView = new AdView(this);
// Set the AdListener.
adView.setAdListener(new AdListener() {
    /** stuff **/
}
AdView adView = (AdView)this.findViewById(R.id.adView);
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device.
AdRequest adRequest = new AdRequest.Builder()
    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
    .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
    .build();
// Start loading the ad in the background.
adView.loadAd(adRequest);

There is two instances of AdView, and this is your problem.

  • first one created from inflating your main.xml layout by setContentView(),
  • second one when you wrote adView = new AdView(this);

You set your listener on the second one, but only the first one is displayed. It cannot work. :)
Choose one method (create it from layout) or the other (create it from code), but don't mix them up.

If you want to create your ad from layout, do the following:

// Retreive the adView.
AdView adView = (AdView)this.findViewById(R.id.adView);
// Set the AdListener.
adView.setAdListener(new AdListener() {
    /** stuff **/
}
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device.
AdRequest adRequest = new AdRequest.Builder()
    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
    .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
    .build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
like image 167
pcans Avatar answered Mar 06 '26 19:03

pcans