在webView中除去广告

首先建一个ADFilterTool.java类

代码如下

 1 import android.content.Context;
 2 import android.content.res.Resources;
 3 
 4 public class ADFilterTool {
 5     public static boolean hasAd(Context context, String url) {
 6         Resources res = context.getResources();
 7         String[] adUrls = res.getStringArray(R.array.adBlockUrl);
 8         for (String adUrl : adUrls) {
 9             if (url.contains(adUrl)) {
10                 return true;
11             }
12         }
13         return false;
14     }
15 
16 }

然后建立一个资源文件AdUrlString.xml,添加需要去除的广告(如果是图片广告把加载图片的网址加进去)

1 <?xml version="1.0" encoding="utf-8"?>
2 <resources>
3     <string-array name="adBlockUrl">
4         <item>需要过滤的网址</item>
5     </string-array>
6 </resources>

在给webview中添加监听器

 1 wv.setWebViewClient(new WebViewClient() {
 2                                 //网络请求部分
 3                                 @Override
 4                                 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
 5                                     url = url.toLowerCase();
 6                                     Log.i("TAG", url);
 7                                     if (!url.contains("你的域名")) {
 8                                         if (!ADFilterTool.hasAd(MainActivity.this, url)) {
 9                                             return super.shouldInterceptRequest(view, url);
10                                         } else {
11                                             return new WebResourceResponse(null, null, null);
12                                         }
13                                     } else {
14                                         return super.shouldInterceptRequest(view, url);
15                                     }
16                                 }
17 
18                             }
19         );

 

posted @ 2020-02-27 21:56  东功  阅读(1045)  评论(0编辑  收藏  举报