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

View File

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