Correctly disable AdMob ads
In your layout file (eg, main.xml) :
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/adsContainer"> <com.admob.android.ads.AdView android:id="@+id/admobAds" android:layout_width="fill_parent" android:layout_height="fill_parent" app:backgroundColor="#000000" app:primaryTextColor="#FFFFFF" app:secondaryTextColor="#CCCCCC"></LinearLayout>
Then in your code (eg, inside a "if" block)
(LinearLayout) adscontainer = (LinearLayout) findViewById(R.id.adsContainer);View admobAds = (View) findViewById(R.id.admobAds);adscontainer.removeView(admobAds);
This will "permanently" (for the lifecycle of the app) remove the ads from the layou, which means that there will not be any ads requested.
I also wanted to give users the ability to disable ads - why force people to see them if they don't want to? and why should you expect people to pay for that option?
Anyway, I outlined how I did this in this article. The article goes into more detail but here's the relevant parts:
The code i use to turn off ads:
private void hideAd() { final AdView adLayout = (AdView) findViewById(R.id.adView1); runOnUiThread(new Runnable() { @Override public void run() { adLayout.setEnabled(false); adLayout.setVisibility(View.GONE); } });}
And to turn them back on (in case anyone was feeling generous)
private void showAd() { final AdView adLayout = (AdView) findViewById(R.id.adView1); runOnUiThread(new Runnable() { @Override public void run() { adLayout.setEnabled(true); adLayout.setVisibility(View.VISIBLE); adLayout.loadAd(new AdRequest()); } });}
Unfortunately the setVisibility(View.GONE);
+ setEnabled(false)
combo does not work universally on all android versions / devices. Depending on when do you invoke it you may end up hanged in empty screen (no NPE, just blank screen).
So far the only solution that works for me is:
For Activity:
protected void removeAdView(int adViewId) { View view = getWindow().getDecorView(); View adView = view.findViewById(adViewId); if (adView != null) { ViewGroup parent = (ViewGroup) adView.getParent(); parent.removeView(adView); parent.invalidate(); }}
For Fragment:
protected void removeAdView(View topView, int adViewId) { View adView = topView.findViewById(adViewId); if (adView != null) { ViewGroup parent = (ViewGroup) adView.getParent(); parent.removeView(adView); parent.invalidate(); }}
This solution is based on @Quartertone's answer but extended to be more universal (i.e. works with all ViewGroup
s not just LinearLayout
). Just put these methods in your base Activity/Fragment classes.