How to know if AdMob ad has been loaded

十年热恋 提交于 2019-11-29 01:11:32

From https://developers.google.com/mobile-ads-sdk/docs/android/intermediate#adlistener

AdView.setAdListener(new AdListener() {
      // Implement AdListener
    });

Your AdListener's onReceiveAd() will be called when an ad is available, onFailedToReceiveAd() will be called whan an ad isn't available with a code explaining why (including network not available and no fill)

Update:

Same basic answer, new URL: https://developers.google.com/admob/android/banner?hl=en

Waqar Vicky

Simply...!!!

final AdView mAdView = (AdView) findViewById(R.id.adView);
        mAdView.setVisibility(View.GONE);
    mAdView.setAdListener(new AdListener() {
        private void showToast(String message) {
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onAdLoaded() {
            showToast("Ad loaded.");
            if (mAdView.getVisibility() == View.GONE) {
                mAdView.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onAdFailedToLoad(int errorCode) {
            showToast(String.format("Ad failed to load with error code %d.", errorCode));
        }

        @Override
        public void onAdOpened() {
            showToast("Ad opened.");
        }

        @Override
        public void onAdClosed() {
            showToast("Ad closed.");
        }

        @Override
        public void onAdLeftApplication() {
            showToast("Ad left application.");
        }
    });


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

I solved this problem with a bit of a workaround. For the first time, I checked if AdView has an empty tag or not.

if (adView.getTag() != null && adView.getTag() instanceof Boolean && (Boolean) adView.getTag()) {
        //Adview is already loaded
    }

If adView has a Boolean tag object and it is true then ad is already loaded otherwise load the ad and set the tag -

adView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                adView.setTag(true); // Set tag true if adView is loaded
            }

            @Override
            public void onAdFailedToLoad(int i) {
                super.onAdFailedToLoad(i);
                adView.setTag(false); // Set tag false if loading failed
            }
        });

you can use isLoaded() method. I am using it on a same context as you and inside a timer to wait until ad is loaded.

https://developer.android.com/reference/com/google/android/gms/ads/InterstitialAd.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!