728x90
반응형
네트워크 상태를 항상 감지해보자
LTE 나 WIFI 가 꺼졌는지 켜졌는지 상태를 알 수 있다.
1. 네트워크 상태 체크하는 클래스를 만들어준다.
class NetworkConnection(
private val context: Context
): LiveData<Boolean>() {
private var connectivityManager: ConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private lateinit var networkCallback: ConnectivityManager.NetworkCallback
override fun onActive() {
super.onActive()
updateConnection()
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> {
connectivityManager.registerDefaultNetworkCallback(connectivityManagerCallback())
}
else -> {
val request = NetworkRequest.Builder().build()
connectivityManager.registerNetworkCallback(request, connectivityManagerCallback())
}
}
}
override fun onInactive() {
super.onInactive()
connectivityManager.unregisterNetworkCallback(networkCallback)
}
private fun connectivityManagerCallback(): ConnectivityManager.NetworkCallback {
networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onLost(network: Network) {
super.onLost(network)
postValue(false)
}
override fun onUnavailable() {
super.onUnavailable()
postValue(false)
}
override fun onAvailable(network: Network) {
super.onAvailable(network)
postValue(true)
}
}
return networkCallback
}
private fun updateConnection() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
postValue(connectivityManager.isDefaultNetworkActive)
}else {
val activeNetwork: NetworkInfo? = connectivityManager.activeNetworkInfo
postValue(activeNetwork?.isConnected)
}
}
}
2. activity에 observe를 추가해준다.
val networkConnect = NetworkConnection(this)
networkConnect.observe(this) { isConnected ->
if(!isConnected){
//네트워크 연결 안됨
}else{
//네트워크 연결됨
}
}
728x90
반응형
'Kotlin' 카테고리의 다른 글
[j android] Geocoder >> List<Address> 반환 값 (0) | 2022.03.04 |
---|---|
[ j android] 권한설정하기 (Permission) (0) | 2022.02.14 |
[ j android ] network 네트워크 상태 체크 (0) | 2021.12.23 |
[j android] Appbar에 뒤로가기 넣기 (0) | 2021.12.10 |
[j android] ListView 클릭 효과 (0) | 2021.10.20 |