Skip to content

Commit c1d0dea

Browse files
committed
Performance Optimized
1 parent 163d29c commit c1d0dea

5 files changed

Lines changed: 68 additions & 36 deletions

File tree

README.MD

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,11 @@ Add AdBlockerWebview In your layout
3535
In your Activity or Fragment
3636

3737
```Kotlin
38-
webview.setAdBlockEnabled(true)
38+
AdBlockerUtil.getInstance().initialize(context)
39+
webview.setAdBlockerEnabled(true)
3940
webview.loadUrl("https://google.com")
4041
```
4142

42-
You can also extend `AdBlockerWebView` to add additional functionality
43+
You can also extend `AdBlockerWebView` to include additional functionality
4344

4445
For a complete example, see the sample app

adblockerwebview/build.gradle

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ android {
88
defaultConfig {
99
minSdkVersion 14
1010
targetSdkVersion 29
11-
versionCode 2
12-
versionName "0.1.1"
11+
versionCode 3
12+
versionName "0.1.2"
1313

1414
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
1515

adblockerwebview/src/main/java/com/islamdidarmd/adblockerwebview/AdBlockerUtil.kt

Lines changed: 50 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,56 @@ package com.islamdidarmd.adblockerwebview
22

33
import android.content.Context
44
import android.net.Uri
5+
import android.util.Log
56
import android.webkit.WebResourceResponse
67
import kotlinx.coroutines.*
8+
import kotlinx.coroutines.channels.awaitClose
9+
import kotlinx.coroutines.flow.Flow
10+
import kotlinx.coroutines.flow.callbackFlow
11+
import kotlinx.coroutines.flow.catch
12+
import kotlinx.coroutines.flow.collect
713
import okhttp3.*
14+
import okio.Okio
815
import okio.buffer
916
import okio.source
10-
import java.io.ByteArrayInputStream
11-
import java.io.IOException
12-
import java.io.InputStream
17+
import java.io.*
18+
import java.net.URL
19+
import kotlin.coroutines.suspendCoroutine
20+
21+
class AdBlockerUtil private constructor() {
22+
private var isStillLoading: Boolean = false
23+
24+
private val TAG = "AdBlockerUtil"
1325

14-
class AdBlockerUtil(context: Context) {
15-
val TAG = "AdBlockerUtil"
1626
private val AD_HOSTS_FILE_NAME = "adblocker_webview_hosts.txt"
1727
private val hostsList = mutableListOf<String>()
1828

19-
init {
20-
CoroutineScope(Dispatchers.Default).launch {
21-
//loading hostname from asset
22-
withContext(Dispatchers.IO) {
23-
try {
24-
loadHostsFromInputStream(context.assets.open(AD_HOSTS_FILE_NAME))
25-
} catch (e: Exception) {
26-
e.printStackTrace()
27-
}
28-
}
29-
delay(200)
30-
//updating list from server
29+
companion object {
30+
private val mInstance by lazy { AdBlockerUtil() }
31+
fun getInstance(): AdBlockerUtil {
32+
return mInstance
33+
}
34+
}
35+
36+
fun initialize(context: Context, scope: CoroutineScope = CoroutineScope(Dispatchers.Default)) {
37+
scope.launch {
3138
loadHostFromServer()
39+
.collect { value: InputStream? ->
40+
try {
41+
val stream = value ?: context.assets.open(AD_HOSTS_FILE_NAME)
42+
loadHostsFromInputStream(stream)
43+
} catch (e: Exception) {
44+
e.printStackTrace()
45+
}
46+
}
3247
}
3348
}
3449

3550
fun isAd(url: String?): Boolean {
51+
if (isStillLoading) {
52+
Log.e(TAG, "isAd: Host entries are still loading.")
53+
return false
54+
}
3655
if (url == null) return false
3756
val host = Uri.parse(url).host ?: return false
3857

@@ -48,11 +67,8 @@ class AdBlockerUtil(context: Context) {
4867
return WebResourceResponse("text/plain", "utf-8", ByteArrayInputStream("".toByteArray()))
4968
}
5069

51-
private fun loadHostsFromInputStream(inputStream: InputStream?) {
52-
if (inputStream == null) {
53-
return
54-
}
55-
70+
private fun loadHostsFromInputStream(inputStream: InputStream) {
71+
isStillLoading = true
5672
val tempList: MutableList<String> = ArrayList()
5773

5874
inputStream.source().buffer().use { source ->
@@ -64,9 +80,11 @@ class AdBlockerUtil(context: Context) {
6480

6581
hostsList.clear()
6682
hostsList.addAll(tempList)
83+
isStillLoading = false
6784
}
6885

69-
private fun loadHostFromServer() {
86+
@ExperimentalCoroutinesApi
87+
private fun loadHostFromServer() = callbackFlow<InputStream?> {
7088
val url = "https://pgl.yoyo.org/as/serverlist.php?hostformat=nohtml&showintro=0"
7189
val client = OkHttpClient.Builder().build()
7290

@@ -76,15 +94,23 @@ class AdBlockerUtil(context: Context) {
7694
try {
7795
client.newCall(request).enqueue(object : Callback {
7896
override fun onResponse(call: Call, response: Response) {
79-
loadHostsFromInputStream(response.body?.byteStream())
97+
offer(response.body?.byteStream())
98+
close()
8099
}
81100

82101
override fun onFailure(call: Call, e: IOException) {
83102
e.printStackTrace()
103+
offer(null)
104+
close()
84105
}
85106
})
86107
} catch (e: Exception) {
87108
e.printStackTrace()
109+
110+
offer(null)
111+
close()
88112
}
113+
114+
awaitClose()
89115
}
90116
}

adblockerwebview/src/main/java/com/islamdidarmd/adblockerwebview/AdBlockerWebView.kt

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,11 @@ open class AdBlockerWebView : WebView {
2525
defStyleAttrs
2626
)
2727

28-
private val adBlockerUtil by lazy {
29-
AdBlockerUtil(context)
30-
}
28+
private val adBlockerUtil = AdBlockerUtil.getInstance()
3129

32-
fun setAdBlockEnabled(enabled: Boolean) {
33-
this._blockAds = enabled
34-
if (BuildConfig.DEBUG) Log.d(TAG, "setAdBlockEnabled $enabled")
30+
fun setAdBlockerEnabled(isEnabled: Boolean) {
31+
this._blockAds = isEnabled
32+
if (BuildConfig.DEBUG) Log.d(TAG, "setAdBlockEnabled $isEnabled")
3533
}
3634

3735
init {
@@ -215,7 +213,11 @@ open class AdBlockerWebView : WebView {
215213
resend: Message?
216214
) {
217215
client?.onFormResubmission(view, dontResend, resend)
218-
super.onFormResubmission(view, dontResend, resend)
216+
try {
217+
super.onFormResubmission(view, dontResend, resend)
218+
} catch (e: Exception) {
219+
e.printStackTrace()
220+
}
219221
}
220222

221223
override fun onLoadResource(view: WebView?, url: String?) {

app/src/main/java/com/islamdidarmd/adblockerwebviewsample/MainActivity.kt

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import android.webkit.WebChromeClient
88
import android.webkit.WebView
99
import android.webkit.WebViewClient
1010
import androidx.appcompat.app.AppCompatActivity
11+
import com.islamdidarmd.adblockerwebview.AdBlockerUtil
1112
import kotlinx.android.synthetic.main.activity_main.*
1213

1314
class MainActivity : AppCompatActivity() {
@@ -17,6 +18,8 @@ class MainActivity : AppCompatActivity() {
1718
super.onCreate(savedInstanceState)
1819
setContentView(R.layout.activity_main)
1920

21+
AdBlockerUtil.getInstance().initialize(this)
22+
2023
webview.settings.apply {
2124
javaScriptEnabled = true
2225
domStorageEnabled = true
@@ -42,7 +45,7 @@ class MainActivity : AppCompatActivity() {
4245
}
4346

4447
switchAdblock.setOnCheckedChangeListener { buttonView, isChecked ->
45-
webview.setAdBlockEnabled(isChecked)
48+
webview.setAdBlockerEnabled(isChecked)
4649
}
4750

4851
btnGo.setOnClickListener {

0 commit comments

Comments
 (0)