Detect network connection type on Android

前端 未结 14 1338
后悔当初
后悔当初 2020-11-22 05:55

How do you detect the network connection type on Android?

Is it through ConnectivityManager.getActiveNetworkInfo().getType(), and is the answer limited

14条回答
  •  梦如初夏
    2020-11-22 06:41

    I use this simple code:

    fun getConnectionInfo(): ConnectionInfo {
        val cm = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    
        return if (cm.activeNetwork == null) {
            ConnectionInfo.NO_CONNECTION
        } else {
            if (cm.isActiveNetworkMetered) {
                ConnectionInfo.MOBILE
            } else {
                ConnectionInfo.WI_FI
            }
        }
    }
    

提交回复
热议问题