+ // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
+ @SuppressWarnings("deprecation")
+ @Override
+ public WebResourceResponse shouldInterceptRequest(WebView view, String url){
+ if (adBlockerEnabled) { // Block ads.
+ // Extract the host from `url`.
+ Uri requestUri = Uri.parse(url);
+ String requestHost = requestUri.getHost();
+
+ // Create a variable to track if this is an ad server.
+ boolean requestHostIsAdServer = false;
+
+ // Check all the subdomains of `requestHost`.
+ while (requestHost.contains(".")) {
+ if (adServersSet.contains(requestHost)) {
+ requestHostIsAdServer = true;
+ }
+
+ // Strip out the lowest subdomain of `requestHost`.
+ requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
+ }
+
+ if (requestHostIsAdServer) { // It is an ad server.
+ // Return an empty `WebResourceResponse`.
+ return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
+ } else { // It is not an ad server.
+ // `return null` loads the requested resource.
+ return null;
+ }
+ } else { // Ad blocking is disabled.
+ // `return null` loads the requested resource.
+ return null;
+ }
+ }
+