Skip to content

Instantly share code, notes, and snippets.

@tfcporciuncula
Created October 22, 2024 16:26
Show Gist options
  • Save tfcporciuncula/99618ec92810c9ae8f5e4fa0b57d078c to your computer and use it in GitHub Desktop.
Save tfcporciuncula/99618ec92810c9ae8f5e4fa0b57d078c to your computer and use it in GitHub Desktop.
CompatConnectedConstraint.kt
/**
* On API 26+, whenever we pass [NetworkType.CONNECTED] as WorkManager's required network type, the
* constraint will only be met if the network is also validated
* ([NetworkCapabilities.NET_CAPABILITY_VALIDATED]). This takes advantage of the new
* [Constraints.Builder.setRequiredNetworkRequest] API to create a constraint that requires a
* network connection without requiring it to be validated.
*/
fun Constraints.Builder.setCompatConnectedConstraint(): Constraints.Builder {
// setRequiredNetworkRequest doesn't work before API 28, so if we're on API 26+, where we know
// WorkManager will also require the network to be validated, the best we can do is to simply
// remove the network constraint.
if (Build.VERSION.SDK_INT >= 26 && Build.VERSION.SDK_INT < 28) {
return setRequiredNetworkType(NetworkType.NOT_REQUIRED)
}
val networkRequest =
NetworkRequest.Builder()
.apply {
if (Build.VERSION.SDK_INT >= 30) {
clearCapabilities()
} else {
// Our only option here is to remove all the default capabilities one by one.
removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
removeCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED)
removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
}
addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
}
.build()
val networkTypeFallback = NetworkType.CONNECTED
return setRequiredNetworkRequest(networkRequest, networkTypeFallback)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment