Adaptive banner: the actual implementation
In Google developers article where it explain how to create an adaptive banner, the showing code appears to be obsolete and some deprecation appears:
private AdSize getAdSize() {
// Step 2 - Determine the screen width (less decorations) to use for the ad width.
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float widthPixels = outMetrics.widthPixels;
float density = outMetrics.density;
int adWidth = (int) (widthPixels / density);
// Step 3 - Get adaptive ad size and return for setting on the ad view.
return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth);
}
Android Studio reveals that:
warning: [deprecation] getDefaultDisplay() in WindowManager has been deprecated
Display display = getWindowManager().getDefaultDisplay();
warning: [deprecation] getMetrics(DisplayMetrics) in Display has been deprecated
display.getMetrics(outMetrics);
WindowManager.getDefaultDisplay()
is deprecated in API level 30 (Android 11) and must be substituted by Context.getDisplay()
.
Display.getMetrics()
is deprecated in API level 30 and must be substituted by WindowMetrics.getBounds()
and Configuration.densityDpi
.
So, to adapt all this deprecated code to our adaptive banner, to get the right width, we can rearrange all this method AdSize getAdSize()
with this simple 2 lines of code:
private static AdSize getAdSize(AppCompatActivity activity) {
int windowWidth = activity.getResources().getConfiguration().screenWidthDp;
return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(activity, windowWidth);
}
for API level 13+.
The differences: the first is a normal banner: it does not take all the available width of the screen.
The second is a smart banner: take all the width, smartly not enough to resize its height.
The third is very smart banner, named adaptive banner: it takes all the width and accommodates its height.