Skip to content

Commit e944415

Browse files
committed
Fix: StrictMode policy violation: android.os.strictmode.UntaggedSocketViolation: Untagged socket detected; use TrafficStats.setTrafficStatsTag() to track all network usage
Signed-off-by: imknown <imknown@qq.com>
1 parent f6a5dd4 commit e944415

1 file changed

Lines changed: 29 additions & 14 deletions

File tree

  • app/src/main/java/net/imknown/android/forefrontinfo/ui/home/datasource

app/src/main/java/net/imknown/android/forefrontinfo/ui/home/datasource/LldDataSource.kt

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,11 @@ import net.imknown.android.forefrontinfo.BuildConfig
1515
import net.imknown.android.forefrontinfo.base.extension.isChinaMainlandTimezone
1616
import net.imknown.android.forefrontinfo.ui.common.LldManager
1717
import net.imknown.android.forefrontinfo.ui.common.isAtLeastAndroid16
18+
import okhttp3.Call
19+
import okhttp3.EventListener
20+
import okhttp3.Protocol
1821
import java.io.IOException
22+
import java.net.InetSocketAddress
1923
import java.net.Proxy
2024
import java.net.ProxySelector
2125
import java.net.SocketAddress
@@ -45,22 +49,33 @@ class LldDataSource {
4549

4650
val client = HttpClient(OkHttp) {
4751
engine {
48-
addInterceptor { chain ->
49-
val thread = Thread.currentThread()
50-
val id = if (isAtLeastAndroid16()) {
51-
thread.threadId()
52-
} else {
53-
@Suppress("DEPRECATION")
54-
thread.id
55-
}.toInt()
56-
TrafficStats.setThreadStatsTag(id)
52+
config {
53+
// https://github.com/square/okhttp/issues/3537#issuecomment-3391015783
54+
val eventListener = object : EventListener() {
55+
override fun connectStart(
56+
call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy
57+
) {
58+
val thread = Thread.currentThread()
59+
val id = if (isAtLeastAndroid16()) {
60+
thread.threadId()
61+
} else {
62+
@Suppress("DEPRECATION")
63+
thread.id
64+
}.toInt()
65+
TrafficStats.setThreadStatsTag(id)
66+
}
5767

58-
val request = chain.request()
59-
val response = chain.proceed(request)
60-
response
61-
}
68+
override fun connectEnd(
69+
call: Call,
70+
inetSocketAddress: InetSocketAddress,
71+
proxy: Proxy,
72+
protocol: Protocol?
73+
) {
74+
TrafficStats.clearThreadStatsTag()
75+
}
76+
}
77+
eventListener(eventListener)
6278

63-
config {
6479
// region [Proxy]
6580
// Fix: java.lang.IllegalArgumentException: port out of range:-1
6681
// Steps to reproduce (small probability): Change Wifi proxy from "Manual" to "PAC"

0 commit comments

Comments
 (0)