Android Flow监听网络状态
Posted 安果移不动
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Flow监听网络状态相关的知识,希望对你有一定的参考价值。
这些个api要用到api24
你可以往下写兼容代码 也可以先不去适配使用minSdk这样
minSdk 24
用到了一个接口
package com.example.prettynumber
import kotlinx.coroutines.flow.Flow
//监听状态。并返回流
interface ConnectivityObserver
fun observer(): Flow<Status>
enum class Status
Available,Unavailable,Losing,Lost
实现
package com.example.prettynumber
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.os.Build
import androidx.annotation.RequiresApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
class NetworkConnectivityObserver(private val context: Context) : ConnectivityObserver
private val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
@RequiresApi(Build.VERSION_CODES.N)
override fun observer(): Flow<ConnectivityObserver.Status>
return callbackFlow
val callbacks = object : ConnectivityManager.NetworkCallback()
override fun onAvailable(network: Network)
super.onAvailable(network)
launch
send(ConnectivityObserver.Status.Available)
override fun onLosing(network: Network, maxMsToLive: Int)
super.onLosing(network, maxMsToLive)
launch
send(ConnectivityObserver.Status.Losing)
override fun onLost(network: Network)
super.onLost(network)
//更新当前事件
launch
send(ConnectivityObserver.Status.Lost)
override fun onUnavailable()
super.onUnavailable()
launch
send(ConnectivityObserver.Status.Unavailable)
//注册事件,需要表明 要大于24才行哦
connectivityManager.registerDefaultNetworkCallback(callbacks)
//解除注册事件
awaitClose
connectivityManager.unregisterNetworkCallback(callbacks)
//防止重复注册事件
.distinctUntilChanged()
使用
class MainActivity : ComponentActivity()
private lateinit var connectivityObserver: ConnectivityObserver
private val TAG = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
connectivityObserver = NetworkConnectivityObserver(applicationContext)
connectivityObserver.observer().onEach
Log.e(TAG, "Status is: $it")
.launchIn(lifecycleScope)
setContent
PrettyNumberTheme
val status by connectivityObserver.observer().collectAsState(
initial = ConnectivityObserver.Status.Unavailable
)
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
)
Text(text = "Network status:$status")
以上是关于Android Flow监听网络状态的主要内容,如果未能解决你的问题,请参考以下文章
Android使用BroadcastReceiver监听网络状态