The Android Developer Challenge is back! Submit your idea before December 2.

Monitor connectivity status and connection metering

You can use the ConnectivityManager to 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.

Kotlin

val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
val isConnected: Boolean = activeNetwork?.isConnectedOrConnecting == true

Java

ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();

Note: getActiveNetworkInfo() was deprecated in Android 10. Use NetworkCallbacks instead for apps that target Android 10 (API level 29) and higher.

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.

Kotlin

val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val isMetered = cm.isActiveNetworkMetered()

Java

ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isMetered = cm.isActiveNetworkMetered();

Note: If your app needs to support Android 4.0 (API level 15) and lower, use ConnectivityManagerCompat.isActiveNetworkMetered instead of ConnectivityManager.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.