본문 바로가기

Kotlin

[ j android ] network 상태 항상 감지 (on,off)

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
반응형