How to block Ads on Android Webview

Dr Adam Fils
2 min readMar 31, 2020

--

Ads are annoying, i just had to say it. Today i will be showing you how to block Ads in Android Webview in 4 Steps.

Blocking Ads On Android
Source: https://techcrunch.com/2015/09/12/raymond-carver-loved-ads/

First, Let’s create a function we’ll call it getTextWebResource and it will take an InputStream as a Parameter.

private WebResourceResponse getTextWebResource(InputStream data) {
return new WebResourceResponse("text/plain", "UTF-8", data);
}

Secondly, Setup you webview with findviewbyid all that good stuff. You will need to set a new WebClient and ovveride the method shouldInterceptRequest(WebView view, String url)

Thirdly, i will be checking for Google or Facebook Ads so i will have add an if statement and checks every url that is loaded into and Webview and if the url contains google or facebook… We replace it with an empty text and bammm!!!! they are Knocked out of the Webview.

webView.setWebViewClient(new WebViewClient() {
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if(url.contains("google")||url.contains("facebook")){
InputStream textStream = new ByteArrayInputStream("".getBytes());
return getTextWebResource(textStream);
}
return super.shouldInterceptRequest(view, url);
}
}

Bonus tip:

If you want to do something fancy like replace the url with an image.. you do.

private WebResourceResponse getImageWebResource(InputStream data) {
return new WebResourceResponse("image/jpg", "UTF-8", data);
}
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if(url.contains("google")||url.contains("facebook")){
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.picture_to_load);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(imageInByte);
return getImageWebResource(bis);
}
return super.shouldInterceptRequest(view, url);
}

That will be all for now. Like, Clap, Follow For More.

You can also comment what other tutorial you will like me to cover in the future.

--

--

Dr Adam Fils

Adam - Google Android Engineer 📱 Passionate coder, problem solver 💡 & vocalist 🎤 Innovating the tech world while hitting the high notes 🎶 Follow my journey!