Created
July 7, 2020 10:32
-
-
Save SergeyBurlaka/eabee844d838ae958b2084463c8b6c50 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://stackoverflow.com/a/53243938/6352712 | |
@IntRange(from = 0, to = 3) | |
fun getConnectionType(context: Context): Int { | |
var result = 0 // Returns connection type. 0: none; 1: mobile data; 2: wifi | |
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager? | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { | |
cm?.run { | |
cm.getNetworkCapabilities(cm.activeNetwork)?.run { | |
if (hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { | |
result = 2 | |
} else if (hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) { | |
result = 1 | |
} else if (hasTransport(NetworkCapabilities.TRANSPORT_VPN)){ | |
result = 3 | |
} | |
} | |
} | |
} else { | |
cm?.run { | |
cm.activeNetworkInfo?.run { | |
if (type == ConnectivityManager.TYPE_WIFI) { | |
result = 2 | |
} else if (type == ConnectivityManager.TYPE_MOBILE) { | |
result = 1 | |
} else if(type == ConnectivityManager.TYPE_VPN) { | |
result = 3 | |
} | |
} | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment