简体   繁体   中英

Safely Removing an AdView from a LinearLayout for Ad Free Users

I have an Android App with a Banner Ad in it. I only put in the AdView element into the LinearLayout after I have checked ads are meant to be displayed.

However, the user can purchase NoAds during the run time of the program. This means I have to safely stop the ad and remove the Adview from the program without falling foul of Admob rules where you cannot hide adverts.

Here is my code, but I am very unsure about the section in the if statement on the line if (mAdView != null) { // It might not be created yet .

Is that just hiding it, not removing it completely?:

public void turnAdvertsOnOff(boolean on) {
    advertsOn = on;

    // IMPORTANT - changes to layout must be done on the UI Thread or will get error
    m_Context.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            LinearLayout myLayout;
            // NEW
            //AdView mAdView;

            myLayout = (LinearLayout) m_Context.findViewById(R.id.myLayout);
            //mAdView = (AdView) m_Context.findViewById(R.id.adView);

            if(advertsOn){
                if(mAdView == null && myLayout != null) {
                    // Create it and add it to the LinearLayout
                    mAdView = new AdView(m_Context);
                    // Sizes BANNER, SMART_BANNER, LARGE_BANNER
                    mAdView.setAdSize(AdSize.SMART_BANNER);
                    mAdView.setAdUnitId(adIdBanner);
                    myLayout.addView(mAdView);
                }
                if (mAdView != null) mAdView.setVisibility(View.VISIBLE);
            }else {
                if (mAdView != null) { // It might not be created yet
                    mAdView.pause();
                    mAdView.setEnabled(false);
                    mAdView.setVisibility(View.GONE);
                    //mAdView.destroy();
                    //mAdView.setVisibility(View.INVISIBLE);
                    //mAdView.pause();
                    //mAdView.setVisibility(View.GONE);
                }
            }
        }});
}

The preferred way is to remove() the AdView from its parent.
Why not set Visibility to GONE?
If you set the visibility to GONE, the AdView will still request the Ad Servers to fill in the Ads, so its better to completely remove the AdView .

For example -
Add the AdView in you layout file, if the User has removed the Ads via IAP, just call myLayout.removeView(mAdView);

Also there's no need to call runOnUiThread() if you are calling turnAdvertsOnOff() from the ui thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM