web服务监测网络变化,及时更新IP

pull/1857/head
kunfei 3 years ago
parent c0ba24b6aa
commit 34a371fdc2
  1. 21
      app/src/main/java/io/legado/app/receiver/NetworkChangedListener.kt

@ -23,15 +23,22 @@ class NetworkChangedListener(private val context: Context) {
return@lazy null
}
fun register() {
private val networkCallback: ConnectivityManager.NetworkCallback? by lazy {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(
object : ConnectivityManager.NetworkCallback() {
return@lazy object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
onNetworkChanged?.invoke()
}
}
)
}
return@lazy null
}
fun register() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
networkCallback?.let {
connectivityManager.registerDefaultNetworkCallback(it)
}
} else {
receiver?.let {
context.registerReceiver(it, it.filter)
@ -40,10 +47,16 @@ class NetworkChangedListener(private val context: Context) {
}
fun unRegister() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
networkCallback?.let {
connectivityManager.unregisterNetworkCallback(it)
}
} else {
receiver?.let {
context.unregisterReceiver(it)
}
}
}
inner class NetworkChangedReceiver : BroadcastReceiver() {

Loading…
Cancel
Save