Some of the most common uses for repeating alarms and background services is to schedule regular updates of application data from Internet resources, cache data, or execute long running downloads. But if you aren't connected to the Internet, or the connection is too slow to complete your download, why bother waking the device to schedule the update at all?
You can use the
ConnectivityManager to check that you're actually
connected to the Internet, and if so, what type of connection is in place.
Determine if you have an internet connection
There's no need to schedule an update based on an Internet resource if you aren't connected to
the Internet. The following snippet shows how to use the
to query the active network and 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 your 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 below, you can alter your refresh rate based on the bandwidth available.
val isWiFi: Boolean = activeNetwork?.type == ConnectivityManager.TYPE_WIFI
boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
Mobile data costs tend to be significantly higher than Wi-Fi, so in most cases, your app's update rate should be lower when on mobile connections. Similarly, downloads of significant size should be suspended until you have a Wi-Fi connection.
Having disabled your updates, it's important that you listen for changes in connectivity in order to resume them once an Internet connection has been established.
Monitor for changes in connectivity
Apps targeting Android 7.0 (API level 24) and higher do not receive
CONNECTIVITY_ACTION broadcasts if they
declare the broadcast receiver in their manifest. Apps will still
CONNECTIVITY_ACTION broadcasts if they register
and that context is still valid.