Going off the documentation for canOpenURL(), it doesn't check if the URL is available, only if there's an app available that can handle its scheme.
On Android, the URL has to be wrapped in an Intent to be able to open it. You can then check if an app is available for the Intent by using the PackageManager.
val intent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(url)
}
if (intent.resolveActivity(packageManager) != null) {
// url can be opened with startActivity(intent) or requireContext().startActivity(intent)
} else {
// ...
}
If this function is in a Fragment rather than Activity, prefix packageManager
with requireContext().
.
Edit:
You can check if it's possible to connect to the URL using a function like this (adapted from here):
suspend fun canConnect(url: String): Boolean = withContext(Dispatchers.IO) {
// We want to check the current URL
HttpURLConnection.setFollowRedirects(false)
val httpURLConnection = (URL(url).openConnection() as HttpURLConnection)
// We don't need to get data
httpURLConnection.requestMethod = "HEAD"
// Some websites don't like programmatic access so pretend to be a browser
httpURLConnection.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"
)
// We only accept response code 200
return@withContext try {
httpURLConnection.responseCode == HttpURLConnection.HTTP_OK
} catch (e: IOException) {
false
} catch (e: UnknownHostException){
false
}
}
It has to be done asynchronously since you're making a connection, or else you risk an Application Not Responding error. So I made it a suspend function that you can call from a coroutine.