You can use the
check that you're connected to the internet, and if you are, to determine what type of connection
is in place.
Determine whether you have an internet connection
You can't run an update based on an internet resource if you aren't connected to
the internet. The recommended way to schedule tasks that require internet connectivity is using
WorkManager. For more information, see
Schedule tasks with WorkManager. You can
also use the method shown in the following snippet to interactively query the active network to
determine if it has internet connectivity.
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork: NetworkInfo? = cm.activeNetworkInfo val isConnected: Boolean = activeNetwork?.isConnectedOrConnecting == true
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
Determine the type of internet connection
It's also possible to determine the type of internet connection currently available.
Device connectivity can be provided by mobile data, WiMAX, Wi-Fi, and Ethernet connections. By querying the type of the active network, as shown in the following code sample, you can change your app's behavior based on the bandwidth available.
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val isMetered = cm.isActiveNetworkMetered()
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); boolean isMetered = cm.isActiveNetworkMetered();
Mobile data costs tend to be significantly higher than Wi-Fi and Ethernet costs. When on a metered connection, you should try to reduce your app's data consumption, or even delay it until you are on a non-metered connection.