Skip to main content

Rendering AdMob view on Canvas (SurfaceView) in android

If you're wondering how put a working AdMob view into your SurfaceView and are tired of looking in the Internet for solution (somehow most suggestions that I found on forums didnt work), here it is...

Assumptions:
A. We request the ad on creation (you may want to refresh it later though...)
B. The AdView is put on the bottom of the screen
C. It's a production ready code, but if you want to test it - add testDevices to the adRequest
D. You've already set AndroidManifest properly as described in the Getting Started tutorial

1. In the activity that initializes your SurfaceView add a field representing your adView, for example:

 private AdView adView;

2. In the onCreate method of the same activity put the following code:

  // window manager preparation 
  WindowManager.LayoutParams windowParams = new WindowManager.LayoutParams();
  windowParams.gravity = Gravity.BOTTOM;
  windowParams.x = 0;
  windowParams.y = 0;
  windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
  windowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
  windowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
  windowParams.format = PixelFormat.TRANSLUCENT;
  windowParams.windowAnimations = 0;

  WindowManager wm = getWindowManager();
  // Create the adView
  adView = new AdView(this, AdSize.BANNER, YOU_ADMOB_SITE_ID);

  // Initiate a generic request to load it with an ad
  adView.loadAd(new AdRequest());

  // Add adView to WindowManager
  wm.addView(adView, windowParams);
3. Override the onDestroy to do the cleanup (or add the cleanup code to your onDestroy if you're already doing something there)

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

Kudos for the concept (and most of the code) to EvilDuck and his post on stackoverflow which was talking about GLSSurfaceView, still the approach was generic enough to work without OpenGL :)

Comments

  1. Thx a lot. Worked for me. But you need add the adView to WindowManager. wm.addView(adView, windowParams);

    ReplyDelete
    Replies
    1. Thank you Mohamed, good point :) I've just fixed this!

      Delete
  2. Any idea why it doesn't work at the top of the screen? Just cuts of the ad...

    ReplyDelete
    Replies
    1. Interesting, are you running your app in the full screen?

      Delete
  3. I always get an error at this line wm.addView(adView, windowParams);
    Error: android.view.WindowLeaked: Activity has leaked window com.google.android.gms.ads.AdView that was originally added here
    Please help!

    ReplyDelete

Post a Comment