개발/Android

네트워크 연결 상태를 확인하는 함수

Patrick0422 2021. 11. 8. 17:33
private fun hasInternetConnection(): Boolean {
    val connectivityManager = getApplication<Application>().getSystemService(
        Context.CONNECTIVITY_SERVICE
    ) as ConnectivityManager

    val activeNetwork = connectivityManager.activeNetwork ?: return false
    val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false

    return when {
        capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
        capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
        capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
        else -> false
    }
}
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

강의를 들으면서 만든 함수인데, 인터넷 연결 상태를 확인하는 작업은 쓸 경우가 많을 것 같아 올려봅니다