Google Admob 廣告快速集成(並集成Firebase統計)

1.在Google Admob 平臺添加項目並新建廣告單元 https://apps.admob.com/

2.在Firebase 平臺添加項目,並下載 google-services.json 文件放到項目根目錄 https://firebase.google.com/

3.根目錄 build.gradle 設置如下:

buildscript {
    repositories {
        google()
        jcenter()
        
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'

        // Check for v3.1.2 or higher
        classpath 'com.google.gms:google-services:4.3.2'  // Google Services plugin
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        
    }
}

4.app 目錄 build.gradle 設置如下:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'


    //firebase ads
    implementation 'com.google.firebase:firebase-ads:18.3.0'
    implementation 'com.google.firebase:firebase-core:17.2.2'

    // (Recommended) Add Analytics
    implementation 'com.google.firebase:firebase-analytics:17.2.2'

}

//google services 放最底下
apply plugin: 'com.google.gms.google-services'

5.資源文件 res/values/strings.xml 設置如下:修改爲你在admob 平臺所添加的廣告單元

<string name="admob_id" translatable="false">ca-app-pub-2263676808286777~xxxxxxxxx</string>
<string name="bannerad_90_id" translatable="false">ca-app-pub-2263676808286777/xxxxxxxx</string>
<string name="bannerad_250_id" translatable="false">ca-app-pub-2263676808286777/xxxxxxxx</string>
<string name="interstitialad_id" translatable="false">ca-app-pub-2263676808286777/xxxxxxxxx</string>
<string name="rewardvideo_id" translatable="false">ca-app-pub-2263676808286777/xxxxxxxxxx</string>

6.AndroidManifest.xml 設置如下:

<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" /> <!-- google ads -->
<meta-data
     android:name="com.google.android.gms.ads.APPLICATION_ID"
     android:value="@string/admob_id" />

7.一個類完成所有初始化,使用時調用相關方法即可

package com.my.fruits;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.RelativeLayout;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
import com.google.firebase.analytics.FirebaseAnalytics;

public class AdmobAdsManager {
private String TAG=getClass().getName();
private MenuActivity menuActivity;

    public AdView menuAdView;
    public AdView adMediumRectangleView;
    public InterstitialAd mInterstitialAd;
    public RewardedVideoAd mRewardedVideoAd;

    public AdmobAdsManager(MenuActivity menuActivity){
        this.menuActivity=menuActivity;
        initGoogleAdmob();
    }

    public void startMenuAdViewLoadAd() {
        if (menuAdView != null) {
            menuAdView.loadAd(new AdRequest.Builder().build());
        }
    }

    public void startAdMediumRectangleViewLoadAd() {
        if (adMediumRectangleView != null) {
            adMediumRectangleView.loadAd(new AdRequest.Builder().build());
        }
    }

    public void startInterstitialAdViewLoadAd() {
        if (mInterstitialAd != null) {
            mInterstitialAd.loadAd(new AdRequest.Builder().build());
        }
    }

    public void hideAdmobBanner(){
        if(menuAdView!=null){
            menuAdView.setVisibility(View.GONE);
        }
    }

    public void hideAdmobMR(){
        if(adMediumRectangleView!=null){
            adMediumRectangleView.setVisibility(View.GONE);
        }
    }


    public void startRewardedVideoAdLoadAd() {
        if (mRewardedVideoAd != null) {
            mRewardedVideoAd.loadAd(ad_RewardVideo, new AdRequest.Builder().build());
        }
    }

     //測試廣告ID ,測試時使用這個即可
    private String Test_Banner="ca-app-pub-3940256099942544/6300978111";
    private String Test_Interstitial="ca-app-pub-3940256099942544/8691691433";
    private String Test_RewardVideo="ca-app-pub-3940256099942544/5224354917";

    private String ad_Banner_90;
    private String ad_Banner_250;
    private String ad_Interstitial;
    private String ad_RewardVideo;

