I have found that there are two ways to detect if the current network is metered:
NetworkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)
NetworkCapabilitiesConnectivityManagerCompat.isActiveNetworkMetered
ConnectivityManagerCompatSo, what's the difference between these methods? And when to use each?
First of all: ConnectivityManagerCompat.isActiveNetworkMetered
is just the androidx
backport of the framework's ConnectivityManager.isActiveNetworkMetered
.
On platforms that have that method (API 16+), the compat version just calls the framework method directly. Otherwise, it tries to guess based on the connection type: Wi-Fi, Bluetooth, and Ethernet connections are assumed to be non-metered, while anything else is assumed to be metered. This guess isn't necessarily correct (Wi-Fi networks can be metered, for instance), but it's the best guess you can make on that API level. You should use this in the (unlikely these days) case where you need to target API 15 or below.
As far as the differences between ConnectivityManager.isActiveNetworkMetered
and NetworkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)
go: for the active data network, they are exactly the same, as the implementation simply calls that exact method.
However, because hasCapability
can be called on any network, it provides you more flexibility if you want the capabilities of networks other than the active data network.