Migrate to coroutines instead of Handler

This commit is contained in:
Mygod
2020-05-29 01:38:02 -04:00
parent 8307f9f8d4
commit df1ef04d18
2 changed files with 31 additions and 23 deletions

View File

@@ -1,7 +1,6 @@
package be.mygod.vpnhotspot.net.monitor
import android.util.LongSparseArray
import androidx.core.os.postDelayed
import be.mygod.vpnhotspot.net.Routing.Companion.IPTABLES
import be.mygod.vpnhotspot.room.AppDatabase
import be.mygod.vpnhotspot.room.TrafficRecord
@@ -9,6 +8,7 @@ import be.mygod.vpnhotspot.util.Event2
import be.mygod.vpnhotspot.util.RootSession
import be.mygod.vpnhotspot.util.parseNumericAddress
import be.mygod.vpnhotspot.widget.SmartSnackbar
import kotlinx.coroutines.*
import timber.log.Timber
import java.net.InetAddress
import java.util.concurrent.TimeUnit
@@ -16,7 +16,6 @@ import java.util.concurrent.TimeUnit
object TrafficRecorder {
private const val ANYWHERE = "0.0.0.0/0"
private var scheduled = false
private var lastUpdate = 0L
private val records = mutableMapOf<Pair<InetAddress, String>, TrafficRecord>()
val foregroundListeners = Event2<Collection<TrafficRecord>, LongSparseArray<TrafficRecord>>()
@@ -36,18 +35,21 @@ object TrafficRecorder {
if (records.remove(Pair(ip, downstream)) == null) Timber.w("Failed to find traffic record for $ip%$downstream.")
}
private var updateJob: Job? = null
private fun unscheduleUpdateLocked() {
RootSession.handler.removeCallbacksAndMessages(this)
scheduled = false
updateJob?.cancel()
updateJob = null
}
private fun scheduleUpdateLocked() {
if (scheduled) return
if (updateJob != null) return
val now = System.currentTimeMillis()
val minute = TimeUnit.MINUTES.toMillis(1)
var timeout = minute - now % minute
if (foregroundListeners.isNotEmpty() && timeout > 1000) timeout = 1000
RootSession.handler.postDelayed(timeout, this) { update(true) }
scheduled = true
updateJob = GlobalScope.launch(start = CoroutineStart.UNDISPATCHED) {
delay(timeout)
update(true)
}
}
fun rescheduleUpdate() = synchronized(this) {
@@ -122,7 +124,6 @@ object TrafficRecorder {
}
fun update(timeout: Boolean = false) {
synchronized(this) {
if (timeout) scheduled = false
if (records.isEmpty()) return
val timestamp = System.currentTimeMillis()
if (!timeout && timestamp - lastUpdate <= 100) return
@@ -133,6 +134,7 @@ object TrafficRecorder {
SmartSnackbar.make(e).show()
}
lastUpdate = timestamp
updateJob = null
scheduleUpdateLocked()
}
}

View File

@@ -1,11 +1,9 @@
package be.mygod.vpnhotspot.util
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import androidx.annotation.WorkerThread
import androidx.core.os.postDelayed
import com.topjohnwu.superuser.Shell
import kotlinx.coroutines.*
import timber.log.Timber
import java.util.*
import java.util.concurrent.TimeUnit
@@ -15,13 +13,9 @@ import kotlin.concurrent.withLock
class RootSession : AutoCloseable {
companion object {
private const val TAG = "RootSession"
val handler = Handler(HandlerThread("$TAG-HandlerThread").apply { start() }.looper)
private val monitor = ReentrantLock()
private fun onUnlock() {
if (monitor.holdCount == 1) instance?.startTimeout()
if (monitor.holdCount == 1) instance?.startTimeoutLocked()
}
private fun unlock() {
onUnlock()
@@ -36,7 +30,7 @@ class RootSession : AutoCloseable {
}
fun <T> use(operation: (RootSession) -> T) = monitor.withLock {
val instance = ensureInstance()
instance.haltTimeout()
instance.haltTimeoutLocked()
operation(instance).also { onUnlock() }
}
fun beginTransaction(): Transaction {
@@ -47,14 +41,14 @@ class RootSession : AutoCloseable {
unlock()
throw e
}
instance.haltTimeout()
instance.haltTimeoutLocked()
return instance.Transaction()
}
@WorkerThread
fun trimMemory() = monitor.withLock {
val instance = instance ?: return
instance.haltTimeout()
instance.haltTimeoutLocked()
instance.close()
}
@@ -85,10 +79,22 @@ class RootSession : AutoCloseable {
shell.close()
if (instance == this) instance = null
}
private fun startTimeout() = handler.postDelayed(TimeUnit.MINUTES.toMillis(5), this) {
monitor.withLock { close() }
private var timeoutJob: Job? = null
private fun startTimeoutLocked() {
check(timeoutJob == null)
timeoutJob = GlobalScope.launch(start = CoroutineStart.UNDISPATCHED) {
delay(TimeUnit.MINUTES.toMillis(5))
monitor.withLock {
close()
timeoutJob = null
}
}
}
private fun haltTimeoutLocked() {
timeoutJob?.cancel()
timeoutJob = null
}
private fun haltTimeout() = handler.removeCallbacksAndMessages(this)
/**
* Don't care about the results, but still sync.
@@ -141,7 +147,7 @@ class RootSession : AutoCloseable {
locked = true
ensureInstance()
}
shell.haltTimeout()
shell.haltTimeoutLocked()
revertCommands.forEach { shell.submit(it) }
} catch (e: RuntimeException) { // if revert fails, it should fail silently
Timber.d(e)