A note on ad size and mediating smart banners

Smart banners are a handy thing for publishers. You can drop an AdMob smart banner into a layout or storyboard, and it’ll stretch or squeeze itself at runtime until it’s just the right size for the device, then request an ad to match. They’re a great feature with all the extra work hidden under the hood.

If you’re building an Android mediation adapter or custom event, though, things aren’t quite as simple -- after all, you’re under that hood, too! A common rough spot for developers is retrieving a smart banner’s size. Because the Google Mobile Ads SDK uses constants to internally represent a smart banner’s height and width, the getHeight and getWidth methods of a smart banner’s AdSize will return those constants (they’re negative numbers, so they’re quite hard to miss). That means relying on calls to getHeight and getWidth to determine a smart banner’s true size isn’t a workable strategy.

So how should adapter and custom event developers calculate sizes correctly? By avoiding getHeight and getWidth, and instead asking for pixel counts using getHeightInPixels and getWidthInPixels, two other methods offered by AdSize. You can scale their return values according to the device’s metrics and end up with the same kind of DPI values returned by getWidth and getHeight for other ad sizes. Here’s a code snippet that shows how it’s done:

// Get the raw pixel counts.
int widthInPixels = size.getWidthInPixels(context);
int heightInPixels = size.getHeightInPixels(context);

// These metrics include screen density, which is what we’re after.
DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();

// These are values you can send to your mediated network’s SDK.
int widthInDpi = Math.round(widthInPixels / displayMetrics.density);
int heightInDpi = Math.round(heightInPixels / displayMetrics.density);

Once you finish the math, you’ll have proper DPI values that can be sent to whichever network you’re mediating. The calls to getHeightInPixels and getWidthInPixels require a valid Context, but you can use the one provided as a parameter to the requestBannerAd methods in MediationBannerAdapter and CustomEventBanner.

Now you know the best way to gauge the size of a smart banner! Use this approach and it’ll help keep your mediation running smoothly.

If you have technical questions about this (or anything else relating to the Google Mobile Ads SDK) stop by our forum.