Prevent callbacks called in main

This commit is contained in:
Mygod
2019-07-30 10:08:12 +08:00
parent 4f7f778114
commit 193a918fce
2 changed files with 35 additions and 27 deletions

View File

@@ -2,6 +2,8 @@ package be.mygod.vpnhotspot.net.monitor
import android.content.SharedPreferences
import be.mygod.vpnhotspot.App.Companion.app
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
abstract class FallbackUpstreamMonitor private constructor() : UpstreamMonitor() {
companion object : SharedPreferences.OnSharedPreferenceChangeListener {
@@ -21,19 +23,21 @@ abstract class FallbackUpstreamMonitor private constructor() : UpstreamMonitor()
fun unregisterCallback(callback: Callback) = synchronized(this) { monitor.unregisterCallback(callback) }
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
if (key == KEY) synchronized(this) {
val old = monitor
val callbacks = synchronized(old) {
val callbacks = old.callbacks.toList()
old.callbacks.clear()
old.destroyLocked()
callbacks
}
val new = generateMonitor()
monitor = new
for (callback in callbacks) {
callback.onLost()
new.registerCallback(callback)
if (key == KEY) GlobalScope.launch { // prevent callback called in main
synchronized(this) {
val old = monitor
val callbacks = synchronized(old) {
val callbacks = old.callbacks.toList()
old.callbacks.clear()
old.destroyLocked()
callbacks
}
val new = generateMonitor()
monitor = new
for (callback in callbacks) {
callback.onLost()
new.registerCallback(callback)
}
}
}
}

View File

@@ -3,6 +3,8 @@ package be.mygod.vpnhotspot.net.monitor
import android.content.SharedPreferences
import android.net.LinkProperties
import be.mygod.vpnhotspot.App.Companion.app
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.lang.UnsupportedOperationException
import java.net.InetAddress
import java.util.*
@@ -26,20 +28,22 @@ abstract class UpstreamMonitor {
fun unregisterCallback(callback: Callback) = synchronized(this) { monitor.unregisterCallback(callback) }
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
if (key == KEY) synchronized(this) {
val old = monitor
val (active, callbacks) = synchronized(old) {
val active = old.currentIface != null
val callbacks = old.callbacks.toList()
old.callbacks.clear()
old.destroyLocked()
Pair(active, callbacks)
}
val new = generateMonitor()
monitor = new
for (callback in callbacks) {
if (active) callback.onLost()
new.registerCallback(callback)
if (key == KEY) GlobalScope.launch { // prevent callback called in main
synchronized(this) {
val old = monitor
val (active, callbacks) = synchronized(old) {
val active = old.currentIface != null
val callbacks = old.callbacks.toList()
old.callbacks.clear()
old.destroyLocked()
Pair(active, callbacks)
}
val new = generateMonitor()
monitor = new
for (callback in callbacks) {
if (active) callback.onLost()
new.registerCallback(callback)
}
}
}
}