How to implement AdMob Banner ads in android app

Implementation This library build.gradle

implementation 'com.google.android.gms:play-services-ads:23.3.0'

Android Internet Permissions: AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    

Use this Meta-data Tag AndroidManifest.xml

<meta-data 
    android:name="com.google.android.gms.ads.APPLICATION_ID" 
    android:value="ca-app-pub-3940256099942544~3347511713" />

Xml Code: activty_main.xml

<com.google.android.gms.ads.AdView
    android:id="@+id/bannerAdView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

Paste these JAVA Codes inside On Create BuandleMainActivity.java

new Thread(
                () -> {
                    // Initialize the Google Mobile Ads SDK on a background thread.
                    MobileAds.initialize(this, initializationStatus -> {});
                })
                .start();

        loadBannerAd();
Paste these JAVA Codes outside of On Create BuandleMainActivity.java


    //============================= Banner ads Emplimention code Start here ==============
    //============================= Banner ads Emplimention code Start here ==============
    private void loadBannerAd() {
        AdView adView = new AdView(this);
        adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
        adView.setAdSize(getAdSize());

        AdView adContainerView = findViewById(R.id.bannerAdView);
        adContainerView.removeAllViews();
        adContainerView.addView(adView);

        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);

    }
    private AdSize getAdSize(){
        //calculate widthPixcel
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int adWidthPixels = displayMetrics.widthPixels;


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
            WindowMetrics windowMetrics = getWindowManager().getCurrentWindowMetrics();
            adWidthPixels = windowMetrics.getBounds().width();

        }

        //calculate Density
        float density = displayMetrics.density;

        //Calculate adWidth
        int adWidth = (int)(adWidthPixels/density);

        //Return adSize
        return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this,adWidth);

    } //============================= Banner ads Emplimention code End here ==============
    //============================= Banner ads Emplimention code End here ==============
    

Video tutorial in this post

Share this post with your friends

See the previous post See the next post
No one has commented on this post yet
Click here to comment
comment url