How to prevent ad blocker from blocking ads on an app

AndroidAdsAdblock

Android Problem Overview


One of my users let the cat out of the bag and told me they were using one of my free apps, which is monetized by ads, but they were blocking the ads with an ad blocker. They told me this mockingly, as if I can't do anything about it.

Can I do something about it? Is there a way to detect that ads are being blocked?

Android Solutions


Solution 1 - Android

I am aware of one way that ad blocking works (on any computer really), they edit the hosts file to point to localhost for all known ad servers. For android this is located in the "etc/hosts" file.

For example, I use admob ads and a host file that I have taken from custom rom lists the folowing admob entries:

127.0.0.1 analytics.admob.com
127.0.0.1 mmv.admob.com
127.0.0.1 mm.admob.com
127.0.0.1 admob.com
127.0.0.1 a.admob.com
127.0.0.1 jp.admob.com
127.0.0.1 c.admob.com
127.0.0.1 p.admob.com
127.0.0.1 mm1.vip.sc1.admob.com
127.0.0.1 media.admob.com
127.0.0.1 e.admob.com

Now anytime a process tries to resolve the above addresses they are routed to the address listed to the left of them (localhost) in this case.

What I do in my apps is check this host file and look for any admob entries, if I find any I notify the user that I've detected ad blocking and tell them to remove admob entries from there and do't allow them use of the app.

After all what good does it do me if they're not seeing ads? No point in letting them use the app for free.

Here is a code snippet of how I achieve that:

	    BufferedReader in = null;
    
    try 
    {
        in = new BufferedReader(new InputStreamReader(
        		new FileInputStream("/etc/hosts")));
        String line;
        
        while ((line = in.readLine()) != null)
        {
        	if (line.contains("admob"))
        	{
        		result = false;
        		break;
        	}
        }
    } 

I vow that all ad supported apps should check this file. You do not need to be root in order to access it, but writing to it might be a different story.

Also, not sure if there is any other files that act the same on a linux based OS, but at any rate we can always check all of those files.

Any suggestions on improving this are welcome.

Also the app called "Ad Free android" needs root access, meaning that it most likely changes the hosts file in order to achieve its goal.

Solution 2 - Android

My code for this issue is thusly: -

try {
	if (InetAddress.getByName("a.admob.com").getHostAddress().equals("127.0.0.1") ||
		InetAddress.getByName("mm.admob.com").getHostAddress().equals("127.0.0.1") ||
		InetAddress.getByName("p.admob.com").getHostAddress().equals("127.0.0.1") ||
		InetAddress.getByName("r.admob.com").getHostAddress().equals("127.0.0.1")) {
		//Naughty Boy - Punishing code goes here.
		// In my case its a dialog which goes to the pay-for version 
		// of my application in the market once the dialog is closed.
	}
} catch (UnknownHostException e) { } //no internet

Hope that helps.

Solution 3 - Android

As developers, we need to do the difficult job of empathizing with the users and find a middle ground between punishing the few who try to take advantage and the many who play by the rules. Mobile advertising is a reasonable way to allow someone to use a functional piece of software for free. The users who employ ad blocking techniques could be considered lost revenue, but if you take a look at the big picture, can also be those who spread the word about your application if they like it. A more gentle approach to running on systems with ads blocked is to display your own "house" ad. Create one or more banner images and display them in the same spot as your normal ad with an ImageView of the same height (e.g. 50dp). If you successfully receive an ad, then set your ImageView's visibility to View.GONE. You can even create a timer to cycle through several house ads to get the user's attention. Clicking on your ad can take the user to the market page to buy the full version.

Solution 4 - Android

Can you check to see if the ad loaded in your app?

Ad blockers work by preventing your app from downloading data. You could check the content length of the data in your ad frame to make sure there is data there.

If there is no data throw up a message and exit or warn you with an email.

It might not be as big an issue as you think since only a small percentage of people block ads.

Solution 5 - Android

The top two answers help you with only a particular (if, probably, the most popular) method of blocking ads. Root users can also block ads with a firewall on the device. WiFi users can block ads with an upstream firewall.

I suggest:

  1. Don't reward ad-blocking users. Ensure that your layout reserves part of the display for an ad even if one can't be loaded. Or if you have a full-screen ad that plays for a bit, ensure that your app waits for a bit even if the ad can't be played. If you use notifications as adverts (you scum), notify the user when you fail to get such an advert. This could be read as "annoy all of your users", but your normal users know what they're getting, and your ad-blocking 'users' aren't wanted.

  2. Ask ad-blockers to stop. The less proftable an industry that supplies what a user wants, the less that industry will supply what the user had wanted. An individual developer will find that he makes more money serving other users. You know this, and your users will think it obvious after you tell them, but it's still an economic argument - it's not intuitive. Have a backup ad that says something like, "This is my job. If you don't pay me, I'll get another one, and you won't get more apps like this from me."

Solution 6 - Android

There is nothing you can do that your users can't do better.

The only thing that comes to mind as remotely effective is to make the ads an inextricable part of the program, so that if they're blocked the user cannot make sense of/interact with the application.

Solution 7 - Android

Rather than checking for individual software installed or modified hosts file, my approach is using an AdListener [like this][1] and, if the ad fails to load due to NETWORK_ERROR, I just fetch some random always-online page (for the kicks, apple.com) and check if the pages loads successfully.

If so, [boom goes the app][2].

To add some code, listener class would be something like:

public abstract class AdBlockerListener implements AdListener {

	@Override
	public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
		if (arg1.equals(ErrorCode.NETWORK_ERROR)) {
			try {
				URL url = new URL("http://www.apple.com/");
				URLConnection conn = url.openConnection();
				BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				reader.readLine();
				onAdBlocked();
			} catch (IOException e) {}
		}
	}
	
	public abstract void onAdBlocked();
}

And then each activity with an adView would do something like:

AdView adView = (AdView) findViewById(R.id.adView);
        adView.setAdListener(new AdBlockerListener() {
			@Override
			public void onAdBlocked() {
				AlertDialog ad = new AlertDialog.Builder(CalendarView.this)
									.setMessage("nono")
									.setCancelable(false)
									.setNegativeButton("OK", new OnClickListener() {
										public void onClick(DialogInterface dialog, int which) {
											System.exit(1);
										}
									})
									.show();
			}
		});

[1]: http://www.bloggure.info/work/java-work/android-java-work/android-detect-adblocking.html "an adlistener like this" [2]: http://en.wikipedia.org/wiki/Boom_goes_the_dynamite

Solution 8 - Android

I think it depends on the content provider for the ads. I know the AdMob SDK provides a callback when an ad request fails. I suspect that you might be able to register for this, then check for a connection in the callback - if there is a connection and you did not receive an ad - take note, if it happens more than once or twice, chances are likely your ads are being blocked. I have not worked with the AdSense for Mobile toolset from Google but it wouldn't surprise me if there was a similar callback mechanism.

Solution 9 - Android

There are two ways for a user to by pass a advertisement:

  1. Use app without internet on.

  2. With rooted phone and modified host file.

I made two tools that you can implement, see code below.

checkifonline(); is for problem 1:

public void checkifonline() {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

	ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
	
	if(haveConnectedWifi==false && haveConnectedMobile==false){

		// TODO (could make massage and than finish();
	}
}

adblockcheck(); is for problem 2

private void adblockcheck() {
	BufferedReader in = null;
    boolean result = true;

    try 
    {
        in = new BufferedReader(new InputStreamReader(
                new FileInputStream("/etc/hosts")));
        String line;

        while ((line = in.readLine()) != null)
        {
            if (line.contains("admob"))
            {
            	result = false;
                break;
            }
        }
    } catch (UnknownHostException e) { }
      catch (IOException e) {e.printStackTrace();}	
   
    if(result==false){

    	// TODO (could make massage and than finish();

    }
}

Solution 10 - Android

This is an extension of a previous answer. The user has informed me that the app they are using is called AdFree Android. It can be found on the market. The app says it works by "nullifying requests to known hostnames serving ads."

I suggest that if you monetize any of your apps with ads, you check at startup for this program and give the user a nasty message, then terminate your app.

Solution 11 - Android

First, let me say that I believe that Ad Blocking, when it comes to applications, is actually a form of piracy. These apps are supported by the ads, and sometimes, a "paid license" to turn off ads and/or add features. By blocking ads, users are stealing potential revenue from the developer that took the time to create the app that you are using.

Anyhow, I want to add a way to help prevent the use of Ad Blockers. I use this method and I do not allow users to use the app if I detect an ad blocker. People get very angry and will give you poor ratings for it. But I also state very clearly in my applications descriptions that you will not be able to use the app if you have an adblocker.

I use the package manager to check if a specific package is installed. While this will not get all of the adblockers, if you keep "up to date" on some of the popular ones, you can get most of them.

PackageManager pm = activity.getPackageManager ();
Intent intent = pm.getLaunchIntentForPackage ( "de.ub0r.android.adBlock" );
if ( Reflection.isPackageInstalled ( activity, intent ) ) {
  // they have adblock installed
}

Solution 12 - Android

Give your users a way to use the app without the ads. I personally find ads one of the most annoying things that could possibly happen on my computer, and I will gladly pay for an application if it spares me the insult of having ads thrown into my face. And I'm sure I'm not the only one.

Solution 13 - Android

For the case when there is no internet connection, I have followed this tutorial and I've build a "network state listener" like so:

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() 
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        
		if (noConnectivity == true)
		{
			Log.d(TAG, "No internet connection");
			image.setVisibility(View.VISIBLE);
		}
		else
		{
            Log.d(TAG, "Interet connection is UP");
			image.setVisibility(View.GONE);
			add.loadAd(new AdRequest());
		}
    }
};

@Override
protected void onCreate(Bundle savedInstanceState)
{
	//other stuff
	private ImageView image = (ImageView) findViewById(R.id.banner_main);
	private AdView add = (AdView) findViewById(R.id.ad_main);
	add.setAdListener(new AdListener());
}

