public class AdBlocker {
public static final String TAG = AdBlocker.class.getName();
private static final String AD_HOSTS_FILE = "ads.txt";
private static final Set<String> AD_HOSTS = new HashSet<>();
public static void init(Context context) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Log.d(TAG, "doInBackground: Reklam filtresi yükleniyor");
loadFromAssets(context);
} catch (IOException e) {
// noop
e.printStackTrace();
}
return null;
}
}.execute();
}
@WorkerThread
private static void loadFromAssets(Context context) throws IOException {
InputStream stream = context.getResources().openRawResource(R.raw.ads);
BufferedSource buffer = Okio.buffer(Okio.source(stream));
String line;
while ((line = buffer.readUtf8Line()) != null) {
AD_HOSTS.add(line);
}
buffer.close();
stream.close();
}
}
🎈 Activity Üzerinde Tanımlama
public class MainActivity extends AppCompatActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
AdBlocker.init(this);
...
}
💎 Engellemeleri Tanımlama
public class AdBlocker {
...
public static boolean isAd(String url) {
HttpUrl httpUrl = HttpUrl.parse(url);
return isAdHost(httpUrl != null ? httpUrl.host() : "");
}
private static boolean isAdHost(String host) {
if (TextUtils.isEmpty(host)) {
return false;
}
int index = host.indexOf(".");
return index >= 0 && (AD_HOSTS.contains(host) ||
index + 1 < host.length() && isAdHost(host.substring(index + 1)));
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static WebResourceResponse createEmptyResource() {
return new WebResourceResponse("text/plain", "utf-8", new ByteArrayInputStream("".getBytes()));
}
}
webView.setWebViewClient(new WebViewClient() {
private final Map<String, Boolean> loadedUrls = new HashMap<>();
@SuppressWarnings("ConstantConditions")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
boolean ad;
if (!loadedUrls.containsKey(url)) {
ad = AdBlocker.isAd(url);
loadedUrls.put(url, ad);
} else {
ad = loadedUrls.get(url);
}
return ad ? AdBlocker.createEmptyResource() :
super.shouldInterceptRequest(view, url);
}
});
// HTTP protokolleri WebView'da düzgün çalışmıyor ve güvenli değil (?)
url = url.replace("http://", "https://");
webView.loadUrl(url);