WebView adblock android | Block ads when using WebView in android | Adblock for WebView

WebView AdBlock android | Block ads when using WebView in android | Adblock for WebView

WebView adblock android | Block ads when using WebView in android | Adblock for WebView

Watch this video

In this post, we are going to learn how we can block ads in webview as browser extensions done in the browser.

When I get the idea on blocking ads in webview that time I search a lot on the internet but did not find any and then I think to make one for the internet and I started coding and find that the whole thing is too big and complex to get understand for everyone and then I think to build a library so everyone can use this easily with some minimum line of codes.

IT’S MY FIRST LIBRARY SO MAYBE IT HAS SOME BUGS IN IT SO IF YOU FACE ANY ISSUE THEN GO AND MAKE AN ISSUE IN THE GITHUB.

So without much-talking let’s start

Step 1

Copy the below code and add it to your project-level build file.

allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}

Step 2

Now copy the below code and past in your app-level build file where you add the dependency.

dependencies {
     implementation 'com.github.MonsterTechnoGits:WebViewAdblock:1.1'
   }

Now after adding this sync your project.

Step 3

Once you are done adding this now you have to ad one simple webview in your activity just add the webview tag in the layout xml like below.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Now fine it by find view by id in the java file.

WebView webView = findViewById(R.id.webView);

Step 3

Now you have to initialize the webview so just add this line of code after finding the view.

new AdBlockerWebView.init(this).initializeWebView(webView);

Step 4

Now we need to add setWebViewClient for the webview

webView.setWebViewClient(new Browser_home());

now need to add a class that handles this webView client and under this class, we need one override method which handles blocking ads.

So copy this full code and past below the onCrete of your java file

private class Browser_home extends WebViewClient {

        Browser_home() {}

        @SuppressWarnings("deprecation")
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

            return AdBlockerWebView.blockAds(view,url) ? AdBlocker.createEmptyResource() :
                    super.shouldInterceptRequest(view, url);

        }

    }

Here shouldInterceptRequest override method will handle blocking ads.

Step 4

Now add the loadurl in the concrete and pass one URL which you want to load. and add internet permission in manifest and then we are ready to go.

webView.loadUrl("https://www.monstertechnocodes.com");

Now run the application and you are done blocking ads in your webview application.

FULL CODE OF JAVA FILE

public class MainActivity extends AppCompatActivity {

    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.webView);
        new AdBlockerWebView.init(this).initializeWebView(webView);
        webView.setWebViewClient(new Browser_home());
        webView.loadUrl("https://www.monstertechnocodes.com");

    }

    private class Browser_home extends WebViewClient {

        Browser_home() {}

        @SuppressWarnings("deprecation")
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

            return AdBlockerWebView.blockAds(view,url) ? AdBlocker.createEmptyResource() :
                    super.shouldInterceptRequest(view, url);

        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

    }

}

Thanks for your time happy coding 😀

GitHub link -> WebViewAdblock

Posts created 41

81 thoughts on “WebView AdBlock android | Block ads when using WebView in android | Adblock for WebView

  1. Знаете ли вы?
    Команды тренера года АБА и НБА ни разу не стали в них финалистками.
    Жизненный путь абсолютного большинства звёзд известен заранее.
    Картина парада Победы, где руководство страны смещено на задний план, получила Сталинскую премию.
    В Чехословакии и СССР был свой «поцелуй победы».
    Убийца с руками-клешнями избежал тюрьмы, но позже сам был убит.

    http://arbeca.net/

  2. Уважаемые, есть кто то, кому интересны недорогие склады / контейнеры / офисы в 10 мин. от метро Теплый стан?
    От 3 до 350 м2 Территория охраняемая.
    Подьезд еврофур. Работаем круглосуточноо
    от 3000 руб. тел. 8 (916)292 95 95
    Наш сайт https://bit.ly/3j4sfvi

  3. [url=http://silagra24.com/]buy 100 mg silagra tablets[/url] [url=http://amoxicillinz.com/]amoxicillin 500 mg[/url] [url=http://priligytab.com/]buy priligy tablets[/url] [url=http://atorvastatin.us.com/]atorvastatin[/url] [url=http://doxycycline36.com/]buy doxycycline[/url] [url=http://furosemidelasix.com/]furosemide 20mg[/url] [url=http://amitriptyline365.com/]amitriptyline buy[/url] [url=http://celebrexcelecoxib.com/]can you buy celebrex in mexico[/url] [url=http://sildenafil36.com/]sildenafil prices in india[/url] [url=http://finpecia911.com/]finpecia online[/url] [url=http://avanatop.com/]avana 164[/url] [url=http://levitra36.com/]levitra generic coupon[/url] [url=http://dapoxetinetabs.com/]dapoxetine buy[/url] [url=http://cymbaltaduloxetine.com/]cymbalta[/url] [url=http://singulair.us.org/]singulair medicine[/url] [url=http://chloroquine.us.com/]chloroquine for malaria[/url] [url=http://xenical24.com/]xenical generic[/url] [url=http://hydroxychloroquine.us.org/]plaquenil buy[/url] [url=http://ciprofloxacin24.com/]order ciprofloxacin[/url] [url=http://ventolinh.com/]buy ventolin[/url]

  4. [url=https://ivermectin3.com/]ivermectin 0.5% lotion[/url] [url=https://cialis5.com/]purchase cialis with paypal[/url] [url=https://zoloft360.com/]zoloft generic 50mg[/url] [url=https://indocinrx.com/]indocin 50 mg tablets[/url] [url=https://zithromax360.com/]buying zithromax in mexico[/url] [url=https://glucophagge.com/]glucophage 1000mg tab[/url]

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top