@Override
protected void onResume()
{
	registerReceiver(mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
	super.onResume();
}

@Override
protected void onPause()
{
	unregisterReceiver(mConnReceiver);
	super.onPause();
}

registerReceiver and unregisterReceiver have to be called in onResume and onPause respectively, as described here.

In your layout xml set up the AdView and an ImageView of your own choice, like so:

<com.google.ads.AdView xmlns:googleads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_alignParentBottom="true"
    android:id="@+id/ad_main"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    googleads:adSize="BANNER"
    googleads:adUnitId="@string/admob_id" />

<ImageView
    android:id="@+id/banner_main"
    android:layout_centerInParent="true"
    android:layout_alignParentBottom="true"
	android:layout_width="379dp"
    android:layout_height="50dp"
    android:visibility="gone"
    android:background="@drawable/banner_en_final" />

Now, whenever the internet connection is available the ad will display and when its off the ImageView will pop-up, and vice-versa. This must be done in every activity in which you want ads to display.

Solution 14 - Android

I'm sure this answer won't be entirely popular with certain segments of developers, however consider if you fall into this category that perhaps your app doesn't deserve to exist on the app store. Please note that these are all implementable as code changes, no hackery or spyware like behavior required.

Basically, change the economics of your app. The User is Always Right - this is the attitude taken by one of the most successful advertising companies ever (Google). If your ads are being blocked by users, its because you suck, not because ads or ad-blockers suck.

http://books.google.com/books/about/The_User_is_Always_Right.html?id=gLjPMUjVvs0C

  • Make ads less annoying and in-your-face. Users react to poor/annoying advertisement, and the seedier your app looks and becomes, the more likely they are to ditch it anyways. I don't mind apps with ads in them as long as they aren't significantly impeding the functionality, and even better I like ads which are relevant to me. (http://www.nngroup.com/articles/most-hated-advertising-techniques/)
  • To detect that ads aren't being loaded, its not necessary to implement the spyware like activities mentioned by previous posters. Load an ad that has a confirmation code, and every once in awhile, insert a prompt asking for the confirmation code. The code doesn't have to be long or annoying, in fact it'd be enough to implement a captcha service with 3 or 4 letters/numbers. (http://textcaptcha.com/api)
  • In addition to detecting failure of ads to load, make better ads. Instead of using an API like mobads (Do you even realize how seedy that sounds? Mobs? Really? Are we developers, the Russian Mafia?), enter a partnership with an ad company that allows you to embed ads directly from your app. It will make your overall app larger to install, and no, you can't guard against manual modification, but the changes suggested above don't guard against that either. And this will better support any paid versions of your app, which will be much more lightweight (and faster).
  • Thoroughly vet the ads you are displaying to the user, be open and transparent about your ad policies, and even allow users to inspect your ads and ad sources. The primary reason I'm ever concerned about ads is not because I hate ads, but because I worry that the poor quality developer responsible for this app is letting in viruses or other malware as well. Ask that an exception be made to the installed adblocker. Team up with ad blockers like AdBlock to get on their exceptions list. If you are a legit application, this shouldn't be a problem. (http://www.cio.com/article/699970/6_Ways_to_Defend_Against_Drive_by_Downloads?page=1&taxonomyId=3089)

I re-iterate: all of the above changes are things you can legitimately do in code to prevent anti-ad behaviors. Ads are blocked for security reasons and visceral reactions, primarily, and sometimes bandwidth and performance, so make sure your ads don't invoke any of these problems, at the code level.

Finally I did want to touch on what Borealid said, which I re-iterated above; in the end it is a 'cat and mouse' game, because the user has ultimate authority and responsibility, both legally and morally, over their own property. A user can do whatever, including directly modify code on the fly. Of course, there are restrictions you can implement etc. but there are always ways to get around the problem. This is the ultimate problem (technically) with DRM (which is what you're trying to do). Rather than waste time and effort on this game, it is better to encourage users to keep ads around; they'll become your best, smartest anti-ad-blockers, for free.

Solution 15 - Android

As well as checking if admob can be resolved, what I do is present a page that basically advises that I have detected an adblocker, state that i understand the possible reasons why, then show some inbuilt ads of my own apps and ask for their kind support for continued development. :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristopher PerryView Question on Stackoverflow
Solution 1 - AndroidIvanView Answer on Stackoverflow
Solution 2 - AndroidJonathanView Answer on Stackoverflow
Solution 3 - AndroidBitBankView Answer on Stackoverflow
Solution 4 - AndroidByron WhitlockView Answer on Stackoverflow
Solution 5 - AndroidJulian FondrenView Answer on Stackoverflow
Solution 6 - AndroidBorealidView Answer on Stackoverflow
Solution 7 - AndroidFilipe PinaView Answer on Stackoverflow
Solution 8 - AndroidnEx.SoftwareView Answer on Stackoverflow
Solution 9 - AndroidJohnView Answer on Stackoverflow
Solution 10 - AndroidChristopher PerryView Answer on Stackoverflow
Solution 11 - AndroidRyan ConradView Answer on Stackoverflow
Solution 12 - AndroiddrmirrorView Answer on Stackoverflow
Solution 13 - AndroidGoran Horia MihailView Answer on Stackoverflow
Solution 14 - AndroidsmaudetView Answer on Stackoverflow
Solution 15 - AndroidpvellaView Answer on Stackoverflow