    private void initGoogleAdmob() {

        //debug
//        ad_Banner_90=Test_Banner;
//        ad_Banner_250=Test_Banner;
//        ad_Interstitial=Test_Interstitial;
//        ad_RewardVideo=Test_RewardVideo;

        //release
        ad_Banner_90=TApplication.tApplication.getString(R.string.bannerad_90_id);
        ad_Banner_250=TApplication.tApplication.getString(R.string.bannerad_250_id);
        ad_Interstitial=TApplication.tApplication.getString(R.string.interstitialad_id);
        ad_RewardVideo=TApplication.tApplication.getString(R.string.rewardvideo_id);

        // Initialize the Mobile Ads SDK.
        MobileAds.initialize(TApplication.tApplication, TApplication.tApplication.getString(R.string.admob_id));

        // Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
        // values/strings.xml.
        menuAdView = new AdView(TApplication.tApplication);
        menuAdView.setId(View.generateViewId());
        menuAdView.setAdSize(AdSize.SMART_BANNER);
        menuAdView.setAdUnitId(ad_Banner_90);
        startMenuAdViewLoadAd();
        menuAdView.setAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(int i) {
                LogTools.i("MenuActivity==menuAdView==", "onAdFailedToLoad");

                menuAdView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startMenuAdViewLoadAd();
                    }
                }, 2 * 60 * 1000);

            }
        });

        final RelativeLayout.LayoutParams menuAdViewLp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, DpTools.dp2px(90));
        menuAdViewLp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        menuAdView.setLayoutParams(menuAdViewLp);

        adMediumRectangleView = new AdView(TApplication.tApplication);
        adMediumRectangleView.setId(View.generateViewId());

        adMediumRectangleView.setAdSize(AdSize.MEDIUM_RECTANGLE);
        adMediumRectangleView.setAdUnitId(ad_Banner_250);
        startAdMediumRectangleViewLoadAd();
        adMediumRectangleView.setAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(int i) {
                LogTools.i("MenuActivity==adMediumRectangleView==", "onAdFailedToLoad");

                adMediumRectangleView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startAdMediumRectangleViewLoadAd();
                    }
                }, 2 * 60 * 1000);


            }
        });

        RelativeLayout.LayoutParams adMediumRectangleViewLp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, DpTools.dp2px(255));
        adMediumRectangleViewLp.setMargins(0, 0, 0, 25);
        adMediumRectangleView.setLayoutParams(adMediumRectangleViewLp);


        //插頁廣告
        mInterstitialAd = new InterstitialAd(TApplication.tApplication);
        mInterstitialAd.setAdUnitId(ad_Interstitial);
        startInterstitialAdViewLoadAd();
        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(int i) {
                LogTools.i("MenuActivity==mInterstitial==", "onAdFailedToLoad");

                  new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startInterstitialAdViewLoadAd();
                    }
                }, 2 * 60 * 1000);

            }

            @Override
            public void onAdClosed() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // Load the next interstitial.
                        startInterstitialAdViewLoadAd();
                    }
                }, 2 * 60 * 1000);

            }

        });

        //激勵廣告
        mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(TApplication.tApplication);
        startRewardedVideoAdLoadAd();
        mRewardedVideoAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {

            boolean isReword;

            @Override
            public void onRewardedVideoAdLoaded() {
                LogTools.i("MenuActivity", "onRewardedVideoAdLoaded");

            }

            @Override
            public void onRewardedVideoAdOpened() {
                LogTools.i("MenuActivity", "onRewardedVideoAdOpened");

            }

            @Override
            public void onRewardedVideoStarted() {
                LogTools.i("MenuActivity", "onRewardedVideoStarted");

            }

            @Override
            public void onRewardedVideoAdClosed() {
                LogTools.i("MenuActivity", "onRewardedVideoAdClosed");

                if (isReword) {

                    //獎勵廣告 回調處理
                    //........

                    isReword = false;
                }

                startRewardedVideoAdLoadAd();
            }

            @Override
            public void onRewarded(RewardItem rewardItem) {
                LogTools.i("MenuActivity", "onRewarded");
                isReword = true;
            }

            @Override
            public void onRewardedVideoAdLeftApplication() {
                LogTools.i("MenuActivity", "onRewardedVideoAdLeftApplication");

            }

            @Override
            public void onRewardedVideoAdFailedToLoad(int i) {
                LogTools.i("MenuActivity", "onRewardedVideoAdFailedToLoad");

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startRewardedVideoAdLoadAd();
                    }
                }, 2 * 60 * 1000);

            }

            @Override
            public void onRewardedVideoCompleted() {
                LogTools.i("MenuActivity", "onRewardedVideoCompleted");
            }
        });


    }


    public void showAdmobInterstitialAds() {
        //插頁廣告顯示
        if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {


            mInterstitialAd.show();

            LogTools.i(TAG,"showAdmobInterstitialAds");

            Bundle bundle = new Bundle();
            bundle.putString("date", DataTools.getStringDate());
            FirebaseAnalytics.getInstance(TApplication.tApplication).logEvent("BCF_IL_AdmobAds", bundle);
        }
    }

    public void showAdmobRewardVideoAds() {
        //插頁廣告顯示
        if (mRewardedVideoAd != null && mRewardedVideoAd.isLoaded()) {

            mRewardedVideoAd.show();

            LogTools.i(TAG,"showAdmobRewardedVideoAds");

            Bundle bundle = new Bundle();
            bundle.putString("date", DataTools.getStringDate());
            FirebaseAnalytics.getInstance(TApplication.tApplication).logEvent("BCF_RV_AdmobAds", bundle);
        }
    }


    /**
     * Called when leaving the activity
     */
    public void onPause() {
        LogTools.i(TAG, "onPause");

        if (menuAdView != null) {
            menuAdView.pause();
        }

        if (adMediumRectangleView != null) {
            adMediumRectangleView.pause();
        }

        if (mRewardedVideoAd != null) {
            mRewardedVideoAd.pause(TApplication.tApplication);
        }
    }


    /**
     * Called when returning to the activity
     */
    public void onResume() {
        LogTools.i(TAG, "onResume");

        if (menuAdView != null) {
            menuAdView.resume();
        }

        if (adMediumRectangleView != null) {
            adMediumRectangleView.resume();
        }

        if (mRewardedVideoAd != null) {
            mRewardedVideoAd.resume(TApplication.tApplication);
        }


    }

    /**
     * Called before the activity is destroyed
     */
    public void onDestroy() {
        LogTools.i(TAG, "onDestroy");

        if (menuAdView != null) {
            menuAdView.destroy();

        }

        if (adMediumRectangleView != null) {
            adMediumRectangleView.destroy();

        }

        if (mRewardedVideoAd != null) {
            mRewardedVideoAd.setRewardedVideoAdListener(null);
            mRewardedVideoAd.destroy(TApplication.tApplication);
        }

        if (mInterstitialAd != null) {
            mInterstitialAd.setAdListener(null);
        }

    }


}

 

7.banner 廣告,在處於前臺的Activity動態添加廣告View,切換其他Activity時 也可以動態添加,一般添加到底部

            //Admob Ads
            if (menuActivity.admobAdsManager.menuAdView != null) {

                ViewGroup viewParent = (ViewGroup) menuActivity.admobAdsManager.menuAdView.getParent();
                if (viewParent != null) {
                    viewParent.removeView(menuActivity.admobAdsManager.menuAdView);
                }
                menuActivity.admobAdsManager.startMenuAdViewLoadAd();
                relativeLayout.addView(menuActivity.admobAdsManager.menuAdView);
            }

8.Interstitial 廣告展示

//插頁廣告顯示
menuActivity.admobAdsManager.showAdmobInterstitialAds();

9.RewardVideo 廣告展示

//獎勵廣告 展示
menuActivity.admobAdsManager.showAdmobRewardVideoAds();

10.初始化

admobAdsManager = new AdmobAdsManager(menuActivity);

所有代碼集成,需要改動相關簡單變量,請認真閱讀一遍代碼

最後附上本人開發的一些小遊戲:https://play.google.com/store/apps/details?id=com.nooogfaaar.flowerplumber

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章